Это простая программа калькулятора. Мне просто нужно что-то проверить в моем массиве и предотвратить любые буквы, находящиеся в нем, прежде чем моя программа продолжит "добавление" двух введенных аргументов. Вход берется из командной строки, например, 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);
}
}
}
Я бы просто попробовал разобрать значения и обработать исключение.
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");
}
}
}
}
Хотя вы не можете "запретить" пользователю вводить буквы, вы можете написать свой код, чтобы вы могли обрабатывать буквы. Вот несколько способов сделать это:
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.
}
}
Вы можете использовать регулярное выражение для проверки шаблонов.
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
Я предлагаю вам использовать регулярное выражение
// 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 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
вместо использования ненужной двойной проверки, которую вы сейчас используете.