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

标签 java command-line calculator

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

最佳答案

虽然您无法“阻止”用户输入字母,但您可以编写代码来处理这些字母。这里有几种方法可以做到这一点:

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.

    }
}

关于java - 如何检查数组中没有输入任何字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28351385/

相关文章:

Java Sonatype 异步 HTTP 客户端上传进度

java - 在 Java 中更新参数值

windows - if 条件下的批处理文件多个操作

java - 在命令行上将多个 jar 添加到类路径

java - 使用weka的命令行创建阈值文件

java - 通过 GUI 上的按钮在文本字段中输入数字

android - 如何计算 EditText 框的总和?

java - 导入无法解决错误

java - 粘性 Eclipse 错误标记

javascript - jQuery 计算插件 - 营养计算器 - 单击关联单选按钮添加值