你将编写一个Java程序来玩Pico,Fermi,Bagel的游戏。以下是游戏规则:
计算机将生成一个秘密"三位数随机。第一个数字不是0,所有数字都不同。用户试图猜测数字。如果用户猜对了,游戏就结束了。
如果没有,计算机会提示并且玩家再次尝试。提示:
对于在适当位置与秘密号码匹配的每个数字,计算机会打印" Fermi"
对于匹配但不在适当位置的每个数字,计算机会打印" Pico"
如果没有数字匹配,则计算机会打印" Bagels"
该程序将有一个主类和一个Bagels类。百吉饼类将调用其他3种方法
1)生成密码
2)确定当前猜测是否为赢家
3)评估当前的猜测和打印提示
我的问题:当我运行我的程序时,它要求我输入一个3位数字,但它只是反复要求我反复输入3位数字。我很确定这个问题与我的Bagels类中的方法有关。我的编译器说generateSecretNumber
和printHint
方法未使用。唯一的问题是,我不确定如何制作它以便使用它们。
主要课程
package assignment.iii;
import javax.swing.JOptionPane;
import java.util.Scanner;
public class AssignmentIII {
public static void main(String[] args) {
int playagain = JOptionPane.showConfirmDialog(null, "Would you like to play?", "Message", JOptionPane.YES_NO_OPTION);
while (playagain == JOptionPane.YES_OPTION) {
Bagels myBagels = new Bagels();
myBagels.playGame();
myBagels.randNumber = 0;
playagain = JOptionPane.showConfirmDialog(null, "Would you like to play again?", "Message", JOptionPane.YES_NO_OPTION);
}
}
}
百吉饼课
package assignment.iii;
import java.util.Random;
import javax.swing.JOptionPane;
public class Bagels {
public int randNumber;
private int Guess;
private int Rand1, Rand2, Rand3;
private int Guess1, Guess2, Guess3;
private int guessCount;
public void playGame() {
if (Guess1 == 0 || Guess1 == Guess2 || Guess2 == Guess3 || Guess1 == Guess3);
JOptionPane.showMessageDialog(null, "Please enter another number" +
"the first digit can't be 0 and no digits can repeat");
do {
Guess = Integer.parseInt(JOptionPane.showInputDialog("Enter a three digit number"));
} while (Guess != randNumber);
if (Guess == randNumber)
System.out.println("It took you " + guessCount + " guesses.");
}
private int generateSecretNumber() {
Random randN = new Random();
return randN.nextInt(999)+1;
}
private void printHint(String guess) {
if (randNumber == Guess)
System.out.println("Correct");
else {
Guess1 = (Guess) / 100;
Guess2 = (Guess % 100) / 10;
Guess3 = (Guess % 100) % 10;
}
if (Guess1 == Rand1) {
System.out.println("Fermi");
}
if (Guess2 == Rand2) {
System.out.println("Fermi");
}
if (Guess3 == Rand3) {
System.out.println("Fermi");
}
if (Guess2 == Rand1) {
System.out.println("Pico");
}
if (Guess3 == Rand1) {
System.out.println("Pico");
}
if (Guess1 == Rand2) {
System.out.println("Pico");
}
if (Guess3 == Rand2) {
System.out.println("Pico");
}
if (Guess1 == Rand3) {
System.out.println("Pico");
}
if (Guess2 == Rand3) {
System.out.println("Pico");
} else if(Guess1 != Rand1 && Guess1 != Rand2 && Guess1 != Rand3 &&
Guess2 != Rand1 && Guess2 != Rand2 && Guess2 != Rand3 &&
Guess3 != Rand1 && Guess3 != Rand2 && Guess3 != Rand3) {
System.out.println("Bagels");
}
guessCount++;
}
}
答案 0 :(得分:2)
generateSecretNumber和printHint方法表示它们未被使用。
是的,这是核心问题。
您将要猜测的数字初始化为零
myBagels.randNumber = 0;
然后再也没有将它设置为另一个值,所以你的循环
while (Guess != randNumber);
将继续,直到有人猜到0。
唯一的问题是我不确定如何制作它以便使用它们。
有很多选择。一个选项是,在playGame()的开头,调用它
randNumber = generateSecretNumber();