Addition with while loop in java

时间:2017-09-25 02:35:02

标签: java addition

I'm trying to figure out how to create a java program where the user inputs a series of integers, the last integer being a 0 (when the program should stop). After stopping, the program should print out the sum of the integers. This needs to be done using a while (true) loop with an if statement

if (num == 0) {
    break;
}

With everything I have tried so far, the loop will not stop even when 0 is inputted.

1 个答案:

答案 0 :(得分:0)

1)声明一个和变量

2)启动无限循环

3)阅读用户输入

4)将其添加到sum变量

5)如果用户输入为0,则跳出循环并打印sum的值。

import java.util.Scanner;

public class Statictest {
    public static void main(String[] args) {
        int sum = 0;
        Scanner scn = new Scanner(System.in);   
        while (true) {
            int temp = scn.nextInt();
            if (temp == 0) {
                break;
            }
            sum += temp;
        }   
        System.out.println("Sum: " + sum);
    }
}