use*_*906 0 java printing arrays system
嗨,我想知道如何打印出一个数组的随机值而不是其中两个.这是我的代码:
public static void main(String args[])
{
String[] currentRoom;
String[][] rooms = new String [2] [2];
rooms [0] [0] = "Start";
rooms [0] [1] = "Treasure Room 1";
rooms [1] [0] = "Goblin Hive 1";
rooms [1] [1] = "Spider Nest";
Random rand = new Random();
{
currentRoom = rooms[rand.nextInt(rooms.length)];
System.out.println(Arrays.toString(currentRoom));
}
}
Run Code Online (Sandbox Code Playgroud)
当我打印出来时,它会说出我的数组中的两个值,例如:["Start","Treasure Room1"],我需要它打印出一个值,如:["Start"]或只是["Spider Nest1" ".我想知道如何解决这个问题.
任何帮助表示赞赏:)
您需要在第二维中生成随机索引,如下所示:
String[] currentRoomRow = rooms[rand.nextInt(rooms.length)];
String currentRoom = currentRoomRow[rand.nextInt(currentRoom.length)];
System.out.println(currentRoom);
Run Code Online (Sandbox Code Playgroud)
当所有行具有相同的大小时,这是可以的; 如果他们不这样做,上面的代码将"赞成"来自"更短"行的项目.修复此缺陷需要更多准备工作:您需要"展平"阵列,生成单个随机数量的项目,然后从展平的阵列中选择一个项目.
| 归档时间: |
|
| 查看次数: |
805 次 |
| 最近记录: |