Java 输出为假时如何重复“if”语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32772938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 13:03:14  来源:igfitidea点击:

How to repeat "if" statement when output is false

javaif-statementrepeat

提问by Trevn Jones

I am working on a simple game in which the user has to guess a random number. I have all the code set up except for that fact that if the guess is too high or too low I don't know how to allow them to re-enter a number and keep playing until they get it. It just stops; here is the code:

我正在开发一个简单的游戏,用户必须在其中猜测一个随机数。我已经设置了所有代码,除了如果猜测太高或太低我不知道如何让他们重新输入一个数字并继续玩直到他们得到它。它只是停止;这是代码:

import java.util.Scanner;
import java.util.Random;

public class Test {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        Random rand = new Random();

        int random = rand.nextInt(10) + 1;

        System.out.print("Pick a number 1-10: ");
        int number = input.nextInt();

        if (number == random) {
            System.out.println("Good!");
        } else if (number > random) {
            System.out.println("Too Big");
        } else if (number < random) {
            System.out.println("Too Small");
        }
    }
}

采纳答案by dasblinkenlight

In order to repeat anything you need a loop.

为了重复任何事情,你需要一个循环。

A common way of repeating until a condition in the middle of loop's body is satisfied is building an infinite loop, and adding a way to break out of it.

重复直到满足循环体中间的条件的一种常见方法是构建一个无限循环,并添加一种方法来打破它。

Idiomatic way of making an infinite loop in Java is while(true):

在 Java 中进行无限循环的惯用方法是while(true)

while (true) {
    System.out.print("Pick a number 1-10: ");
    int number = input.nextInt();
    if (number == random) {
        System.out.println("Good!");
        break; // This ends the loop
    } else if (number > random) {
        System.out.println("Too Big");
    } else if (number < random) {
        System.out.println("Too Small");
    }
}

This loop will continue its iterations until the code path reaches the breakstatement.

这个循环将继续迭代,直到代码路径到达break语句。

回答by Lock

You could use a do...while.

你可以使用一个do...while.

Random rand = new Random();
int random = rand.nextInt(10) + 1;
do {
  Scanner input = new Scanner(System.in);

  System.out.print("Pick a number 1-10: ");
  int number = input.nextInt();

  if (number == random) {
    System.out.println("Good!");
  } else if (number > random) {
    System.out.println("Too Big");
  } else if (number < random) {
    System.out.println("Too Small");
  }

} while ( number != random );

回答by mcleod_ideafix

Enclose the if statements within a do-while loop, that will loop around while the user hasn't guessed the number:

将 if 语句括在 do-while 循环中,当用户没有猜到数字时,它将循环:

 int number;
 do {
    System.out.print("Pick a number 1-10: ");
    number = input.nextInt();

    if (number == random) {
        System.out.println("Good!");
    } else if (number > random) {
        System.out.println("Too Big");
    } else if (number < random) {
        System.out.println("Too Small");
    }
 } while (number != random);

回答by tstark81

You need to use a loopfor that. The code should work like this:

您需要为此使用循环。代码应该像这样工作:

import java.util.Scanner;
import java.util.Random;

public class Test {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        Random rand = new Random();

        int random = rand.nextInt(10) + 1;

        System.out.print("Pick a number 1-10: ");
        int number = input.nextInt();

        boolean found = false;
        while (!found) {
           if (number == random) {
                System.out.println("Good!");
               found = true;
            } else if (number > random) {
                System.out.println("Too Big, try again:");
                number = input.nextInt();
            } else if (number < random) {
                System.out.println("Too Small, try again:");
                number = input.nextInt();
            }
        }
    }
}

回答by darkryder

What you're looking for are constructs in the programming language that allow you do a specific thing again and again.

您正在寻找的是编程语言中的构造,它允许您一次又一次地做特定的事情。

This is done using loops. Check the docs for the while loopfor instance. That's what you need.

这是使用循环完成的。例如,检查while 循环文档。这就是你所需要的。

回答by intcreator

In order to repeat code conditionally, use a loop.

为了有条件地重复代码,请使用循环。

// this code will execute only once
System.out.print("Pick a number 1-10: ");
// initialize number to a value that would not be used and not equal random
int number = -1;

// the code inside the curly braces will repeat until number == random
while (number != random) {
    // get next number
    number = input.nextInt();
    // handle case one
    if(number > random) System.out.println("Too Big");
    // handle case two
    if(number < random) System.out.println("Too Small");
}
// once number == random, the condition is false so we break out of the loop
System.out.println("Good!");

回答by mvw

Several techniques exist to loop your request, among them:

存在多种技术来循环您的请求,其中包括:

  • while (<condition>) { <do something> }

  • do { <something> } while (<condition>);

  • for (<init statement>, <condition>, <update statement>) { <do something> }

  • while (<condition>) { <do something> }

  • do { <something> } while (<condition>);

  • for (<init statement>, <condition>, <update statement>) { <do something> }

To show off, you can avoid using one of the above explicit loop constructs by using recursion:

为了炫耀,您可以通过使用递归来避免使用上述显式循环结构之一:

mport java.util.Scanner;
import java.util.Random;

public class Test {

    public static void ask(int random) {
        Scanner input = new Scanner(System.in);
        System.out.print("Pick a number 1-10: ");
        int number = input.nextInt();

        if (number == random) {
            System.out.println("Good!");
        } else if (number > random) {
            System.out.println("Too Big");
            ask(random);
        } else if (number < random) {
            System.out.println("Too Small");
            ask(random);
        }
    }


    public static void main(String[] args) {
        Random rand = new Random();

        int random = rand.nextInt(10) + 1;
        ask(random);
    }
}

Here the ask()method keeps calling itself, until the end condition (user guessed right) is reached.

在这里,该ask()方法不断调用自身,直到达到结束条件(用户猜对了)。

Depending on the cleverness of the Java virtual machine this might stress the call stack, or not.

根据 Java 虚拟机的聪明程度,这可能会对调用堆栈造成压力,也可能不会。