你好我是java的初学者,我在随机化一组字符串时遇到了问题(5)。如果你看看“可爱”循环,我可以随机化列表,但它只输出数字1 - 5而不是输出我想要的字符串。我在这里做错了什么?
基本上,我想要的是让用户键入他们想要观看的视频类型,然后让节目从他们选择5个视频的类别中随机化并从中选择一个并输出给用户
if(userString.equalsIgnoreCase("cute")){
int cutelist = rand.nextInt(5);
if (cutelist == 0) {
String cute1 = "https://www.youtube.com/watch?v=EdCVijVT7Wk";
} else if (cutelist == 1) {
String cute2 = "http://youtu.be/-XCvPptsfhI?t=7s";
} else if (cutelist == 2) {
String cute3 = "https://www.youtube.com/watch?v=-nkEPsSsH68";
} else if (cutelist == 3) {
String cute4 = "https://www.youtube.com/watch?v=FZ-bJFVJ2P0";
} else {
String cute5 = "https://www.youtube.com/watch?v=argCvDpk_KQ";
}
String cute1 = "https://www.youtube.com/watch?v=EdCVijVT7Wk";
String cute2 = "http://youtu.be/-XCvPptsfhI?t=7s";
String cute3 = "https://www.youtube.com/watch?v=-nkEPsSsH68";
String cute4= "https://www.youtube.com/watch?v=FZ-bJFVJ2P0";
String cute5 = "https://www.youtube.com/watch?v=argCvDpk_KQ";
System.out.println("Here's a funny you can watch:" + cutelist);
}
答案 0 :(得分:2)
您打印出随机数。
int cutelist = rand.nextInt(5);
...
System.out.println("Here's a funny you can watch:" + cutelist);
如果您要打印出一个字符串值(cute1
,cute2
等),则应将它们放入数组或ArrayList
并使用cutelist
变量作为索引。
你想要的东西是:
int index = rand.nextInt(5);
String[] videos = new String[5];
videos[0] = "https://www.youtube.com/watch?v=EdCVijVT7Wk";
videos[1] = "http://youtu.be/-XCvPptsfhI?t=7s";
videos[2] = "https://www.youtube.com/watch?v=-nkEPsSsH68";
videos[3] = "https://www.youtube.com/watch?v=FZ-bJFVJ2P0";
videos[4] = "https://www.youtube.com/watch?v=argCvDpk_KQ";
System.out.println("Here's a funny you can watch:" + videos[index]);
有关详细信息,请参阅Java Tutorial on Arrays。请务必注意,除了上图所示之外,还有其他方法可以初始化数组。