gpt4 book ai didi

java - 可能的选择数量有限?

转载 作者:行者123 更新时间:2023-11-30 07:40:11 25 4
gpt4 key购买 nike

这里是 Java 新手。

有这段代码(来自教程),我想知道,我应该使用什么循环或其他方法来将最大猜测选择限制为例如 3?我的意思是用户只能猜测有限的次数,然后程序就会停止。

package com.company;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {
int secretNum;
int guess;
boolean correct = false;

Scanner keybord = new Scanner(System.in);
System.out.print("GIVE ME SECRET NUMBER");
secretNum = keybord.nextInt();

while (!correct){
System.out.println("GUESS: ");
guess = keybord.nextInt();

if (guess == secretNum){
correct = true;
System.out.println("YOU ARE RIGHT");
}
else if (guess < secretNum){
System.out.println("HIGHER");
}
else if (guess > secretNum) System.out.println("LOWER");
}
}
}

最佳答案

您可以使用如下计数器跟踪尝试次数:

public static void main(String[] args) {
int attempts = 0;
Scanner keybord = new Scanner(System.in);
System.out.print("GIVE ME SECRET NUMBER");
int secretNum = keybord.nextInt();

while (true){
System.out.println("GUESS: ");
int guess = keybord.nextInt();
attempts++;

if (guess == secretNum){
System.out.println("YOU ARE RIGHT");
break;
}
if (attempts == 3) {
System.out.println("Max attempts!");
break;
}
else if (guess < secretNum){
System.out.println("HIGHER");
}
else if (guess > secretNum) System.out.println("LOWER");
}
}

关于java - 可能的选择数量有限?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58041165/

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