如何重复"if"?输出为假时的语句 [英] How to repeat "if" statement when output is false

查看:49
本文介绍了如何重复"if"?输出为假时的语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个简单的游戏,用户必须猜测一个随机数.我设置了所有代码,但事实是,如果猜得太高或太低,我都不知道如何让他们重新输入一个数字并继续玩直到他们得到为止.它只是停止;这是代码:

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

推荐答案

要重复任何操作,您需要循环.

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.

在Java中形成无限循环的惯用方式是 while(true):

Idiomatic way of making an infinite loop in Java is 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");
    }
}

此循环将继续其迭代,直到代码路径到达 break 语句.

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

这篇关于如何重复"if"?输出为假时的语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆