所以我現在編程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處理這樣的異常。
你顯示的代碼片段似乎沒問題。我假設你的代碼的另一部分有一個「問題」。很有可能,你已經用'sc.nextInt()'或類似的方式讀過其他一些輸入。此方法_不消耗控制檯上鍵入的換行符。如果你進入你的顯示方法,那麼'String s = sc.nextLine()'語句直接使用這個掛起的換行符,而不用等待任何其他輸入。你也得看看你的其他代碼。 – Seelenvirtuose
@Seelenvirtuose 感謝您的回答。 Bevor我再次訪問該方法,我問用戶他是否想要一個新遊戲。 (y/n答案)。 如果他想要一個新的遊戲,returnInt()方法會再次被使用。 但是,這不應該是問題eversicne我訪問sc.nextLine()通過我的程序(改變方向等),所以我不明白爲什麼它在那種特定情況下這樣做 –
我說,如果在_another_ place sc .nextInt()'被使用,你有一個未被使用的掛起的換行符。下一個'sc.nextLine()'只消耗這個換行符,並且不會優先輸入任何內容。因此,問題出現在代碼的另一部分! – Seelenvirtuose