尝试和捕获用户输入会导致变量未初始化

时间:2012-10-03 15:03:05

标签: java variables input initialization try-catch

* 编辑:好的,在修复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来检查用户输入是否是有效的Integer。

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

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();
            }
        }
    }
}

3 个答案:

答案 0 :(得分:1)

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

try
{
    guess = Integer.parseInt(iConsole.nextLine());
}
catch (Exception e)
{
    System.out.println("Invalid input. Please try again.");
    continue; // jump to beginning of loop
}

答案 1 :(得分:0)

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

int guess = -1; // some default value 

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

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
  }
}

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

答案 2 :(得分:0)

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

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

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