一旦循环结束,循环内的值是否会丢失?

时间:2016-10-15 23:20:19

标签: java

我正在做一个名为"面向对象的Java编程"

的在线课程

我无法弄明白exercise 36 ..

  

创建一个程序,要求用户输入数字(整数)。程序打印"键入数字“直到用户键入数字-1。当用户输入数字-1时,程序会打印"谢谢你,以后再见!"和用户输入的数字之和(没有数字-1)。

import java.util.Scanner;

public class LoopsEndingRemembering {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        int n = 0;
        int sum = 0;
        while (n != -1) {
            System.out.println("Type numbers");
            n = Integer.parseInt(reader.nextLine());
            sum = sum + n; // <-- The value set here is tossed once the loop of over?..
        }
        System.out.println("Thank you and see you later!");
        System.out.println("The sum is " + sum); // <-- Does not acknowledge the free state of 'loop' and any variables that come of it        
    }
}

因此,当我点击“本地运行测试”时, (它是一个插件 Netbeans中的按钮我得到了:

  

输入1 -1你应该打印&#34;总和是1&#34;预期:其中1为卤素;但是:&lt; 0&gt;

根据我的理解,&#39; 0&#39;表示最后一个println只识别&#39; sum&#39; ...的初始化。为什么会这样?..

1 个答案:

答案 0 :(得分:1)

在循环时更改你,将用户输入检查为循环中的最后一项。例如:

public static void loopTest()
{
    Scanner reader = new Scanner(System.in);
    int n = 0;
    int sum = 0;
    System.out.println("Type a number then press enter... type '-1' to sum the numbers and exit");
    n = Integer.parseInt(reader.nextLine());
    while (n != -1)
    {
       sum = sum + n;
       n = Integer.parseInt(reader.nextLine());
    } 
    System.out.println("Thank you and see you later!");
    System.out.println("The sum is " + sum ); // <-- Does   
}