我正在編寫一個程序,該程序假設從用戶讀取字符串並驗證字符串和操作數。只有兩個可接受的操作數是「+」和「 - 」。該字符串不能包含除數字之外的任何字符(如果有),則應該顯示爲「輸入錯誤」,但會一直提示用戶。我在下面粘貼了我的代碼,我們假設爲這個程序使用例外。我的代碼無法正常工作,它崩潰,這些數字需要進行總結,並打印出來,但我無法這樣做,與在字符串中驗證字符串異常
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;
}
}
你會得到什麼具體的錯誤? – Seb
當我輸入一串字符,它假設說「不好的輸入」,它使用戶再次提示,但它給了我這個「線程中的異常」主「java.lang.Error:未解決的編譯問題: \t方法IllegalOperandException(焦炭)是不確定的型式試驗 \t在TEST.validInput(TEST.java:44) \t在TEST.main(TEST.java:21) –