2011-03-28 69 views
0

我一直在这一点工作,它不会编译。它给了我一个错误说使用开关并尝试声明来验证用户输入

变量的选择可能没有 初始化 开关(选择) ^

,但我在程序变量集。所以我不知道问题是什么?它是否真的能够避免编译?

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

      } 
     } 
    } 
+0

仅供参考'Java',而不是'JAVA' :) – 2011-03-28 19:22:03

回答

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) 
      { 
+0

还是不明白有什么问题?我是新来的。 – 2011-03-28 19:26:14

+0

好吧,我想通了。我只需要将整数'choice'设置为零。谢谢 – 2011-03-28 19:31:42

+2

@Josh:你不应该依靠你的代码来抛出一个异常,以达到你的正常代码路径。虽然它总是会抛出NFE,因为你只解析空字符串,而不是用户实际输入的内容(你忽略了“answer”变量)。 – 2011-03-28 19:52:31

0

你应该尝试块之前iniatialize选择的变量,因为你是在抓,在某些情况下,如果异常被选择happining那么varaible选择将未初始化的初始化之前扔引用它。