Как я могу проверить, что буквы не введены в массив?

1

Это простая программа калькулятора. Мне просто нужно что-то проверить в моем массиве и предотвратить любые буквы, находящиеся в нем, прежде чем моя программа продолжит "добавление" двух введенных аргументов. Вход берется из командной строки, например, 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);
        }
    }
}
  • 0
    Здесь не проблема, но вы можете напрямую написать условие в первом операторе if например, так: args.length != 2 вместо использования ненужной двойной проверки, которую вы сейчас используете.
  • 0
    Вы можете использовать регулярные выражения, подробнее здесь vogella.com/tutorials/JavaRegularExpressions/article.html
Показать ещё 2 комментария
Теги:
calculator
command-line

5 ответов

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

    }
}
  • 0
    что такое "NFE"? ?
  • 0
    @Aify Получил спасибо.
Показать ещё 2 комментария
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
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.

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");
    }
}
  • 0
    У меня есть цикл, чтобы он суммировал введенный
  • 0
    System.out.println («Результат:: + args [0] + args [1]); это дает тот же эффект без зацикливания :)
Показать ещё 2 комментария

Ещё вопросы

Сообщество Overcoder
Наверх
Меню