如何从Java中的数组中打印出随机字符串 [英] How to print out a random String from an array in Java

查看:114
本文介绍了如何从Java中的数组中打印出随机字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试制作我的第一场比赛已有一段时间,但遇到了困难。我想从字符串数组中提取随机字符串,然后将其打印出来,但是我的代码中有错误。我四处张望,但找不到解决方案。下面是代码:
(我已经声明了currentRoom变量)

Hi I have been trying to make my first game for a while but have run into difficulty. I want to pull a randomized String from an array of Strings and then print it out but I have errors in my code. I have looked all over but I can't find the solution. Here is the code: (I have already declared the currentRoom varible)

      int currentRoom;
String [][] rooms = {{"Start", "Treasure Room1"}, {"Goblin Home1", "Spider Nest1"}};

Random rand = new Random()
currentRoom = rooms [rand.nextInt( rooms.length)];


System.out.println(currentRoom);

我在第6行的currentRoom变量中有一个错误,我认为这使所有事情搞砸了,但是我不知道这样的错误可能在任何地方。

I have an error on my currentRoom variable in line 6 and I think that is messing everything up, but I don't know so the mistake could be anywhere.

可以提供任何帮助:)

推荐答案

必须更改的两件事:


  1. currentRoom应该是字符串数组

  2. 打印字符串数组应使用Arrays.toString

  1. currentRoom should be String Array
  2. Printing string array should be done using Arrays.toString

         String[] currentRoom;
     String [][] rooms = {{"Start", "Treasure Room1"}, {"Goblin Home1", "Spider Nest1"}};

     Random rand = new Random();

     currentRoom = rooms [rand.nextInt(rooms.length)];


     System.out.println(Arrays.toString(currentRoom));


样本输出

[Goblin Home1, Spider Nest1]

希望这会有所帮助!

这篇关于如何从Java中的数组中打印出随机字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆