如何检查一个数组的随机片段是否等于特定的数组部分?

问题描述 投票:1回答:1

我试图让我的String数组从它得到一个随机的String,如果它是某个String然后它需要在我的文本区域打印结果。

String[] items = new String[]{"nothing useful", "trash", "a fork"};

说阵:

Random rand = new Random();
String outcome = items[rand.nextInt(items.length)];

从数组中获取随机String作为String命名结果:

if(outcome.equals(items[2])){
  textArea2.append("a fork" + "\n");
}

我尝试将"a fork"放入文本区域。我的所有文本区域都有效,所以这不是我的问题。

我试过使用.equals==if(outcome=="a fork")以及各种类似的东西而没有任何工作。

我需要它将"a fork"添加到名为textArea2的文本区域。

java arrays random
1个回答
0
投票

你确定你的if(outcome.equals(items[2]))到达了吗?也许你的代码触发器有问题。只需在其前面放一些印刷品,以确保它真正执行:

System.out.println("if gets reached");
if(outcome.equals(items[2])){
    textArea2.append("a fork" + "\n");
}

据我所知,==.equals()甚至if(outcome == "a fork")应该在这种情况下工作。

© www.soinside.com 2019 - 2024. All rights reserved.