【发布时间】:2019-10-14 03:47:51
【问题描述】:
我正在尝试创建一组代码,让您可以用计算机猜数字。问题部分和调试控制台部分都很清楚,我能够运行它,直到我尝试通过集成终端输入值。
我已将返回的字符串值从 Input.nextLine() 转换为 int 值,尽管这似乎没有效果,我也从在集成终端而不是调试控制台上运行代码切换。此外,我尝试了 catch(NumberFormatException) 语句,但它失败了,因为 Visual Studio Code 无法识别 catch 或 NumberFormatException。
while ( win == false)
{
int CorrectNumber = 70;
int g = (int)( Math.random() * 101 );
System.out.print( "The Number I Guess Is:" + g);
String TooHigh = "TooHigh";
//type TooHigh if the number computer guessed is too high
TooHigh = input.nextLine();
int h1 = Integer.parseInt(TooHigh);
String TooLow = "TooLow";
//type TooLow if the number computer guessed is too low
TooLow = input.nextLine();
int l1 = Integer.parseInt(TooLow);
if ( g == h1 ) //too high
{
int y = (int)( Math.random() * ( g - 70 ) );
System.out.print( "Another Number I Guessed is: " + y );
}
else if ( g == l1 ) //too low
{
int z = (int)( Math.random() * ( 70 - g ) );
System.out.print( "Another Number I Guessed is: " + z );
}
else if ( g == 70 ) //computer wins
{
win = true;
}
当我输入文字告诉计算机它猜到的数字是太高还是太低时,我希望它会给我另一个数字。但相反,我收到以下消息:
Exception in thread "main" java.lang.NumberFormatException: For input string: "TooLow"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at RevGuess.main(RevGuess.java:23)
【问题讨论】: