我想创建一个程序,让您尝试三次查找任何给定的数字。它基本上是一个猜谜游戏。问题是,我必须在没有任何循环的情况下这样做。到目前为止,我只能从用户那里获得输入,阅读该输入并告诉他们他们是否赢了或“输了”游戏。程序只运行一次并停止(如预期的那样)。
我被告知可以在没有循环的情况下完成,尽管代码更多。你能告诉我这里我做错了什么,并给我一些关于我应该改变什么的指示?如果您需要澄清,请告诉我。 感谢。
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");
}
}
答案 0 :(得分:1)
您可以使用递归来完成此操作。看这个程序。在评论中查找解释。
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");
}
}
答案 1 :(得分:0)
你可以接下来的条件:
get user input
if input is correct, congratulation user and exit
else
get user input //second attempt
if input is correct, congratulation user and exit
...
你可以从那里继续。您提供的代码,您告诉用户它们是否太高或太低,必须包含在上述伪代码的每个分支中。
答案 2 :(得分:0)
我认为本练习的主要目的是为了加强嵌套的if-else概念。
import java.util.Scanner;
公共类HelloWorld {
public static void main(String []args){
int num=3;
int count=1;
Scanner ran = new Scanner(System.in);
System.out.println("Enter a number: ");
int x = ran.nextInt();
if(x>num || x<num)
{
System.out.println("incorrect guess");
count++;
System.out.println("Enter a number: ");
x = ran.nextInt();
if(x>num || x<num)
{
System.out.println("incorrect guess");
count++;
System.out.println("Enter a number: ");
x = ran.nextInt();
if(x>num || x<num)
{
System.out.println("incorrect guess YOU LOSE");
}
else
{
System.out.println("YOU WIN");
}
}
else
{
System.out.println("YOU WIN");
}
}
if(x==num && count==1)
{
System.out.println("YOU WIN");
}
System.out.println("Number Guessing Game (c) 2017 Anna Gibson");
}
}