如何检查数组中没有输入任何字母?

How can I check that no letters are entered in the array?

这是一个简单的计算器程序。在我的程序继续 "adding" 输入的两个参数之前,我只需要一些东西来检查我的数组并防止其中有任何字母。输入取自命令行,例如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);
        }
    }
}

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

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

虽然您不能 "prevent" 用户输入字母,但您可以编写代码来处理这些字母。这里有几种方法可以做到这一点:

1) 解析字母,如果找到就扔掉。

2) 解析字母,如果找到任何字母,return 一条错误消息并要求用户重试

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

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

附带说明一下,我可能会重写该程序,使其 运行 在 while 循环中使用 Scanner 对象获取输入。这样,您不必每次都从命令行使用 java 运行 程序 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.

    }
}

我建议你使用正则表达式

// 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

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

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

无需循环:

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