英文:
How do I make a random int into a variable I can use and compare in Java?
问题
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("Guess the number/most common number: ");
int guess = scan.nextInt();
Random rand = new Random();
int[] roll = new int[numRoll];
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] + ", ");
}
boolean correctGuess = false;
for (int i = 0; i < roll.length; i++) {
if (guess == roll[i]) {
correctGuess = true;
break;
}
}
if (correctGuess) {
System.out.println("Good job, you guessed correctly!");
} else {
System.out.println("You did not guess correctly.");
}
}
}
英文:
its not great code I know but I need help at line 30 with if (guess == roll) im trying to make it if you guess the number right it will say you win and if not it will not say you win.
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");
}
}
}
答案1
得分: 0
如果你想在n次掷骰子后猜测出出现频率最高的数字,你可以将每个掷骰子的结果的计数更新到一个数组中,而不是将每次掷骰子的结果存储到数组中:
for(int i = 0; i < roll.length; i++)
{
roll[rand.nextInt(6)]++; // 存储每个骰子的计数
}
要找出你猜测的最频繁的点数是否正确,找到数组中的最大值(最常掷出的数字):
int maxIdx = 0;
for(int i = 0; i < roll.length; i++)
{
if(roll[i] > roll[maxIdx])
maxIdx = i;
}
要将你的猜测与最常见的数字进行比较:
if (guess == maxIdx+1) // +1 以补偿数组的起始索引
{
System.out.println("恭喜你猜对了");
}
else
{
System.out.println("你没有猜对");
}
英文:
If you would like to guess the number with the highest frequency after n number of rolls, you can update the count of each roll into an array instead of storing the roll outcome of each roll into the array:
for(int i = 0; i < roll.length; i++)
{
roll[rand.nextInt(6)]++; //store count of each roll
}
To find out if you guessed the most frequency roll, find the maximum value (most commonly rolled number) of the array:
int maxIdx = 0;
for(int i = 0; i < roll.length; i++)
{
if(roll[i] > roll[maxIdx])
maxIdx = i;
}
To compare your guess against the most common number:
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");
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论