有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Try and Catch with JOption无法按预期工作

    int i=0;
    int c=0;
    int a=0;
    int b=0;
    String stringy;
    String input;

    do { //loop for value a
        try // try-catch to prevent program from crashing
        {
            stringy= JOptionPane.showInputDialog("Type a value for a or press q to quit:");                       
            if (stringy.equalsIgnoreCase("q")) System.exit(0); 
            a = Integer.parseInt(stringy);
            i++;               
         } catch (Exception e) {
               stringy= JOptionPane.showInputDialog("Error. Try Again! ");                 
         }  // end catch     
    } while(i==0); // end loop

输出会生成一个jOption输入对话框("type a value..."),当我输入一个字符串或系统不希望的东西时,它会进入"catch"并弹出"error try again!"。然而,当我在其中输入任何东西时,即使它是一个数字,它也会返回(“键入一个值…”)对话框。我希望它读取错误框中的输入,而不是跳回第一个对话框。谢谢你的帮助


共 (3) 个答案

  1. # 1 楼答案

    如果你想使用来自catch()的输入,你应该把基本输入带出循环。 并使用break;子句代替while(i==0)i++

           stringy= JOptionPane.showInputDialog("Type a value for a or press q to quit: ");
           while(true)
           {
               if (stringy.equalsIgnoreCase("q")) System.exit(0);
               try {
                   a = Integer.parseInt(stringy);
                   break;
               } catch (Exception e) {
                  stringy= JOptionPane.showInputDialog("Error. Try Again! ");
               }             
           }
           JoptionPane.showMessageDialog("Input accepted!");
    

    请用正确的格式写你的代码,你已经在循环开始时注释了“{”

  2. # 2 楼答案

    为输出添加一个字符串怎么样

        String input;
        String output = "Type a value for a or press q to quit: "
    
        do  //loop for value a        {
            try // try-catch to prevent program from crashing
            {
                stringy= JOptionPane.showInputDialog(output);                       
                                if (stringy.equalsIgnoreCase("q"))          
                {
                  System.exit(0);
                }             
                a= Integer.parseInt(stringy);
                i++;               
             }
             catch (Exception e)
             {
                   output= "Error. Try Again! ";                 
    
             }  
    
  3. # 3 楼答案

    显然,您还必须检查第二个对话框的输入,类似于以下内容:

    stringy = JOptionPane.showInputDialog("Error. Try Again! ");
    
    if (stringy.equalsIgnoreCase("q")) {
        System.exit(0);
    }