Java 如何检查数组中是否未输入字母?

Java 如何检查数组中是否未输入字母?,java,command-line,calculator,Java,Command Line,Calculator,这是一个简单的计算器程序。在我的程序继续“添加”输入的两个参数之前,我只需要一些东西来检查我的数组,并防止数组中出现任何字母。输入来自命令行,例如java加法器12 public class Adder { public static void main(String[] args) { //Array to hold the two inputted numbers float[] num = new float[2]; //Sum of

这是一个简单的计算器程序。在我的程序继续“添加”输入的两个参数之前,我只需要一些东西来检查我的数组,并防止数组中出现任何字母。输入来自命令行,例如
java加法器12

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);
        }
    }
}
公共类加法器{
公共静态void main(字符串[]args){
//数组来保存两个输入的数字
float[]num=新浮点[2];
//数组[2]的和将存储在应答中
浮动答案=0;
/*
有些人需要检查输入的土地类型。。。
*/
//如果输入了两个以上的图形,将显示错误消息
如果(args.length>2 | | args.length<2){
System.out.println(“错误:只输入两个数字,不能多也不能少”);
}
否则{
//循环以添加数组num中的所有值
对于(int i=0;i
您可以使用正则表达式检查模式

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

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

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
虽然您不能“阻止”用户输入字母,但您可以编写代码以便处理字母。以下是几种方法:

1) 分析这些字母,如果你发现了,就把它们扔掉

2) 解析这些字母,如果发现了,返回一条错误消息并要求用户重试

try {
    // your parsing code here
} catch (NumberFormatException e) {
    // error message and ask for new input
}
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) 解析这些字母,如果发现了,返回一条错误消息并要求用户重试

try {
    // your parsing code here
} catch (NumberFormatException e) {
    // error message and ask for new input
}
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.

    }
}

我建议您使用正则表达式

// One or more digits
Pattern p = Pattern.compile("\d+");
if(!p.matcher(input).matches())
   throw new IllegalArgumentException();
有关正则表达式的详细信息,请参见:
我建议您使用正则表达式

// One or more digits
Pattern p = Pattern.compile("\d+");
if(!p.matcher(input).matches())
   throw new IllegalArgumentException();
有关正则表达式的详细信息,请参见:

我可能会尝试解析这些值,然后处理异常

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");
            }
        }
    }
}
公共类加法器{
公共静态void main(字符串[]args){
//数组来保存两个输入的数字
float[]num=新浮点[2];
//数组[2]的和将存储在应答中
浮动答案=0;
/*
有些人需要检查输入的土地类型。。。
*/
//如果输入了两个以上的图形,将显示错误消息
如果(args.length>2 | | args.length<2){
System.out.println(“错误:只输入两个数字,不能多也不能少”);
}
否则{
试一试{
//循环以添加数组num中的所有值
对于(int i=0;i
我可能会尝试解析这些值,然后处理异常

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");
            }
        }
    }
}
公共类加法器{
公共静态void main(字符串[]args){
//数组来保存两个输入的数字
float[]num=新浮点[2];
//数组[2]的和将存储在应答中
浮动答案=0;
/*
有些人需要检查输入的土地类型。。。
*/
//如果输入了两个以上的图形,将显示错误消息
如果(args.length>2 | | args.length<2){
System.out.println(“错误:只输入两个数字,不能多也不能少”);
}
否则{
试一试{
//循环以添加数组num中的所有值
对于(int i=0;i
无需循环:

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");
    }
}
无需循环:

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

这里没有问题,但是您可以直接在第一个
if
语句中编写条件,如下所示:
args.length!=2
而不是现在使用的无用的重复检查。您可以