如何从用户输入中获取随机字符并将其存储到数组中?

ndasle7k  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(336)
public static void main(String[] args) {
    String[] array = new String[4];

    System.out.println("Type 3 Strings:");
    Scanner input = new Scanner(System.in);// User input
    for (int i = 0; i < 3; i++) // used for loop for user input
        array[i] = input.nextLine(); // Assigned users value to array

    System.out.println("Your Strings are:");
    System.out.println(array[0]);
    System.out.println(array[1]);
    System.out.println(array[2]);
}

现在我想从中找到一个随机字符集 array ,随机字符也是最大值(输入字符串长度为1)。然后将随机字符存储到另一个数组中。我下一步要做什么?。

zzwlnbp8

zzwlnbp81#

public static void main(String... args) {
    String[] array = new String[] {"125123412343","12123412343","12312341234"};
    String[] newArray = new String[3];

    Random random = new Random();

    for (int i = 0; i < 3; i++) {
        int start = Math.abs(random.nextInt() % array[i].length());
        int end = Math.abs(random.nextInt() % (array[i].length() - start));
        newArray[i] = array[i].substring(start, end == 0 ? start + 1 : start + end);
    }

    for (String str : newArray)
        System.out.println(str);
}

现在呢?

相关问题