我是编程的新手,我正在制作一个猜谜游戏,程序随机生成一个介于1到10之间的数字,然后要求用户猜出该数字是什么,用户应该能够继续猜测,直到他猜对了,系统问他们是否想再玩一次, 在我的代码中,我打印了系统随机生成的数字,以便在测试时更快地完成游戏。当我尝试执行程序并输入系统已生成的数字时,它们是正确的并且询问是否要再次播放的消息不会出现。
任何帮助将不胜感激! 提前谢谢你,
(另外,这个问题有什么问题只是告诉我,这是我第一次在这里询问)
这是我的代码,
import java.util.Scanner;
import java.util.Random;
public class GuessingGame1 {
public static int randomizer() {
Random rand = new Random();
int num = rand.nextInt(10)+1;
System.out.println(num);
int count = 0;
return num;
}
public static int userInput() {
System.out.println("I've thought of a number between 1 and 10");
System.out.println("Enter your guess...");
Scanner scan = new Scanner(System.in);
int guess = scan.nextInt();
return guess;
}
public static String compare() {
int count = 0;
String result = null;
if (userInput() == randomizer()) {
System.out.println("You guessed it - I was thinking of " + randomizer());
count++;
result = "It took you " + count + " guesses.";
return result;
}
else if (userInput() > randomizer()) {
result = "Lower!";
count++;
return result;
}
else if (userInput() < randomizer()) {
result = "Higher";
count++;
}
return result;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner scanLine = new Scanner(System.in);
String playAgain = "";
do {
randomizer();
do {
userInput();
compare
} while (userInput() != randomizer());
System.out.println("Play again? Yes/No");
playAgain = scanLine.nextLine();
} while (playAgain.equalsIgnoreCase("yes") || playAgain.equalsIgnoreCase("y"));
}
}
答案 0 :(得分:0)
问题是你给Randomizer打了两次电话!
调用randomizer一次作为参数进行比较,并从匹配中返回boolean返回布尔值。
答案 1 :(得分:0)
你必须改变你的方法
public static String compare(int a,int b) {
int count = 0;
String result = null;
if (a == b) {
System.out.println("You guessed it - I was thinking of " + b);
count++;
result = "It took you " + count + " guesses.";
return result;
}
else if (a > b) {
result = "Lower!";
count++;
return result;
}
else if (a < b) {
result = "Higher";
count++;
}
return result;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner scanLine = new Scanner(System.in);
String playAgain = "";
int a;
int b;
do {
do {
a=userInput();
b= randomizer();
System.out.println(compare(a,b));
} while (a != b);
System.out.println("Play again? Yes/No");
playAgain = scanLine.nextLine();
} while (playAgain.equalsIgnoreCase("yes") || playAgain.equalsIgnoreCase("y"));
}
}
答案 2 :(得分:0)
你已经将()保留在比较中,并且当调用compare函数时,计数将始终为零。