检测无效输入的数量(使用parseInt)

时间:2014-10-02 12:40:29

标签: java

我正在尝试制作一个程序,允许用户输入5个不同的数字;但我没有显示数字,而是向用户显示他已完成的错误/无效输入数量。问题是:我不知道该怎么做,但到目前为止我已经成功制作了一个程序,但它不太正确。

import javax.swing.JOptionPane;

public class TopicThirteen {

    public static void main(String[] args) {
        String msg = "";
        int num = 0;
        int counter;

        //for loop that gets the 5 numbers from the user
        for(counter = 0; counter < 5; counter++) {
            try {
                num = Integer.parseInt(JOptionPane.showInputDialog(
                        "Enter number " + (counter + 1)));
            } catch(Exception e) {
                JOptionPane.showMessageDialog(null, "Error " + e);
            }
        }
        //sets msg to the string equivalent of input
        switch(num) {
        case 1:
            msg = "one Invalid Inputs";
            break;
        case 2:
            msg = "two Invalid Inputs";
            break;
        case 3:
            msg = "three Invalid Inputs";
            break;
        case 4:
            msg = "four Invalid Inputs";
            break;
        case 5:
            msg = "five Invalid Inputs";
            break;
        }
        // displays the number in words if with in range
        JOptionPane.showMessageDialog(null, msg);
    }
}

2 个答案:

答案 0 :(得分:3)

你还需要一个变量来保持计数并在每个错误输入上增加该计数器,即catch块内。要在数字解析异常方面更具体,您应该使用NumberFormatException

int wrongInputCounts = 0 ;
//for loop that gets the 5 numbers from the user
for(counter = 0; counter < 5; counter++){

    try{

        num = Integer.parseInt(JOptionPane.showInputDialog("Enter number "+(counter+1)));

    }catch(NumberFormatException e){
        wrongInputCounts++;
        JOptionPane.showMessageDialog(null,num + " is not a valid number");
    }
}

然后打开wrongInputCounts:

switch(wrongInputCounts){

答案 1 :(得分:1)

这个版本怎么样:

public class TopicThirteen
{   
    public static void main(String[] args){

        String msg = "";
        int num =0;
        int counter;

        //for loop that gets the 5 numbers from the user
        for(counter = 0; counter < 5; counter++){

            try{

                Integer.parseInt(JOptionPane.showInputDialog("Enter number "+(counter+1)));

            }catch(Exception e){
                num++;
                JOptionPane.showMessageDialog(null,"Error "+e);
            }
        }

        msg = num + " invalid input(s)";
        //displays the number in words if with in range
        JOptionPane.showMessageDialog(null,msg);
    }
}

正如您所说,您不必抓住用户输入但用户输入错误。