输入“ q”后如何完全结束循环?

时间:2019-02-13 22:52:46

标签: java while-loop

输入“ q”后程序不会停止;它仍然会打印随机数及其总和。我希望程序在输入“ q”后立即完全停止。

import java.util.Scanner;
import java.util.Random;
public class lab7
{
public static void main(String[] args)
{
    Scanner input = new Scanner(System.in);
    Random rand = new Random();
    String letter = " ";
    int num = 0;
    System.out.print("Push your luck");
      */the program prints push your luck! 
    while(!letter.equals("q")){
        int sum = rand.nextInt(12);
        System.out.println(" ");
        letter = input.nextLine();
         */ the program should not print random number or sum when input "q" 
         */but in this case it does
        System.out.println("Random number: " + sum);
        System.out.println("Updated number: " + num);
        num = num + sum;
}
}
}

5 个答案:

答案 0 :(得分:1)

首先给变量赋予有意义的名称。因此,sed -e "s/\(,'[^']*\)'\([^']*@[^']*',\)/\1\2/" 应该是num,而sum应该是sum
接下来,像这样在循环内重新排列代码:

num

循环中的Scanner input = new Scanner(System.in); Random rand = new Random(); String letter = " "; int sum = 0; System.out.print("Push your luck"); while (!letter.equals("q")) { int num = rand.nextInt(12); System.out.println(" "); letter = input.nextLine(); if (!letter.equals("q")) { sum = sum + num; System.out.println("Random number: " + num); System.out.println("Updated number: " + sum); } } 语句可防止在输入if时执行任何其他代码。

答案 1 :(得分:0)

看起来像你想做的:

letter = input.nextLine();
while(!letter.equals("q")) {
    int sum = rand.nextInt(12);
    System.out.println(" ");
    System.out.println("Random number: " + sum);
    System.out.println("Updated number: " + num);
    num = num + sum;
    letter = input.nextLine();
}

答案 2 :(得分:0)

只需将输入移动到循环的最后一行,并在前面添加一个输入即可。这样一来,总是在收到输入后立即检查循环条件。

letter = input.nextLine();
while(!letter.equals("q")){
        int sum = rand.nextInt(12);
        System.out.println(" ");
        System.out.println("Random number: " + sum);
        System.out.println("Updated number: " + num);
        num = num + sum;
        letter = input.nextLine();
}

答案 3 :(得分:0)

您可以创建一个if子句来检查是否输入了q,并使用break;语句停止它。在这种情况下,continue语句也适用。

答案 4 :(得分:0)

一个for循环应该做。

for(String aletter = input.nextLine();!aletter.equals("q");aletter=input.nextLine()) { 
    int sum = rand.nextInt(12);
    System.out.println(" ");
    System.out.println("Random number: " + sum);
    System.out.println("Updated number: " + num);
    num = num + sum;
}

而且,由于您不使用输入,因此可以将其简化:

while(!input.nextLine().equals("q")) { 
    int sum = rand.nextInt(12);
    System.out.println(" ");
    System.out.println("Random number: " + sum);
    System.out.println("Updated number: " + num);
    num = num + sum;
}

如果您想要至少一个输出,然后才能使用“ q”将其停止:

do { 
    int sum = rand.nextInt(12);
    System.out.println(" ");
    System.out.println("Random number: " + sum);
    System.out.println("Updated number: " + num);
    num = num + sum;
}while(!input.nextLine().equals("q"));