使用来自用户的数字输入退出循环

时间:2015-03-18 06:34:51

标签: java loops input exit

我可以问一下这个问题的解决方案是什么?当用户输入-1时,这将包含在总数中,这不是我们想要的。我试图在不使用 if 控制结构的情况下执行此操作。

    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);

我知道我可以使用字符串并使用退出代码作为字符串,同时将String输入解析为整数,但是我试图用整数(在这种情况下,-1)来实现它。 / p>

由于

3 个答案:

答案 0 :(得分:3)

如果你在循环之前读取第一个输入,你可以在没有if语句的情况下实现你想要的东西:

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();
}

这是一种缩短代码的方法:

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");
}

答案 1 :(得分:0)

您还可以使用do...while循环来解决问题。

    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) 

答案 2 :(得分:0)

使用do-while循环:

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);