I'm writing a program that suppose to read in a string from the user and validate the string and the operands. The only two acceptable operands are "+" and "-". The string cannot contain any characters other than numbers if it does, it should say "Bad input" but keep prompting the user. I have pasted my code below and we are suppose to use exceptions for this program. My code is not working and it crashes and those numbers need to be summed up and printed out but I'm having trouble doing that with the operands that are in the string
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;
}
}