gpt4 book ai didi

java - 掷骰子计划

转载 作者:行者123 更新时间:2023-12-01 18:34:54 26 4
gpt4 key购买 nike

我已经整理了这个程序的一般意义,我只需要“较小或较大”部分的帮助,这使得它无法完成。我确实知道“<==>”是不可行的;它作为占位符存在,直到我知道该放什么。我应该放两行吗?一个用于“<=”,一个用于“">=”还是其他方法?

问题:

编写一个掷骰子的程序(但对玩家隐藏数字),然后要求用户输入 1 - 6 范围内的数字。如果玩家输入与计算机掷骰子相同的数字,则玩家将获得 10 美元。如果玩家输入比 1 小或大的数字,那么玩家将赚取 3 美元。如果玩家输入的数字小于或大于 2,那么玩家将赚取 1 美元。玩家必须支付 3 美元才能玩一次。制作一个 MatchDice 游戏。提示:使用 Math.random() 方法计算随机值。

我的代码:

import java.util.*;

public class RollDice {

public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
Random dice = new Random();

// Generate the random number, between 1 and 6
int randomValue = (int)(Math.random()*6) + 1;
int dealerValue = (int)(Math.random()*6) + 1;

System.out.println("Dealer rolled a dice and here is your turn.");
System.out.print("Enter a number : ");
int randomValue = input.nextInt();

if(randomValue == dealerValue)
System.out.println("Dealer's number was " + randomValue);
System.out.println("You won $10 ");
else if(randomValue == dealerValue <==> 1)
System.out.println("Dealer's number was " + randomValue);
System.out.println("You won $3 ")
else if(randomValue == dealerValue <==> 2)
System.out.println("Dealer's number was " + randomValue);
System.out.println("You won $1 );
else
System.out.println("You lost $3 ");
}
}

最佳答案

使用Math.abs(a - b),其中a是用户编号,b是...好吧,你知道。

更新

这是完整的解决方案,修复了错误并最大限度地减少了重复。

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
static Random rnd = new Random();

static int dice() {
return rnd.nextInt(6) + 1;
}

public static void main(String[] args) throws IOException
{
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

int dealerValue = dice();

System.out.print(
"Dealer rolled a dice and here is your turn.\n" +
"Enter a number: ");

int userValue = Integer.parseInt(input.readLine());

int difference = Math.abs(randomValue - userValue);

int profit =
difference == 0 ? 10 :
difference == 1 ? 3 :
difference == 2 ? 1 :
-3;

System.out.println("Dealer's number was " + dealerValue);
System.out.println("You " + ((profit >= 0) ? "won" : "lost") + " $" + Math.abs(profit));
}
}

关于java - 掷骰子计划,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22430181/

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