gpt4 book ai didi

java - 要求用户仅重试三个答案之一? (java)

转载 作者:行者123 更新时间:2023-12-01 13:40:00 24 4
gpt4 key购买 nike

我用 Java 编写了一个小程序,要求用户选择三张卡片,范围从 4 到 6。这是一个有点草率的代码,但它有效。生成三个随机数(4 到 6)。如果用户按照正确的顺序猜出这些数字,他就赢了。现在,如果用户第一次没有猜对所有卡片,应该有一个选项可以改变他的猜测。用户应通过插入 1、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);
}
System.out.println("My hand of cards: " + "[" + card[0] + "]" + "[" + card[1] + "]" + "[" + card[2] + "]\n");


int count = 0;
for (int i=0; i<3; i++){
if (card[i] == guess[i])
count++;
}

if (count == 3){
System.out.println("Congratulations, you have won!");
} else{
System.out.println("I'm sorry, you lost!");
}
}
}

最佳答案

像这样怎么样:

System.out.println("Would you like to change one of your guesses? yes/no");
if(scan.next() == "yes")
{
System.out.println("What guess would you like to change? 1/2/3");
if(scan.nextInt() == 1 || scan.nextInt() == 2 || scan.nextInt() == 3)
{
int temp = scan.nextInt();
System.out.println("What is your new guess?");
guess[temp-1] == scan.nextInt(); // -1 because array index starts at 0
}
else
System.out.println("That's not a valid guess number");
}

这是一个非常基本的示例。您可以将其变得像您想要的那样复杂。例如,通过添加循环提示用户再次询问他们的猜测是否无效。

关于java - 要求用户仅重试三个答案之一? (java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20909404/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com