如何将一个随机整数变成一个我可以在 Java 中使用和比较的变量?

How do I make a random int into a variable I can use and compare in Java?

我知道这不是很好的代码,但我需要在第 30 行使用 if (guess == roll) 获得帮助,如果你猜对了数字,它会说你赢了,如果没有,它不会说你赢了赢了。

import java.util.Random;
import java.util.Scanner;

public class diceGame 
{
 public static void main(String[] args) 
 {
    Scanner scan = new Scanner(System.in);
    diceGame test = new diceGame();
     
    System.out.println("Number of rolls?: ");
    int numRoll = scan.nextInt();
    
    System.out.println("Gues the number/most common number: ");
    int guess = scan.nextInt();
     
     Random rand = new Random();
    
            for(int i = 0; i < roll.length; i++)
            {
            roll[i] = rand.nextInt(6)+1;
            }
            
        for(int i = 0; i < roll.length; i++)
        {
        System.out.print(roll[i] + ", ");
        }
 
        
        if (guess == roll)
        {
            System.out.println("Good job you guess correct");
        }
        else
        {
            System.out.println("You did not guess correct");
        }
 } 
    
 }

如果您想在 n 次掷骰后猜出频率最高的数字,您可以将每个掷骰的 计数更新 到一个数组中,而不是存储掷骰结果每个卷入数组:

for(int i = 0; i < roll.length; i++)
{
    roll[rand.nextInt(6)]++;   //store count of each roll
}

要找出您是否猜中了最频繁的滚动,请找到数组的最大值(最常滚动的数字):

int maxIdx = 0;

for(int i = 0; i < roll.length; i++)
{
    if(roll[i] > roll[maxIdx])
        maxIdx = i;
}

将您的猜测与最常见的数字进行比较:

if (guess == maxIdx+1)  //+1 to maxIdx to offset array start index
{
    System.out.println("Good job you guess correct");
}
else
{
    System.out.println("You did not guess correct");
}