[英]get current position(index) while reading a file
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.当条件为真时,如何获取
num
的位置(索引)。
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();
}
You could add a separate counter, position
, which always counts, outside the if
:您可以在
if
之外添加一个单独的计数器position
,它始终计数:
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++;
}
while((numm=br.read()) != -1 && Character.getNumericValue(numm) != num) {
count++;
}
if(numm != -1){
System.out.println(count);
}else{
// Position is the end of input
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.