"Mistaken" result of calculation. JAVA. So stuck

Viewed 92

Hello everybody. I'm stuck and don't understand why the code gives me back a "wrong" answer.

My task: to write a program which takes numbers and counts them until the user types "exit", then the program prints out the summary of all digits which the user just inserted and stops.

I'm learning java online at the moment and don't know how to answer that: when you type 1 or 2 or 3 numbers or more, it calculates and print the wrong result, or even the code can't be compiled and pops up an error.

E.g. you put 2 numbers and there is an error

Exception in thread "main" java.lang.NumberFormatException: For input string: "exit" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68) at java.base/java.lang.Integer.parseInt(Integer.java:652) at java.base/java.lang.Integer.parseInt(Integer.java:770) at JR.constructors.Solution.main(Solution.java:11)


OR 3 numbers, such as 2 + 3 + 4 and it prints 6 instead of 8.

Help me please!

And here is my code

public static void main(String[] args) throws Exception {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    int sum = 0;
    while(true){
        int a = Integer.parseInt(reader.readLine());
        String s = reader.readLine();
        sum += a;
        if(s.equals("exit")){
            System.out.println(sum);
            break;
        }
    }
}
3 Answers

If anyone types anything other than a number Integer.parseInt() will fail and throw an error, So use 1 variable to get the input from the stream , first look and see if the user typed "exit" if not try to convert the string to an integer, make sure to put this in a try catch block to catch error if the user typed something invalid.

Problems:

  1. Using reader.readLine() twice.
  2. Wrong placement of the exit criteria.

Solution:

  1. Remove reader.readLine() from within Integer#parseInt.
  2. Place the exit criteria at the beginning of the loop so that the program can exit without trying to parse the word, exit which will throw NumberFormatException because this function can parse only integer strings.

    Code:

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    public class Main {
        public static void main(String[] args) throws IOException {
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            int sum = 0;
            while (true) {
                String s = reader.readLine();
                if (s.equals("exit")) {
                    System.out.println(sum);
                    break;
                }
                int a = Integer.parseInt(s);
                sum += a;
            }
        }
    }
    

    A sample run:

    2
    3
    4
    exit
    9
    

The mentionned errors (exceptions) come from incorrect input parsing. You must make a clear distinction between reading a number and reading a String, or wisely catch exceptions when converting strings to numbers.

I'd propose a solution with Scanner instead (simpler, clearer, less exceptions handling).

public static void main(String[] args) {
    Scanner scn = new Scanner(System.in);

    String inputStr = null;
    int sum = 0;

    // Attention: order of conditions matters
    while(!"exit".equals(inputStr) && scn.hasNext()) {
        if(scn.hasNextInt()) {
            sum += scn.nextInt();
        }
        else {
            inputStr = scn.next();
        }
    }

    System.out.println("SUM="+sum);
    System.exit(0);
}
Related