2012-01-25 13 views
2

這裏是我的代碼:錯誤而重定向從文件輸入

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) 

幫我指出錯誤。

回答

4

請勿在每種方法中創建掃描儀對象。傳遞您創建的第一個Scanner對象。

這裏是一個應該解決的問題更改列表:

--- 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--; 
+0

謝謝,你的技巧工作,但我仍然沒有得到,爲什麼從文件重定向輸入沒有奏效,但鍵盤輸入罰款? –

+0

我認爲這與Scanner在內部維護緩衝區的方式有關。事實上,當我複製一次性粘貼整個輸入時,實際上通過鍵盤輸入不適用於我。只有我一個一個輸入輸入,它才適用於我。也許當你一次性完成整個輸入時,你創建的第一個Scanner對象將獲得緩衝區中的全部輸入,然後另外兩個Scanner對象獲得空的緩衝區。 –

+0

@SusamPal - 我認爲你是對的。這將解釋不同的行爲。 –

1

爲什麼要創建3個掃描儀?可能的是,它是在線

1)P = sc.nextInt();
2)Q = sc.nextInt();

窒息因爲只有1 INT輸入在管線1被讀出,然後第2行是試圖掃描nextInt( )爲空行。

我不知道爲什麼這將工作時手工輸入,除非輸入是在不同的順序。

+0

同樣的原因,我不明白。爲什麼當我通過鍵盤輸入時,它的工作正常,而順序完全相同。 –

0

您不應該使用<重定向輸入。您需要使用掃描儀類從文件讀取。

File file = new File("data.txt"); 
Scanner scanner = new Scanner(file); 
while (scanner.hasNextLine()) { 
//logic 
} 
+1

使用'<來重定向輸入沒有任何錯誤。重定向和管道是向從stdin讀取的程序提供輸入的常用方式。掃描儀(System.in)對象不關心輸入是否來自鍵盤,重定向或管道,只要它在標準輸入上得到輸入即可。 –