如何将一个随机int转换为一个可以在Java中使用和比较的变量



我知道这不是一个好代码,但我在第30行需要帮助,如果(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");
}

相关内容

最新更新