如何检查阵列中是否没有输入字母?

时间:2015-02-05 18:28:14

标签: java command-line calculator

这是一个简单的计算器程序。在我的程序继续“添加”输入的两个参数之前,我只需要检查我的数组并防止其中包含任何字母。输入取自命令行,例如java adder 1 2

public class Adder {
    public static void main(String[] args) {
        //Array to hold the two inputted numbers
        float[] num = new float[2];
        //Sum of the array [2] will be stored in answer
        float answer = 0;

        /*
            some how need to check the type of agruments entered...
        */

        //If more than two agruments are entered, the error message will be shown
        if (args.length > 2 || args.length < 2){
            System.out.println("ERROR: enter only two numbers not more not less");
        }

        else{
        //Loop to add all of the values in the array num 
            for (int i = 0; i < args.length; i++){
                num[i] = Float.parseFloat(args[i]);
                //adding the values in the array and storing in answer
                answer += Float.parseFloat(args[i]);
            }

            System.out.println(num[0]+" + "+num[1]+" = "+answer);
        }
    }
}

5 个答案:

答案 0 :(得分:6)

虽然您无法“阻止”用户输入字母,但您可以编写代码以便处理这些字母。以下是几种方法:

1)解析字母,如果发现任何字母,请将它们丢弃。

2)解析字母,如果发现任何字母,则返回错误消息并要求用户重试

3)解析数字,并捕获抛出的NFE(NumberFormatException),然后返回错误消息并要求用户再试一次

try {
    // your parsing code here
} catch (NumberFormatException e) {
    // error message and ask for new input
}

另外,我可能会重写该程序,使其在while循环中运行,使用Scanner对象获取输入。这样,每次要添加内容时,都不必使用java命令行运行程序,只需运行程序一次,接受输入直到用户想要退出。它看起来像这样:

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    while (true) {
        // ask for input
        System.out.println("insert 2 numbers separated by a space or quit to quit:")
        //scanner object to take input, reads the next line
        String tempString = scan.nextLine();
        // break out of the loop if the user enters "quit"
        if (tempString.equals("quit") {
            break;
        }
        String[] tempArray = tempString.split(" ");
        // add the values in tempArray to your array and do your calculations, etc. 
        // Use the Try/catch block in 3) that i posted when you use parseFloat()
        // if you catch the exception, just continue and reloop up to the top, asking for new input.

    }
}

答案 1 :(得分:2)

您可以使用正则表达式检查模式。

String data1 = "d12";
String data2 = "12";
String regex = "\\d+";
System.out.println(data.matches(regex)); //result is false
System.out.println(data.matches(regex)); //result is true

答案 2 :(得分:2)

我可能只是尝试解析值然后处理异常。

public class Adder {
    public static void main(String[] args) {
        //Array to hold the two inputted numbers
        float[] num = new float[2];
        //Sum of the array [2] will be stored in answer
        float answer = 0;

        /*
            some how need to check the type of agruments entered...
        */

        //If more than two agruments are entered, the error message will be shown
        if (args.length > 2 || args.length < 2){
            System.out.println("ERROR: enter only two numbers not more not less");
        }

        else{
            try {
                //Loop to add all of the values in the array num 
                for (int i = 0; i < args.length; i++){
                    num[i] = Float.parseFloat(args[i]);
                    //adding the values in the array and storing in answer
                    answer += Float.parseFloat(args[i]);
                }

                System.out.println(num[0]+" + "+num[1]+" = "+answer);
            } catch (NumberFormatException ex) {
                System.out.println("ERROR: enter only numeric values");
            }
        }
    }
}

答案 3 :(得分:0)

我建议您使用正则表达式

// One or more digits
Pattern p = Pattern.compile("\d+");
if(!p.matcher(input).matches())
   throw new IllegalArgumentException();

有关正则表达式的更多信息,请参阅: http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html

答案 4 :(得分:0)

无需循环:

public static void main(String[] args) {
    // length must be 2
    if (args.length != 2) {
        System.out.println("we need 2 numbers");
        // regex to match if input is a digit
    } else if (args[0].matches("\\d") && args[1].matches("\\d")) {
        int result = Integer.valueOf(args[0]) + Integer.valueOf(args[1]);
        System.out.println("Result is: " + result);
        // the rest is simply not a digit
    } else {
        System.out.println("You must type a digit");
    }
}