我想创建一个程序,让您尝试三次来找到任何给定的数字。这本质上是一个猜谜游戏。问题是,我必须在没有任何循环的情况下执行此操作。到目前为止,我只能从用户那里获取输入,读取该输入并告诉他们是赢了还是“输了”游戏。该程序仅运行一次并停止(如预期)。
有人告诉我,尽管需要更多代码,但无需循环即可完成。你们能让我知道我在这里做错了什么,并给我一些关于我应该改变什么的指示吗?如果您需要澄清,请告诉我。 谢谢。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner ran = new Scanner(System.in);
System.out.println("Enter a number: ");
int x = ran.nextInt();
if (x < 3) {
System.out.println("Too low. Try again.");
System.out.println("Enter a number: ");
} else if (x > 3) {
System.out.println("Too high. Try again");
} else if(x == 3) {
System.out.println("You win. Nice job.");
} else {
System.out.println("You lose");
}
System.out.println("Number Guessing Game (c) 2017 Anna Gibson");
}
}
最佳答案
您可以使用递归来完成此操作。看看这个程序。在评论中查找解释。
import java.util.Scanner;
public class HelloWorld {
private static Scanner ran = new Scanner(System.in);
//this is number of tries you want to give to user
private static int counter = 5;
//The actual number
private static final int NUM = 3;
public static boolean guessingMachine() {
//counter indicates that number of attempts remaining
if(counter == 0) {
return false;
}
counter--;
System.out.println("Enter a number: ");
int x = ran.nextInt();
if (x < NUM) {
System.out.println("Too low. Try again.");
//try again... call this method again
return guessingMachine();
} else if (x > NUM) {
System.out.println("Too high. Try again");
//try again... call this method again
return guessingMachine();
} else {
//x == NUM success
return true;
}
}
public static void main(String[] args) {
boolean result = guessingMachine();
if(result)
System.out.println("You win. Nice job.");
else
System.out.println("You lose");
System.out.println("Number Guessing Game (c) 2017 Anna Gibson");
}
}
关于java - 猜一个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43132029/