這裏是我的代碼:錯誤而重定向從文件輸入
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--;
}
}
}
這裏的輸入數據:
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
當我給帶鍵盤,它工作正常此輸入數據,但是當我保存這個輸入將其作爲輸入文件並重定向(在Linux中使用'<'),它會拋出錯誤消息。
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)
幫我指出錯誤。
謝謝,你的技巧工作,但我仍然沒有得到,爲什麼從文件重定向輸入沒有奏效,但鍵盤輸入罰款? –
我認爲這與Scanner在內部維護緩衝區的方式有關。事實上,當我複製一次性粘貼整個輸入時,實際上通過鍵盤輸入不適用於我。只有我一個一個輸入輸入,它才適用於我。也許當你一次性完成整個輸入時,你創建的第一個Scanner對象將獲得緩衝區中的全部輸入,然後另外兩個Scanner對象獲得空的緩衝區。 –
@SusamPal - 我認爲你是對的。這將解釋不同的行爲。 –