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/