2016-01-20 150 views
0

所以我現在編程Snake,我有一個方法來從控制檯讀取一個整數值。
當我的方法拋出一個錯誤 - 或至少當我回到那個方法時 - 它不會從輸入中讀入新行,而只是傳遞一個空字符串。
這裏是我的代碼:JAVA:掃描儀不讀取下一行//返回空字符串

static int readInInt() 
{ 
    //We Read in the next line the user enters 
    String s = sc.nextLine(); 
    //x returns -1 if mistake happens 
    int x = -1; 

    try 
    { 
     //Now we try to parse that int 
     x = Integer.parseInt(s); 
     x = Math.abs(x); 
     System.out.println("Setting the speed to " + (x*100) + "ms."); 
    } 
    catch(NumberFormatException ex) 
    { 
     //If we can't parse it we try to get the ints with a regex and then parse it 
     System.out.println("Du hast eine nummer eingetippt die das System nicht analysieren kann."); 
     System.out.println("Das System probiert jetzt die Nummer die du eingetippt hast über umwege zu Analysieren."); 
     s = s.replaceAll("[^-?0-9]+", ""); 
     try 
     { 
      x = Integer.parseInt(s); 
     } 
     catch(Exception e) 
     { 
      //and if that doesnt work we just say Error! 
      System.out.println("Error Handling didn't work.\n" 
        + "Please try again with just a simple number (e.g. 7)");    
      //Return an Error in form of -1 
      return -1; 
     } 
     x = Math.abs(x); 
     System.out.println("Setting the speed to " + (x*100) + "ms."); 
    } 

    return x; 
} 

我已經聲明「SC」作爲一個靜態類在我PROGRAMM的beginnning變量static Scanner sc = new Scanner(System.in);

掃描儀爲什麼會返回空字符串? - 不要求用戶輸入 -
是的,我知道Method.readNextInt,但我發現它easyer處理這樣的異常。

+0

你顯示的代碼片段似乎沒問題。我假設你的代碼的另一部分有一個「問題」。很有可能,你已經用'sc.nextInt()'或類似的方式讀過其他一些輸入。此方法_不消耗控制檯上鍵入的換行符。如果你進入你的顯示方法,那麼'String s = sc.nextLine()'語句直接使用這個掛起的換行符,而不用等待任何其他輸入。你也得看看你的其他代碼。 – Seelenvirtuose

+0

@Seelenvirtuose 感謝您的回答。 Bevor我再次訪問該方法,我問用戶他是否想要一個新遊戲。 (y/n答案)。 如果他想要一個新的遊戲,returnInt()方法會再次被使用。 但是,這不應該是問題eversicne我訪問sc.nextLine()通過我的程序(改變方向等),所以我不明白爲什麼它在那種特定情況下這樣做 –

+1

我說,如果在_another_ place sc .nextInt()'被使用,你有一個未被使用的掛起的換行符。下一個'sc.nextLine()'只消耗這個換行符,並且不會優先輸入任何內容。因此,問題出現在代碼的另一部分! – Seelenvirtuose

回答

0

謝謝@Seelenvirtuose誰帶我到解決方案的正確軌道!

I said, if in another place sc.nextInt() was used, you have a pending newline that was not consumed. The next sc.nextLine() only consumes this newline and does not give the priority to enter anything. The problem, therefore, is in another portion of your code! –

的解決方案是,在我的代碼一些部分我使用sc.next()其中只有下一個字符串直到空格中讀取(如果我沒有記錯的話),而不是sc.nextLine()
所以我已經把所有sc.next()更改爲sc.nextLine()不是它工作得很好。

有同時做試錯,我已經找到了2個其他解決方案:
一)Wrtie sc.reset()它確實「重置掃描器會丟棄其所有明確的狀態信息。[...]」 bevor accesing的sc.nextLine()命令或
b)只需創建一個新的實例掃描儀類。

再次感謝Seelenvirtuose