0

*编辑:好的,在修复 try catch 错误后,我在catch {..打印时遇到问题。*,基本上当我说我想再玩一次时,它会继续游戏,但它也会打印第一个catch,然后在第 23 行要求输入。

if (decision.equalsIgnoreCase("yes"))
        {
            ai = (int)(Math.random()*101);
            System.out.println("From 0 to 100, what number do you think I have generated?");

            tryCatch = true;
            loop = true;
            rtrn = true;

            while (tryCatch == true)    
            {   
                while (loop == true)
                {
                    try
                    {
                        guess = Integer.parseInt(iConsole.nextLine());
                        if (guess >= 0)
                        {
                            loop = false;
                        }
                    }

                    catch (NumberFormatException e)
                    {
                        System.out.println("Invalid input. Please try again.");
                    }

                    catch (InputMismatchException e)
                    {
                        System.out.println("Invalid input. Please try again!");
                    }
                }

嗨,这是我的第一篇文章,所以如果我在论坛上弄错了代码格式,我会编辑它。

现在我正在用 java eclipse 编写一个游戏,其中 cpu 生成一个数字,用户必须猜测它。我大部分时间都在使用扫描仪类。我遇到的麻烦是创建一个 try catch 来检查用户输入是否是有效的整数。

最终发生的是它下面的代码块无法识别已经初始化的变量。

package ics3U;

import java.util.*;
import java.io.*;

public class highLow
{
    static public void main (String args[]) throws IOException
    {
        String name;
        String decision;
        String decision2;
        int ai;
        int guess;
        int counter = 1;
        boolean fullGame = true;
        boolean tryCatch = true;
        boolean rtrn = true;

        Scanner iConsole = new Scanner(System.in);

        System.out.println("Hello! Welcome to HiLo!");
        System.out.println("What is your full name?");

        name = iConsole.nextLine();

        System.out.println("Hello " + name + "! Would you like to play?");
        decision = iConsole.nextLine();

        while (fullGame == true)
        {
            if (decision.equalsIgnoreCase("yes"))
            {
                ai = (int)(Math.random()*101);
                System.out.println("From 0 to 100, what number do you think I have generated?");

                tryCatch = true;
                rtrn = true;

                while (tryCatch == true)    
                {   
                    try
                    {
                        guess = Integer.parseInt(iConsole.nextLine());
                    }

                    catch (Exception e)
                    {
                        System.out.println("Invalid input. Please try again.");
                    }

                    while (guess != ai)
                    {
                        if (guess < ai)
                        {
                            System.out.println("Too low!");
                            guess = iConsole.nextInt();
                        }

                        else if (guess > ai)
                        {
                            System.out.println("Too high!");
                            guess = iConsole.nextInt();
                        }
                        counter = counter + 1;
                    }
                    System.out.println("Correct! You guessed it after " + counter + " tries!");
                    counter = ((counter - counter)+1);
                    System.out.println("Would you like to play again?");

                    while (rtrn == true)
                    {
                        decision2 = iConsole.next(); //finally..

                        if (decision2.equalsIgnoreCase("yes"))
                        {
                            fullGame = true;
                            tryCatch = false;
                            rtrn = false;
                            break; //do-while may be needed, have to bypass catch, 'break' works after restating value of tryCatch & rtrn
                        }

                        else if (decision2.equalsIgnoreCase("no"))
                        {
                            System.out.println("Goodbye.");
                            fullGame = false;
                            tryCatch = false;
                            rtrn = false;
                            iConsole.close();
                        }

                        else
                        {
                            System.out.println("Sorry?");
                        }
                    }

                    /*catch (Exception e)
                    {
                        System.out.println("Invalid input. Please try again.");
                    }

                    catch (NumberFormatException e)
                    {
                        System.out.println("Invalid input. Please try again.");
                    }
                    //More specific Exceptions, turn this on later              
                    catch (InputMismatchException e)
                    {
                        System.out.println("Invalid input. Please try again!");
                    }*/
                }
            }

            else if (decision.equalsIgnoreCase("no"))
            {
                System.out.println("Goodbye.");
                fullGame = false;
                tryCatch = false;
                rtrn = false;
                iConsole.close();
            }

            else
            {
                System.out.println("Sorry?");
                decision = iConsole.nextLine();
            }
        }
    }
}
4

3 回答 3

1

continue在你的 catch 块中添加一个语句。这样,如果用户输入的不是整数并且解析失败,它将立即重试,而不是尝试运行循环的其余部分。

try
{
    guess = Integer.parseInt(iConsole.nextLine());
}
catch (Exception e)
{
    System.out.println("Invalid input. Please try again.");
    continue; // jump to beginning of loop
}
于 2012-10-03T15:08:34.673 回答
0

由于语句位于 try 块中,因此它们有可能会失败,并且您的程序有可能尝试使用未初始化的变量。解决方案是将变量初始化为有意义的默认值,即

int guess = -1; // some default value 

您还应该将 while 循环包裹在 try/catch 块周围。在输入的数据有效之前,不要让程序继续进行。

boolean validGuess = false;
while (!validGuess) {
  // prompt user for input here
  try {
    guess = Integer.parseInt(iConsole.nextLine());
    if (/* .... test if guess is valid int */ ) {
      validGuess = true;
    } 
  } catch (NumberFormatException e) {
      // notify user of bad input, that he should try again
  }
}

如果您需要在整个程序中执行类似的操作,您甚至可以将所有这些封装到它自己的方法中。

于 2012-10-03T15:05:04.520 回答
0

尝试在此行之后的 try 块内的 catch 块之后(在循环中)移动所有代码

guess = Integer.parseInt(iConsole.nextLine());

正如您目前拥有的那样,只要 parseInt 中出现异常,它仍然会尝试处理未分配的猜测而不是重新启动循环。

于 2012-10-03T15:09:29.697 回答