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;
}
}
}
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.
reader.readLine() twice.reader.readLine() from within Integer#parseInt.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With