用Java更改自己的答案

用Java更改自己的答案,java,random,Java,Random,我目前正在用Java编写一个程序。这是一个纸牌游戏,你必须猜测三张牌(4、5或6)随机生成的数字。如果你猜对了数字的顺序,你就赢了。如果您第一次没有按照正确的顺序猜到这些数字,您可以只重试一张卡。到目前为止,所有这些我都工作了,但是当我想更改第二个或第三个答案时,我必须键入“2”两次或“3”三次才能更改这些卡片。这是我的密码: package cardgame; import java.util.Scanner; public class CardGame { public static

我目前正在用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");
    }
  }

如你所见,我必须插入两次。另外,我的新猜测是第二名6分,而第二名应该是4分。我哪里出错了?我似乎无法修复它。

您在这一行中呼叫了
scan.nextInt
最多3次:

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){

哦,真是个愚蠢的错误!谢谢你指出。现在很有魅力。