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;
}
}
}