在Java while循环中添加值并使用sentinel将其停止

时间:2017-03-31 04:30:14

标签: java while-loop sentinel

我想创建一个用户输入多个值的循环,当他们想要停止输入他们输入-1的值时。我知道它必须使用哨兵,但我不知道如何。

Scanner myInput = new Scanner(System.in);
int total = 0;
int count = 0;

while(values >= 0)
{
    int values;
    total += values;
    count ++;

    System.out.println("Please input your value, type - 1 to stop entering values.");
    values = myInput.nextInt();       
}

System.out.println ("The sum of all your values is " + total);

3 个答案:

答案 0 :(得分:0)

我认为您的主要问题是在views循环内声明了values。尝试在循环之前放置声明。

while

答案 1 :(得分:0)

import java.util.Scanner;
class Demo{


    public static void main(String args[]){
                java.util.Scanner myInput = new java.util.Scanner(System.in);

                int total = 0; int count = 0;
                int values=0;

                while(values >= 0)

                {


                        total += values; count ++;

                        System.out.println("Please input your value, type - 1 to stop entering values."); values = myInput.nextInt();

                }

                System.out.println ("The sum of all your values is " + total);
        }

}

答案 2 :(得分:0)

public static void main(String[] args) {
    Scanner myInput = new Scanner(System.in);
    System.out.println("Please input your value, type - 1 to stop entering values.");
    int values = 0;
    int total = 0;

    while (values >= 0) {
        total += values;
        values = myInput.nextInt();
    }
    System.out.println("The sum of all your values is " + total);
    myInput.close();
}

出局将是这样的:
output