-1

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; 


} 


}
Mel David
  • 1
  • 5
  • What concrete error do you get? – Seb Feb 04 '16 at 21:44
  • when I input a string of characters, it suppose to say "Bad input" and it makes the user prompt again but it is giving me this "Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method IllegalOperandException(char) is undefined for the type TEST at TEST.validInput(TEST.java:44) at TEST.main(TEST.java:21) – Mel David Feb 04 '16 at 21:47

1 Answers1

1

First, to throw an exception you have to create new object. So, correct way to do so will be

throw new IllegalOperandException(c);

Second, you pass a character to a constructor, but constructor can accept only String. You can create second constructor in your IllegalOperandException class

public IllegalOperandException(char c){
    this(String.valueOf(c)); //this will call IllegalOperandException(String) constructor
}

or you can change line where you throw an exception to this

throw new IllegalOperandException(String.valueOf(c));

Third, return false is unreachable. If you throw an exception, code execution jumps directly to catch statement and your validInput(String) can't return anything (it has nowhere to return value). So, you don't need it

Meegoo
  • 417
  • 5
  • 13
  • omg it works now but now when i try this test case like this " 3231 + sdsa" it suppose to only say "Bad Input" but the output is "3231 + Bad Input" and where do I add the while loop so after the user gets the "Bad Input" message the user can input different values, The program is suppose to terminate when the user enters an empty string – Mel David Feb 04 '16 at 21:54
  • [Here](https://gist.github.com/6de47c5d4929d2efce14) is slightly modified version. Although I would use just regular expressions, then all the checks could be shrinked down to 3-4 lines –  Meegoo Feb 04 '16 at 22:24
  • How would you sum up the integers like 232 + 10 it would be 242 and it would keep prompting the user to do more problems just like that till the user enters whitespaces – Mel David Feb 04 '16 at 22:31
  • [Here's](https://gist.github.com/Meegooo/3f30cc21a46200656da7) slightly better version –  Meegoo Feb 04 '16 at 22:36
  • I need to sum up the numbers that are inputted by the user, how do I do that? for example a test case would be like this "4343.5 + 10 - 15" which would output "4348.5" – Mel David Feb 04 '16 at 22:43
  • In a nutshell, you can split on spaces, iterate through each member of the array and look for `+` and `-` signs. When you get one, you look at previous (`i-1`) member and next (`i+1`) member, parse them to `Integer` using `Integer.parseInt()` and sum/subtract them. Then you can replace next (`i+1`) element with your new sum/subtraction and continue the loop. Of course then stupid user could write something like "123 456 + + 123" which would pass the validation but won't work as expected (it would throw `NumberFormatException` because `+` can't be parsed into `Integer`). –  Meegoo Feb 04 '16 at 22:44
  • Also, your paser would fail when it meets dot. I suggest you use regular expressions for validation purposes. But I can't help you with those. –  Meegoo Feb 04 '16 at 22:48
  • Whelp, you can't split on spaces if input would be something like "123+123". So, you can do that `String fixedString = string.replace("+", " + ").replace("-", " - ").replaceAll(" +", " ")`. That will convert strings like "123+123 - 123" to "123 + 123 - 123" which you can parse using the way above –  Meegoo Feb 04 '16 at 22:57
  • I wrote the method of summing them up but it crashs and doesn't work – Mel David Feb 04 '16 at 23:02
  • public static double sumNums (String nums) throws NumberFormatException { double sum; String[] stringArray2 = nums.split("\\s+"); for(String s : stringArray2) { for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if(c == '+') sum += Integer.parseInt(stringArray[i-1]); else if(c == '-') sum -= Integer.parseInt(stringArray[i+1]); } return sum; } return sum; } } – Mel David Feb 04 '16 at 23:02
  • Something like that i think https://gist.github.com/Meegooo/5c913f1b0925268eac7d –  Meegoo Feb 05 '16 at 06:18
  • I used that code you provided with some edits but it still doesn't sum up and I get the wrong output – Mel David Feb 05 '16 at 15:02
  • I edited the main question and put my recent code up there – Mel David Feb 05 '16 at 15:04