Chien
Chien

Reputation: 355

Stuck with repeated input when try to add integers from user together

I'm trying to read integers from the user (also me), and I don't know how many integers I would need to add together. Therefore I used a do-while; everything is fine until the compiler rised an error in the condition to quit the loop. I'm not using JDK on an OS which uses English as the system language, so the error message is not in English. All I can do is to leave the codes here.

I know I would never need to add 99999 to the sum, so firstly I compared the input with 99999; after failing I defined a stopNum which equals to 99999, and that would not work either.

int sum = 0;
final int stopNum = 99999;

do {
    int input = Integer.parseInt(System.console().readLine());
    sum = +input;
} while (input != stopNum);

Upvotes: 1

Views: 38

Answers (1)

Andrew
Andrew

Reputation: 49606

  1. Define int input = 0; outside of the loop, so it's accessible in the condition.

  2. It's not sum = +input;, it's sum += input;. You want to add input to sum, not reassign sum with a positive input.

  3. It's not input != stopNum, it's input < stopNum. It's hard to enter n numbers that give exactly stopNum.

Upvotes: 1

Related Questions