【发布时间】:2016-02-04 21:41:08
【问题描述】:
我正在编写一个程序,假设从用户那里读取字符串并验证字符串和操作数。仅有的两个可接受的操作数是“+”和“-”。该字符串不能包含除数字以外的任何字符,如果包含,它应该说“输入错误”但不断提示用户。我在下面粘贴了我的代码,我们假设为这个程序使用异常。我的代码不工作,它崩溃了,这些数字需要总结和打印出来,但我在使用字符串中的操作数时遇到了麻烦
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String term;
do {
String str = input.nextLine();
term = str.trim();
try {
System.out.println(validInput(str));
System.out.println(sumNums(str));
} catch (IllegalOperandException e) {
System.out.println("Bad Input");
} catch (NumberFormatException e) {
System.out.println("Bad Input");
}
} while (term.length() > 0);
}
public static String validInput(String string) throws IllegalOperandException {
String output = "";
String[] stringArray = string.split("\\s+");
for (String s : stringArray) {
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (!(Character.isDigit(c) || c == '+' || c == '-' || c == '.' )) {
throw new IllegalOperandException(String.valueOf(c));
}
else if(Character.isDigit(c)){
Double.parseDouble(Character.toString(c));
}
}
output = output + s + " ";
}
return output;
}
public static double sumNums (String nums) throws NumberFormatException, ArrayIndexOutOfBoundsException {
String[] stringArray2 = nums.split("\\s+");
int i = 0;
int sum;
if (stringArray2[i].equals("-")) {
i++;
sum = Integer.parseInt(stringArray2[i]);
} else
sum = Integer.parseInt(stringArray2[i]);
for(int j = 0; j < stringArray2.length; j++) {
if (stringArray2[i].equals("+"))
sum+=Integer.parseInt(stringArray2[i-1]);
if (stringArray2[i].equals("-"))
sum-=Integer.parseInt(stringArray2[i+1]);
}
return sum;
}
}
【问题讨论】:
-
你得到了什么具体的错误?
-
当我输入一串字符时,它假设说“输入错误”并且它使用户再次提示,但它给了我这个“线程“主”java.lang.Error中的异常:未解决的编译问题:在 TEST.main(TEST.java:21) 处的 TEST.validInput(TEST.java:44) 类型 TEST 的方法 IllegalOperandException(char) 未定义
标签: java arrays string validation exception