Java - 返回相同整数的随机 nextInt 方法

标签 java random

我正在编写一些代码。我被困在其中涉及 Random nextInt() 方法的一部分。我遇到的这个问题是我的代码从我的数组索引返回完全相同的随机整数。我打算做的是遍历一个 for 循环,对于我的 16 次迭代中的每一次,我想让 Random nextInt() 方法通过索引从数组中选择一个字符串并将其打印到屏幕上。目前,我能够从每个索引生成 1 个随机字符串。对于接下来的 15 次迭代,我的代码打印相同的随机选择,而不是随机选择一个新的。

import java.awt.Color;
import java.util.*;
import java.util.Random;

class Main {
    private int numStrings = 6; 
    private double guitarLength = 28.2;
    private String guitarManufacturer = "Gibson";
    private Color guitarColor = Color.RED; 
    private int musicLength = 16;
    private static int i = 1;
    private static Random rand = new Random();

public Main (){
    this.numStrings = numStrings; 
    this.guitarLength = guitarLength;
    this.guitarManufacturer = guitarManufacturer;
    this.guitarColor = guitarColor;
}

public Main (int strings, double length, String manufacturer, Color color){
     numStrings = strings;
     guitarLength = length;
     guitarManufacturer = manufacturer;
     guitarColor = color;
     System.out.printf("%d, %f, %s, %s", numStrings, guitarLength, guitarManufacturer, guitarColor + "\n");
}

public int getNumStrings() {
  return this.numStrings;
}

public double getGuitarLength() {
  return this.guitarLength;
}

public String getGuitarManufacturer() {
  return this.guitarManufacturer;
}

public Color getGuitarColor(){
  return this.guitarColor;
}

public static void playGuitar(){
    String[] musicNotes = {"A", "B", "C", "D", "E", "F", "G"};
    String[] musicDuration = {"(0.25)","(0.5)","(1)", "(2)","(4)"};
    int index1 = rand.nextInt(musicNotes.length);
    int index2 =  rand.nextInt(musicDuration.length);
     for (i = 1; i < 17; i++){
        System.out.print(musicNotes[index1]);
        System.out.print(musicDuration[index2] + ",");
        }
     }

public static void main (String args[] ){
    Main newGuitar = new Main(6, 24.75, "Les Paul", Color.white);
    playGuitar();
 }
}

最佳答案

您只需生成两个随机数(index1index2),然后在循环中多次使用它们。

您应该为循环的每次迭代生成新的随机数:

for (i = 1; i < 17; i++) {
    int index1 = rand.nextInt(musicNotes.length);
    int index2 =  rand.nextInt(musicDuration.length);
    System.out.print(musicNotes[index1]);
    System.out.print(musicDuration[index2] + ",");
}

关于Java - 返回相同整数的随机 nextInt 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52353088/

相关文章:

java - JAssert 库未纳入 Spring Boot 测试

java - android listview setOnScrollListener 不工作

python随机模块种子方法

jquery - 如何添加淡入效果?

c++ - 使自己的随机数类与 uniform_int_distribution 兼容

jquery - 使用 jQuery 随机加载 Div

java - 通过 IRC 的 SSH 客户端输出

java - JVM 如何加载具有自己引用的类

java - 有一个禁用的onClick?

python - 基于单个随机整数的 Python 中的随机连续列表切片