[英]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.