尝试将字符串解析为int时出错

时间:2013-03-23 20:43:58

标签: java string int

在这个Java程序中,用户应该猜测1到100之间的数字,然后如果按S,它会显示尝试的摘要。问题是我正在获取输入字符串并将其转换为数字,因此我可以将其与范围进行比较,但是我还需要能够将该字符串用作菜单输入。 更新如何在用户正确猜测后使程序返回菜单选项。因此,在用户获胜后,我希望问题显示摘要报告,否则可以使用S

进行访问

这是我的代码

public class GuessingGame {
  public static void main(String[] args) {


    // Display list of commands
                System.out.println("*************************");
                System.out.println("The Guessing Game-inator");
                System.out.println("*************************");  
                System.out.println("Your opponent has guessed a number!");
                System.out.println("Enter a NUMBER at the prompt to guess.");
                System.out.println("Enter [S] at the prompt to display the summary report.");
                System.out.println("Enter [Q] at the prompt to Quit.");
                System.out.print("> ");


    // Read and execute commands
    while (true) {

      // Prompt user to enter a command
      SimpleIO.prompt("Enter command (NUMBER, S, or Q): ");
      String command = SimpleIO.readLine().trim();

      // Determine whether command is "E", "S", "Q", or
      // illegal; execute command if legal.
      int tries = 0;
      int round = 0;
      int randomInt = 0;
      int number = Integer.parseInt(command);
      if (number >= 0 && number <= 100) {
        if(randomInt == number){

                System.out.println("Congratulations! You have guessed correctly." +
                                " Summary below");
                round++;
        }
        else if(randomInt < number)
        {
                System.out.println("your guess is TOO HIGH. Guess again or enter Q to Quit");
                tries++;
        }      
        else if(randomInt > number){
                System.out.println("your guess is TOO LOW. Guess again or enter Q to Quit");
                tries++;
        }

      } else if (command.equalsIgnoreCase("s")) {
         // System.out.println("Round        Guesses");
         // System.out.println("-------------------------");
        //  System.out.println(round + "" + tries);



      } else if (command.equalsIgnoreCase("q")) {
        // Command is "q". Terminate program.
        return;

      } else {
        // Command is illegal. Display error message.
        System.out.println("Command was not recognized; " +
                           "please enter only E, S, or q.");
      }

      System.out.println();
    }
  }
}

4 个答案:

答案 0 :(得分:1)

要检查字符串是否为整数,只需尝试将其解析为整数,如果抛出异常,则它不是整数。

见:

http://bytes.com/topic/java/answers/541928-check-if-input-integer

String input = ....
try {
    int x = Integer.parseInt(input);
    System.out.println(x);
}
catch(NumberFormatException nFE) {
    System.out.println("Not an Integer");
}

答案 1 :(得分:1)

您应首先检查S / Q值,然后将字符串解析为整数。如果捕获NumberFormatException(由Integer.parseInt()抛出),则可以确定输入是否为有效值。我会做那样的事情:

if ("s".equalsIgnoreCase(command)) {
    // Print summary
} else if ("q".equalsIgnoreCase(command)) {
    // Command is "q". Terminate program.
    return;
} else {
    try {
        Integer number = Integer.parseInt(command);
        if(number < 0 || number > 100){
            System.out.println("Please provide a value between 0 and 100");
        } else if(randomInt == number){
            System.out.println("Congratulations! You have guessed correctly." +
                        " Summary below");
            round++;
        } else if(randomInt < number) {
            System.out.println("your guess is TOO HIGH. Guess again or enter Q to Quit");
                 tries++;
        } else if(randomInt > number) {
            System.out.println("your guess is TOO LOW. Guess again or enter Q to Quit");
            tries++;
        }
    } catch (NumberFormatException nfe) {
        // Command is illegal. Display error message.
        System.out.println("Command was not recognized; " +
                       "please enter only a number, S, or q.");
    }
}

使用此算法(我确信它可以进行优化),您可以处理以下情况:

  • 用户输入s / S
  • 用户输入q / Q
  • 用户输入无效值(非数字)
  • 用户输入无效号码(小于0或大于100)
  • 用户输入有效号码

答案 2 :(得分:0)

如果String无效,Integer.parseInt(command)将为您提供NumberFormatException。如果用户输入的“S”或“E”无法解析为int值,则可以在代码中使用。

我修改了你的代码。检查此代码:

 while (true) {

          // Prompt user to enter a command
          SimpleIO.prompt("Enter command (NUMBER, S, or Q): ");
          String command = SimpleIO.readLine().trim();

          // Determine whether command is "E", "S", "Q", or
          // illegal; execute command if legal.
          int tries = 0;
          int round = 0;
          int randomInt = 0;
          if(!command.equals("S") && !command.equals("E")) {
            // Only then parse the command to string  

          int number = Integer.parseInt(command);
          if (number >= 0 && number <= 100) {
            if(randomInt == number){

答案 3 :(得分:0)

您正在尝试将传入的String转换为int,然后再检查它是否为转义序列(S或Q)。

尝试重新排列if语句,先检查S和Q,然后尝试将值转换为int

我还建议你将Integer.parseInt调用(它是后续的,依赖代码)包装在try-catch块中,这样如果用户键入任何内容,就可以向用户提供错误声明。是一个int