显示多骰子滚筒的特定输出

displaying a certain output for a multi dice roller

我是 java 的新手,我为自己设定了一个目标来制作一个骰子滚动程序(保持小)。最终目标是能够掷出用户选择数量的骰子,并能够在需要时让每个骰子有不同的面数,我让它得到骰子的数量和每个骰子有多少面。这是我为它制作的代码(可能真的很糟糕,如果是这样的话抱歉):

public class Roller {
   public final Random rando;
   public final int faces;

   public Roller(int faces) {
       this.rando = new Random();
       this.faces = faces;
   }

   public int roll() {
       return 1 + rando.nextInt(faces);
   }
   //above code is not mine I built off what my friend wrote cause i didnt know if i still need it
   public static void main(String[] args) {
       Random rand = new Random();
       Scanner scan = new Scanner(System.in);
       System.out.print("How many dice do you want to roll?\n");
       int D6 = scan.nextInt();
       ArrayList<Integer> list = new ArrayList<>();
       for (int i = 0; i < D6; i++) {
           System.out.print("How many sides does die " + (i + 1) + " have?\n");
           Roller dice = new Roller(scan.nextInt());
           list.add(dice.roll());
       }
   }
}

现在我想显示 ArrayList 但我想将其显示为

“掷骰子 1 #

掷骰子 2 #"

等而且我不知道如何做到这一点,尤其是对于不同数量的骰子。非常感谢任何帮助。

假设您 运行 现在有一个值列表 [1, 3, 5, 2, 4] 并且您想按照您的描述显示它们。

在您的 main 方法中,您有列表,因此您可以进行一些循环和字符串格式化以获得所需的输出。 (编辑为使用 printf() 而不是 String.format())

// in main...
// after list has all it's values
for (int i = 0; i < list.size(); i++) {
    System.out.printf("Dice #%d rolled %d", i+1, list.get(i));
}

请注意,以下语句仍然有效,并且仍可应用于 printf(...)

To walk through it, String formatting is just a fancy way to format your strings (funny how that works out). The first %d corresponds to the first value given to format(), which is i+1. It's i+1 as opposed to plain i because otherwise you'd see "Dice #0 rolled ..." first, since you start indexing arrays and lists at 0. With the second %d in the format() call, you pass in list.get(i) which is the value in the list at the given index. This should correspond nicely to the order of the rolls.

不必使用字符串格式来完成此操作。我发现它往往更好,更容易个人阅读,但它很容易用字符串连接代替。

//replace the print statement with this if you want
System.out.println("Dice #" + (i+1) + " rolled " + list.get(i));

IMO 对我来说似乎比较草率,而且需要记住在连接的部分之间留空格或省略空格可能很烦人。