我正在处理一些代码。我陷入其中涉及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();
}
}
答案 0 :(得分:4)
您只生成两个随机数(index1
和index2
),然后在循环中多次使用它们。
您应该为循环的每次迭代生成新的随机数:
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] + ",");
}
答案 1 :(得分:0)
您正在循环开始之前调用rand.nextInt
,因此在整个循环中它们的值相同。您需要在循环内移动这两行。