1

I want to make a loop where the user inputs multiple values and when they want to stop input their values they input -1. I know it has to use a sentinel but I don't know how.

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);
walen
  • 7,103
  • 2
  • 37
  • 58
Shancamilo
  • 13
  • 3

3 Answers3

0

I think your main problem is that values is declared inside the while loop. Try putting the declaration before the loop.

int values = 0;
while(values >= 0)
{
    ...
}
d512
  • 32,267
  • 28
  • 81
  • 107
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);
        }

}
Sunil Prajapati
  • 330
  • 2
  • 6
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();
}

Out put will be like this:
output

Community
  • 1
  • 1
Lahiru
  • 1,428
  • 13
  • 17