3
在這段代碼中,我試圖打印起始行號碼。在這裏我正在讀取文本文件中的值並將這些值相加。但我正在嘗試從它開始計數的位置獲取行號..如何使用java打印起始行號碼
我該怎麼做?
代碼
import java.io.*;
class CountR
{
public static void main(String args[])
{
setForSum("read.txt",7);
}
public static void setForSum(String filename,int param2)
{
try
{
FileInputStream fstream = new FileInputStream(filename);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
int i = 0;
int sum=0;
int startline=0;
System.out.println(param2+": Is in");
while ((strLine = br.readLine()) != null)
{
++i;
startline = i;
int line = Integer.parseInt(strLine);
sum=sum+line;
System.out.println("Sum= "+sum);
if(sum>=param2)
{
/* System.out.println("line number : "+i);*/
System.out.println("Start line number :"+startline+" End line number:" +i);
sum =0;
}
}
in.close();
}
catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
}
}
read.txt
文件
1
2
3
4
1
2
3
1
2
3
1
2
3
1
2
3
1
2
3
1
2
3
1
2
3
我現在得到的輸出是這樣的。
Sum= 1
Sum= 3
Sum= 6
Sum= 10
Start line number :4 End line number:4
Sum= 1
Sum= 3
Sum= 6
Sum= 7
Start line number :8 End line number:8
Sum= 2
Sum= 5
Sum= 6
Sum= 8
Start line number :12 End line number:12
Sum= 3
Sum= 4
Sum= 6
Sum= 9
Start line number :16 End line number:16
Sum= 1
Sum= 3
Sum= 6
Sum= 7
Start line number :20 End line number:20
Sum= 2
Sum= 5
Sum= 6
Sum= 8
Start line number :24 End line number:24
Sum= 3
但應
Sum= 1
Sum= 3
Sum= 6
Sum= 10
Start line number :1 End line number:4
Sum= 1
Sum= 3
Sum= 6
Sum= 7
Start line number :5 End line number:8
Sum= 2
Sum= 5
Sum= 6
Sum= 8
Start line number :9 End line number:12
Sum= 3
Sum= 4
Sum= 6
Sum= 9
Start line number :13 End line number:16
Sum= 1
Sum= 3
Sum= 6
Sum= 7
Start line number :17 End line number:20
Sum= 2
Sum= 5
Sum= 6
Sum= 8
Start line number :21 End line number:24
Sum= 3
你意識到'java.io.LineNumberReader'類? – EJP