Reputation: 160
I have a text file like so:
1 2
3 7
5 8
with 2 numbers on each row. I want to do something different with the first number and the second number. I'm trying to scan through the text file and print the numbers to make sure that I scanned it right. However, only the first two numbers show up (1 4), then an error says:
"java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:858)
at java.base/java.util.Scanner.next(Scanner.java:1497)
at java.base/java.util.Scanner.nextInt(Scanner.java:2161)
at java.base/java.util.Scanner.nextInt(Scanner.java:2115)
at com.company.SCC.input(SCC.java:30)
at com.company.SCC.<init>(SCC.java:15)
at com.company.Main.main(Main.java:11)"
I don't understand what the problem is and how to scan the document row by row (I recycled the code for the Scanner and it was previously working). I'm not sure what I'm doing wrong, any help would be appreciated.
try {
String file = "testcase1.txt";
FileReader in = new FileReader(file);
BufferedReader br = new BufferedReader(in);
String s;
int x;
while ((s = br.readLine()) != null) {
Scanner sca = new Scanner(s);
x = sca.nextInt();
graph.addVertex(x);
int y = sca.nextInt();
graph.addAdjvex(x, y);
System.out.println(x + " " + y);
}
} catch (Exception e) {
e.printStackTrace();
}
Upvotes: 1
Views: 3560
Reputation: 416
Try
try {
File file = new File("testcase1.txt");
Scanner sc = new Scanner(file);
int x, y;
while (sc.hasNextLine()) {
x = sc.nextInt();
y = sc.nextInt()
graph.addVertex(x);
graph.addAdjvex(x, y);
System.out.println(x + " " + y);
}
sc.close();
} catch (Exception e) {
e.printStackTrace();
}
Upvotes: 1
Reputation: 6309
try {
File file = new File("testcase1.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
int x = sc.nextInt();
int y = sc.nextInt();
sc.nextLine();
graph.addVertex(x);
graph.addAdjvex(x, y);
System.out.println(x + " " + y);
}
sc.close()
} catch (Exception e) {
e.printStackTrace();
}
Upvotes: 1