ErDevFy
ErDevFy

Reputation: 105

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.

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

Answers (2)

tevemadar
tevemadar

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

Mady Daby
Mady Daby

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

Related Questions