[英]JAVA: Scanner doesn't read next line // returns empty string
因此,我目前正在對Snake進行編程,我有一個方法可以從控制台讀取一個整數值。
當我的方法拋出錯誤時(或者至少返回到該方法時),它不會從輸入中讀取新行,而只是傳遞一個空字符串。
這是我的代碼:
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”聲明為靜態類變量static Scanner sc = new Scanner(System.in);
在我的程序開始時。
掃描器為什么返回空字符串? -無需用戶輸入-
是的,我知道方法.readNextInt,但是我發現更容易處理此類異常。
感謝@Seelenvirtuose,他使我正確地找到了解決方案!
我說過,如果在其他地方使用sc.nextInt(),則您有一個未使用的待處理換行符。 下一個sc.nextLine()僅使用此換行符,而不優先輸入任何內容。 因此,問題出在代碼的另一部分! –
解決的辦法是在我的代碼的某些部分中,我使用的是sc.next()
,它僅讀取下一個字符串,直到空白(如果我沒有記錯),而不是sc.nextLine()
。
所以,我已經改變了所有sc.next()
來sc.nextLine()
不只是正常工作。
在進行跟蹤和錯誤處理時,我發現了另外兩種解決方案:
a)編寫sc.reset()
,以便通過使用sc.nextLine()
命令來“ 重置掃描器會丟棄其所有顯式狀態信息[...] ”,或
b)只需創建一個Scanner類的新實例。
再次感謝Seelenvirtuose 。
我使用兩種不同的掃描儀解決了:一種用於讀取int和float值,另一種用於讀取String。
Scanner scanString = new Scanner(System.in);
Scanner scanIntFloat = new Scanner(System.in);
int cod = scanIntFloat.nextInt();
String name = scanString.nextLine();
埃里亞斯。
您可以使用兩個不同的掃描儀 .......
第一台用於讀取int , float和double的掃描程序。
第二個掃描器,用於讀取字符串值。
像下面...
Scanner scanIntFloat = new Scanner(System.in);
Scanner scanString = new Scanner(System.in);
int cod = scanIntFloat.nextInt();
String name = scanString.nextLine();
發生了類似的問題。 我所做的是添加了nextLine(); next()之后的命令; 命令來捕獲填充輸入請求所在位置插入的緩沖區的字符。
基本上:
希望這可以幫助 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.