Reputation: 105
I want to read a file that has one line.
How can I get the position(index) of the num
when the condition is true.
Scanner s = new Scanner(System.in);
System.out.println("Please enter a number");
int num = s.nextInt();
try {
File file = new File("1000.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
StringBuffer sb = new StringBuffer();
int numm;
int count = 0;
while ((numm = br.read()) != -1) {
if (Character.getNumericValue(numm) == num) {
//how could I get the position of num when the condition is true.
count++;
}
}
System.out.println(count);
br.close();
fr.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
Upvotes: 0
Views: 677
Reputation: 13195
You could add a separate counter, position
, which always counts, outside the if
:
int numm;
int count = 0;
int position = 0;
while ((numm = br.read()) != -1) {
if (Character.getNumericValue(numm) == num) {
//how could I get the position of num when the condition is true.
count++;
}
position++;
}
Upvotes: 1
Reputation: 1269
while((numm=br.read()) != -1 && Character.getNumericValue(numm) != num) {
count++;
}
if(numm != -1){
System.out.println(count);
}else{
// Position is the end of input
}
Upvotes: 0