[英]How do I return a random specified amount in an array?
我正在制作一个游戏,用户可以选择他们手中的骰子数量。 我的代码不会 output 任何骰子(直到我稍后在我的主程序中使用它)。 当它们稍后出现在我的主目录中时,第一个数字是随机的,但 rest 为零,并且总是有五个骰子(即使我输入我只想要两个或三个)。 有谁知道为什么我的用户输入没有给我正确的 output?
这是我为 output 得到的:
这是我的主要内容:
public class yahtzee {
public static void main(String[] args) {
int play = 1, scorea = 0, sum = 0;
int[] wins = new int[15];
while ((play == 1) && (sum < 15)) {
sum = 0;
int[] Dice = new int[]{0, 0, 0, 0, 0};// creates an array
int roll = 0;
int x, y, w, z;
int rerolla = 0, rerollb = 03;
dice die = new dice();
yahtzeeConfig config = new yahtzeeConfig();
for (x = 0; x < 1; x++) {
Dice[x] = config.Sides();
die.roll();
//Dice[x] = die.get();// sets the dice values
//Dice[x]= config.Sides();
}
System.out.println("\nHere is your roll:\n");
if (Dice[x] == 1) {
System.out.println("Die 1: " + Dice[0]);
}
if (Dice[x] == 2) {
System.out.println("Die 1: " + Dice[0]);
System.out.println("Die 2: " + Dice[1]);
}
if (Dice[x] == 3) {
System.out.println("Die 1: " + Dice[0]);
System.out.println("Die 2: " + Dice[1]);
System.out.println("Die 3: " + Dice[2]);
}
if (Dice[x] == 4) {
System.out.println("Die 1: " + Dice[0]);
System.out.println("Die 2: " + Dice[1]);
System.out.println("Die 3: " + Dice[2]);
System.out.println("Die 4: " + Dice[3]);
}
if (Dice[x] == 5) {
//System.out.println("\nHere is your roll:\n");
System.out.println("Die 1: " + Dice[0]);
System.out.println("Die 2: " + Dice[1]);
System.out.println("Die 3: " + Dice[2]);
System.out.println("Die 4: " + Dice[3]);
System.out.println("Die 5: " + Dice[4]);
}
}
}
}
这是我的 yahtzeeConfig class:
import java.util.Scanner;
import java.util.Random;
class yahtzeeConfig {
public int Sides() {
String file = "yahtzeeConfig.txt";
Scanner scan = new Scanner(System.in);
//configures sides of dice
System.out.println("Enter the number of " +
"sides you would like on each dice (1-6): ");
int sides = scan.nextInt();
return sides;
}
}
如果你想从方法Slides()
中返回 6 个随机数,你可以使用
final int[] dicesRandom = new Random().ints(1, 6).distinct().toArray();
在您的方法中实现
public int[] Sides() {
String file = "yahtzeeConfig.txt";
final int[] dicesRandom = new Random().ints(1, 6).distinct().toArray();
return dicesRandom;
}
在主 class 中,您不需要通过 for 循环,只需调用此方法,它将为您生成 6 个数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.