使用Switch和Try语句验证用户输入

时间:2011-03-28 19:12:18

标签: java

我已经在这方面工作了一段时间,它不会编译。它给我一个错误说

  

变量选择可能不是   初始化                 开关(选择)                        ^

但我在程序中设置了该变量。所以我不知道问题是什么?这真的是其他东西阻止编译吗?

 import java.io.*;
    import javax.swing.JOptionPane;

    public class MyType
    {
        public static void main(String[] args)
        {
            String strChoice = "", strTryString, strTryInt, strTryDouble;
            Integer choice, tryInt;
            double tryDouble;
            boolean done = false;

            while(!done)
        {
                try
                {
                    String answer = JOptionPane.showInputDialog(null, "What's my type\n\n\n1) String\n2) integer\n3) double\n4) Quit the program");
                    choice = Integer.parseInt(strChoice);

                    //test for valid codes 1, 2, 3, or 4
                    if (choice<1 || choice>4) throw new NumberFormatException();
                    else done = true;
                }
                    catch(NumberFormatException e)
                {
                    JOptionPane.showInputDialog(null, "Please enter a 1, 2, 3, or 4", "Error", JOptionPane.INFORMATION_MESSAGE);
                    switch(choice)
                {
                        case 1:
                            JOptionPane.showMessageDialog(null, "Correct, any input can be saved as a String");
                            break;

                        case 2:
                            JOptionPane.showMessageDialog(null, "Correct!");
                            tryInt = Integer.parseInt(strChoice);
                            break;

                        case 3:
                            JOptionPane.showMessageDialog(null, "Correct!");
                            tryDouble = Integer.parseInt(strChoice);
                            break;

                        case 4:
                            done = true;
                            JOptionPane.showMessageDialog(null, "Exit.");
                            System.exit(0);
                            break;
                        default:  throw new NumberFormatException();
            }
            }

            }
        }
    }

2 个答案:

答案 0 :(得分:0)

如果showInputDialog抛出,则不设置'choice'。

try
            {
                String answer = JOptionPane.showInputDialog(null, "What's my type\n\n\n1) String\n2) integer\n3) double\n4) Quit the program");
                choice = Integer.parseInt(strChoice);

                //test for valid codes 1, 2, 3, or 4
                if (choice<1 || choice>4) throw new NumberFormatException();
                else done = true;
            }
                catch(NumberFormatException e)
            {

答案 1 :(得分:0)

你应该在try块之前对选择变量进行初始化,因为你在catch中引用它,在某些情况下如果在初始化选择之前抛出异常,那么变量选择将是未初始化的。