gpt4 book ai didi

Java 基础高 :Low Guessing Game Help (Loops)

转载 作者:行者123 更新时间:2023-12-01 18:29:21 24 4
gpt4 key购买 nike

我已经停止编程有一段时间了。大概四年左右,我只是想玩玩它,所以我决定制作一个高:低的猜数字游戏。 (猜一个数字 1-100,程序会提示你的猜测是否太高或太低),我完全忘记了我将如何进行:

a) 一旦用户猜出正确的数字,询问他们是否想再玩一次b) 如果他们没有猜出正确的数字(太高或太低),程序会让他们再次猜测。

我知道你需要循环,但我只是忘记了如何处理它们

package highlow;

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

public class guessing {
public static void main(String[] args){

Scanner input = new Scanner(System.in);

Random rand = new Random();
int tries;
int correctNum = rand.nextInt(100);

System.out.println("enter a number 1-100");
int guess1 = input.nextInt();

if(guess1 < correctNum){
System.out.println("number is too low!");
}
else if(guess1 > correctNum){
System.out.println("Number is too high!");
}
else if(guess1 == correctNum){
System.out.println("correct!");
}
else{
System.out.println("not a valid option");
}


}

}

最佳答案

您需要将所有内容包装在 while 循环中,以便它不断重复,直到用户猜对为止:

// Make the scanner, get the random number etc... Put all the setup and
// stuff you don't want to be repeated here

while (true) {
System.out.println("enter a number 0-99"); // Changed from 1-100 because rand.nextInt(100)
// returns a number between 0 and 99
// You can do correctNum += 1 to make it between 1 and 100
// But put this in before the while loop starts
int guess1 = input.nextInt();

if(guess1 < correctNum){
System.out.println("number is too low!");
}
else if(guess1 > correctNum){
System.out.println("Number is too high!");
}
else if(guess1 == correctNum){
System.out.println("correct!");
break; // <---- Add this, this will make the loop stop when the
//player gets the answer correct and therefore the program will end
}
else{
System.out.println("not a valid option");
}
}

While 循环重复其内部的所有内容,直到其 () 内的语句为 false。在我们的例子中,循环将永远进行,因为 true 位于 () 内部,但使用 break 语句,当用户猜测时循环将结束正确。

关于Java 基础高 :Low Guessing Game Help (Loops),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24973305/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com