简体   繁体   English

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

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

This is a simple calculator program. 这是一个简单的计算器程序。 I just need something to check my array and prevent any letters being in it before my program continues "adding" the two arguments entered. 在我的程序继续“添加”输入的两个参数之前,我只需要检查一下我的数组并防止其中包含任何字母,就可以了。 The input is taken from the command line eg java adder 1 2 输入来自命令行,例如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);
        }
    }
}

While you can't "prevent" the user from inputting letters, you can write your code so that you can handle the letters. 虽然您无法“防止”用户输入字母,但是您可以编写代码以处理字母。 Here are a couple ways to do this: 这里有几种方法可以做到这一点:

1) Parse for the letters, and if you find any, throw them out. 1)解析字母,如果发现字母,请将其丢弃。

2) Parse for the letters, and if you find any, return an error message and ask the user to try again 2)解析字母,如果发现字母,则返回错误消息,并要求用户重试

3) Parse for the numbers , and catch the NFE (NumberFormatException) thrown, then return an error message and ask the user to try again 3)解析数字 ,并捕获抛出的NFE(NumberFormatException),然后返回错误消息,并要求用户重试

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

On a side note, I probably would rewrite that program so that it runs in a while loop, using a Scanner object to take input. 附带说明一下,我可能会重写该程序,以便它使用Scanner对象获取输入,从而在while循环中运行。 That way, you don't have to run the program using java from command line everytime you want to add something, you can just run the program once, and accept input until the user wants to quit. 这样,您不必每次想添加东西时都使用命令行从Java运行该程序,您只需运行一次该程序,然后接受输入,直到用户想要退出即可。 It would look something like this: 它看起来像这样:

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.

    }
}

You can use regex to check for patterns. 您可以使用正则表达式检查模式。

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

I would probably just try parsing the values and then handle the exception. 我可能只是尝试解析值,然后处理异常。

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

I suggest that you use a Regular Expression 我建议您使用正则表达式

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

For more about regular expression see: http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html 有关正则表达式的更多信息,请参见: http : //docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html

No need to loop: 无需循环:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM