我目前正在开发 Java 程序。这是一款纸牌游戏,您必须猜测三张牌(4、5 或 6)随机生成的数字。如果您以正确的顺序猜对了数字,您就赢了。如果您第一次没有按正确的顺序猜出这些数字,您可以只重试一张牌。到目前为止,所有这些我都开始工作了,但是当我想更改我的第二个或第三个答案时,我必须输入“2”两次或“3”三次才能更改这些卡片。这是我的代码:
package cardgame;
import java.util.Scanner;
public class CardGame {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int[] guess = new int[3];
int[] card = new int[3];
System.out.println("Pick three cards with numbers ranging from 4 to 6!\n");
for (int i=0; i<3; i++){
System.out.print("Card number " + (i+1) + " (4, 5 or 6): ");
guess[i] = scan.nextInt();
}
System.out.println(" ");
System.out.println("Your hand of cards: " + "[" + guess[0] + "]" + "[" + guess[1] + "]" + "[" + guess[2] + "]");
for (int i=0; i<3; i++){
card[i] = (int) (Math.random() * 3 + 2 +2);
}
int count = 0;
for (int i=0; i<3; i++){
if (card[i] == guess[i])
count++;
}
if (count == 3){
System.out.println("My hand of cards: " + "[" + card[0] + "]" + "[" + card[1] + "]" + "[" + card[2] + "]\n");
System.out.println("Congratulations, you have won!\nType 'end' to end the game and I will show you my hand of cards.");
} else{
System.out.println("Not quite yet there!\n");
}
if (count !=3){
System.out.println("Would you like to change one of your guesses? yes/no");
}
if("yes".equals(scan.next())){
System.out.println("\nWhat card would you like to change? 1/2/3");
{
if(scan.nextInt() == 1 || scan.nextInt() == 2 || scan.nextInt() == 3){
System.out.println("\nWhat is your new guess?");
int secondGuess = scan.nextInt();
if (secondGuess == card[0] || secondGuess == card[1] || secondGuess == card[2]){
count++;
}
if (count == 3){
System.out.println("\nCongratulations, you have won!");
} else{
System.out.println("\nI'm sorry, you lost!");
}
}
}
}
// Print the 3 random numbers card[0], card[1] and card[2]
System.out.println("My hand of cards: " + "[" + card[0] + "]" + "[" + card[1] + "]" + "[" + card[2] + "]\n");
}
}
到目前为止的输出:
Pick three cards with numbers ranging from 4 to 6!
Card number 1 (4, 5 or 6): 4
Card number 2 (4, 5 or 6): 5
Card number 3 (4, 5 or 6): 6
Your hand of cards: [4][5][6]
Not quite yet there!
Would you like to change one of your guesses? yes/no
yes
What card would you like to change? 1/2/3
2
2
What is your new guess?
6
Congratulations, you have won!
My hand of cards: [4][4][6]
如您所见,我必须两次插入两个。另外,我的新猜测是第二名 6 分,要赢得它应该是第二名 4 分。我哪里出错了?我似乎无法修复它。
最佳答案
您在此行中最多调用了 3 次 scan.nextInt
:
if(scan.nextInt() == 1 || scan.nextInt() == 2 || scan.nextInt() == 3){
根据您输入的数字,最多可以读取三个数字。
- 第一个数字是 1:只读取一个数字。
- 第一个数字不是 1,第二个数字是 2:读取了两个数字。
- 否则,读取 3 个数字。
抓取数字一次,然后进行比较:
int someNumber = scan.nextInt();
if(someNumber == 1 || someNumber == 2 || someNumber == 3){
关于java - 用 Java 改变你自己的答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20959938/