Reputation: 7267
i am trying to read the txt file and add up row values i.e i am passing the parameters to java code. it should print the line numbers of added values
i am passing filename and int value to java program.
for ex: read.txt
contains
2
2
3
4
4
6
7
7
8
8
9
0
now i am passing parameter as 5, so it should add up the rows and print the line number and it should print the line number if the sum >= 5
for ex
2+2+3 = 7 is > 5
because the last number added up is 3 and it is in line number 3
so it should print line number 3
4+4 = 8 is > 5
so it should print line number 3
6 is > 5
so it should print line number 6
because its in line number 6
and so on.. how can i do this?
here is what i have tried
code:
import java.io.*;
class CountR
{
public static void main(String args[])
{
setForSum("read.txt",3);
}
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;
while ((strLine = br.readLine()) != null)
{
i++;
if(param2 == Integer.parseInt(strLine))
{
System.out.println(i);
}
}
in.close();
}
catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
}
}
Upvotes: 0
Views: 152
Reputation: 27346
First thing I've noticed, is this if statement
is only going to work if you land on your specified number, exactly.
if(param2 == Integer.parseInt(strLine))
{
System.out.println(i);
}
Should be:
if(param2 >= Integer.parseInt(strLine))
{
System.out.println(i);
}
Secondly, you're not totalling up the values, are you? You're just reading each value, so declare some value outside of the loop:
int currentTotal = 0;
then in the loop:
currentTotal += Integer.valueOf(strLine);
THEN use currentTotal
in your statement:
if(currentTotal >= Integer.parseInt(strLine))
{
System.out.println("Line Number " + i);
}
And as Heuster
mentioned, make sure you're resetting currentTotal
back to 0 inside your if statement!
Upvotes: 1