【问题标题】:How can I solve java.lang.NumberFormatException: For input string: "TooLow"如何解决 java.lang.NumberFormatException:对于输入字符串:“TooLow”
【发布时间】: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)

【问题讨论】:

    标签: java visual-studio-code


    【解决方案1】:

    你为什么要从 String 中获取一个 int 来说明猜测太低了?可以将其视为字符串,然后您可以将字符串与 .equals 进行比较,以查看字符串的值是否相同。如果是,则告诉程序它太低或太高。

    【讨论】:

      【解决方案2】:

      您正在将 int 与 String 进行比较,这就是您收到错误的原因。您应该做的是将用户输入与太高或太低进行比较,并根据用户输入执行 if/else 的太低或太高部分

      【讨论】:

        【解决方案3】:

        根据您的源代码,java 无法将单词“TooLow”转换为整数。它仍然对你的目标有偏见,如果你想比较整数总是输入数字,所以代码 int h1 = Integer.parseInt(TooHigh);将完美运行。

        【讨论】:

          猜你喜欢
          • 2016-12-15
          • 2012-12-05
          • 2013-09-04
          • 1970-01-01
          • 1970-01-01
          • 2017-09-18
          相关资源
          最近更新 更多