问题
Here's my code:
import java.util.Scanner;
class Graph{
boolean [][]array;
int N;
Graph (){
array = new boolean [1001][1001];
N=0;
}
void read_graph() {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
sc.nextLine();
String str;
String []substr;
for (int K=1; K<=N; K++){
str = sc.nextLine();
substr = str.split(" ");
for (int I=0; I<substr.length; I++)
System.out.println(substr[0]+" "+substr[I]);
}
}
void query(){
Scanner sc = new Scanner(System.in);
int P, Q;
int counter = 0;
boolean flag = true;
while (flag){
counter++;
P = sc.nextInt();
Q = sc.nextInt();
sc.nextLine();
if ( P == Q && P == 0 )
flag =false;
else {
if (Q == 1)
System.out.println("DFS done");
else
System.out.println("Bfs done");
}
}
}
}
class demo{
public static void main( String [] args ){
Graph G= new Graph();
Scanner sc = new Scanner(System.in);
int numGraphs = sc.nextInt();
while (numGraphs>0){
G.read_graph();
G.query();
numGraphs--;
}
}
}
Here's the Input data:
1
6
1 2 3 4
2 2 3 6
3 2 1 2
4 1 1
5 0
6 1 2
5 1
1 0
1 0
0 0
When I give this input data with keyboard it works fine but when I saved this input to file and redirected this as input(in linux using '<'), it throws error message.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:855)
at java.util.Scanner.next(Scanner.java:1478)
at java.util.Scanner.nextInt(Scanner.java:2108)
at java.util.Scanner.nextInt(Scanner.java:2067)
at Graph.read_graph(b.java:13)
at demo.main(b.java:56)
Help me in pointing out the mistake.
回答1:
Don't create a Scanner object in every method. Pass the first Scanner object you have created around.
Here is a list of changes that should fix the issue:
--- demo-old.java 2012-01-25 23:12:54.000000000 +0530
+++ demo.java 2012-01-25 23:13:45.000000000 +0530
@@ -10,4 +10,3 @@
-void read_graph() {
- Scanner sc = new Scanner(System.in);
+void read_graph(Scanner sc) {
N = sc.nextInt();
@@ -26,4 +25,3 @@
-void query(){
-Scanner sc = new Scanner(System.in);
+void query(Scanner sc){
int P, Q;
@@ -53,4 +51,4 @@
while (numGraphs>0){
- G.read_graph();
- G.query();
+ G.read_graph(sc);
+ G.query(sc);
numGraphs--;
回答2:
Why are you creating 3 scanners? It is possible that it is choking in the lines
1) P = sc.nextInt();
2) Q = sc.nextInt();
because the input with only 1 int is being read in line 1 and then line 2 is trying to scan the nextInt() for an empty line.
I have no idea why this would work when inputing by hand, unless the input is in a different order.
回答3:
You should not use <
to redirect input. You need to use scanner class to read from file.
File file = new File("data.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
//logic
}
来源:https://stackoverflow.com/questions/9007322/error-while-redirecting-the-input-from-file