try {
Scanner sc = new Scanner(new File("testing.txt"));
while (sc.hasNextInt()){
int i = sc.nextInt();
//timing.add(i);
System.out.println(i);
}
sc.close();
}catch (FileNotFoundException e) {
e.printStackTrace();
}
The text file does have int and strings in it. I can get it to print words from the text file, but not the numbers.
The text file includes the following:
Michael 3000
7000 Bilbo
I like the number 2000 do you?
No, I like 9000
Your first value ("Michael") isn't an integer, therefore it never gets inside of the body of the loop.
Perhaps you want to change the code to loop until it reaches the end of the file, reading and printing integers, but consuming (without printing) non-integer values. So something like this:
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(new File("test.txt"));
while (sc.hasNext()) {
if (sc.hasNextInt()) {
System.out.println(sc.nextInt());
} else {
// Just consume the next token
sc.next();
}
}
sc.close();
}
}
See more on this question at Stackoverflow