每次循环后,如何在循环中将变量的值添加到自身?

时间:2019-09-24 13:47:02

标签: java

练习是将所有用户输入的总和相加。

我似乎无法弄清楚如何写sum =所有“ read”的值。

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    int sum = 0;


    System.out.println("Enter numbers:");
    while (true) {
        int read = Integer.parseInt(input.nextLine());
        if (read == 0) {
            break;
        }

        read = 

        System.out.println("Sum now: " + sum);
    }

    System.out.println("Sum in the end: " + sum);

}

感谢所有帮助。

3 个答案:

答案 0 :(得分:1)

这应该通过以下方式实现:

public static void main(String[] args) {

    int sum = 0;

    System.out.println("Enter numbers:");
    try (Scanner input = new Scanner(System.in)) {
        while (true) {
            int read = Integer.parseInt(input.nextLine());
            if (read == 0) {
                break;
            }

            sum += read;

            System.out.println("Sum now: " + sum);
        }
    }

    System.out.println("Sum in the end: " + sum);

}

答案 1 :(得分:0)

sum = sum + read

sum += read

答案 2 :(得分:0)

public static void main(String[] args) {
        int sum = 0;
        try (Scanner input = new Scanner(System.in)) {
            System.out.println("Enter numbers:");
            while (sum >= 0) {
                int read = input.nextInt();
                sum +=read;
                if (read == 0) {
                    break;
                }
                System.out.println("Sum now: " + sum);
            }
        } catch (Exception e) {
            System.out.println("Please Enter numbers only");
        }
        System.out.println("Sum in the end: " + sum);
    }