[英]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.