简体   繁体   中英

Exiting loop with numeric input from user

may I ask what are some proposed solutions to this issue? When the user enters -1, this will be included into the total, which is not what we want. I am trying to do this without the use of an if control structure.

    int numberToAdd = 0, total = 0;
    Scanner input = new Scanner(System.in);

    while (numberToAdd != -1) {
        System.out.println("Number to add? -1 to quit");
        numberToAdd = input.nextInt();
        total = total + numberToAdd;
    }
    System.out.println("Total: = " + total);

I am aware that I can instead use strings and use an exit code that is a string, whilst parsing String inputs as an integer, however I am trying to accomplish that with an integer (in this case, -1).

Thanks

You can achieve what you want without an if statement if you read the first input prior to the loop :

System.out.println("Number to add? -1 to quit");
numberToAdd = input.nextInt();
while (numberToAdd != -1) {
    total = total + numberToAdd;
    System.out.println("Number to add? -1 to quit");
    numberToAdd = input.nextInt();
}

Here's a way to make the code shorter:

System.out.println("Number to add? -1 to quit");
while ((numberToAdd = input.nextInt()) != -1) {
    total = total + numberToAdd;
    System.out.println("Number to add? -1 to quit");
}

You can also use do...while loop to solve your problem.

    int numberToAdd = 0, total = 0;
    Scanner input = new Scanner(System.in);
    System.out.println("Number to add? -1 to quit");

   do{
         total = total + numberToAdd;
         System.out.println("Number to add? -1 to quit");
         numberToAdd = input.nextInt();
     }while(numberToAdd != -1) 

Use do-while loop:

int numberToAdd = 0, total = 0;
Scanner input = new Scanner(System.in);

do {
    total += numberToAdd;
    System.out.println("Number to add? -1 to quit");            
    numberToAdd = input.nextInt();
} while (numberToAdd != -1);

System.out.println("Total: = " + total);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM