【问题标题】:How to make joined random between two strings如何在两个字符串之间随机连接
【发布时间】:2017-10-03 15:58:57
【问题描述】:

我有字符串数组名和字符串数组公司

public class Main {
    public static void main(String[] args) {
        String[] name = {"Alex", "John", "David", "Peter"};
        String[] company = {"Adidas", "Nike", "New Balance", "Puma"};
        Random random = new Random();
System.out.println(name[random.nextInt(name.length)] + " " + company[random.nextInt(company.length)]);

     }
}

我有

Alex Puma

没关系,但我想打印所有随机的名称和公司,例如

Alex Puma
Peter Nike
David New Balance
John Adidas

如何做到最好?

【问题讨论】:

  • 什么是团队?...
  • 对不起,语法错误
  • 将你的 printlns 放入一个循环中,并根据需要多次调用它们?
  • @DodgyCodeException 这会导致重复。例如三个“Alex”,没有一个“John”。
  • @arshajii OP 从未说过不允许重复。

标签: java arrays string random


【解决方案1】:

随机播放两个数组:

Collections.shuffle(Arrays.asList(name));
Collections.shuffle(Arrays.asList(company));

然后打印每一对:

for (int i = 0; i < name.length; i++)
    System.out.println(name[i] + " " + company[i]);

【讨论】:

  • 如果名称多于公司怎么办?你会得到 ArrayIndexOutOfBoundsException。
  • @DodgyCodeException 重点是展示一般做法。 OP可以像这样整理低级细节。 :-)
  • 嗨@arshajii。我还有一个问题,如果你不介意的话。例如,我有 String[] name = {"Alex", "John", "David", "Peter"};如何成对分组?还是一组一个名字,第二组三个?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-12
  • 2014-01-30
  • 2021-09-01
  • 1970-01-01
  • 2011-11-04
相关资源
最近更新 更多