这个代码是否可以从数组中打印出随机字符串?

时间:2017-07-12 12:01:45

标签: java arrays

我(初学者)想要从数组中打印随机名称(字符串)。虽然这段代码运行得很好,但我认为这不是正确的方法。任何帮助都将受到高度赞赏。

package com.test;

public class Main {

    public static void main(String[] args) {

        //print random names from the array

        String name[] = new String[10];
        name[0] = "John";
        name[1] = "James";
        name[2] = "Ashley";
        name[3] = "Robert";
        name[4] = "Bradley";
        name[5] = "Jennifer";
        name[6] = "Stewart";
        name[7] = "Natalie";
        name[8] = "Austin";
        name[9] = "Scarlette";

        int random = (int) (Math.random() * 9);
        switch (random) {
            case 0:
                System.out.println(name[0]);
                break;
            case 1:
                System.out.println(name[1]);
                break;
            case 2:
                System.out.println(name[2]);
                break;
            case 3:
                System.out.println(name[3]);
                break;
            case 4:
                System.out.println(name[4]);
                break;
            case 5:
                System.out.println(name[5]);
                break;
            case 6:
                System.out.println(name[6]);
                break;
            case 7:
                System.out.println(name[7]);
                break;
            case 8:
                System.out.println(name[8]);
                break;
            case 9:
                System.out.println(name[9]);
                break;}
    }
}

2 个答案:

答案 0 :(得分:11)

这将是一个更好的方法。

删除开关循环
System.out.println(name[random]);

您还可以在一行代码中进行初始化和声明部分。 Refer

整个代码将成为

package com.test;
public class Main {

public static void main(String[] args) {

    String[] name = {"John","James","Ashley","Robert","Bradley","Jennifer","Stewart","Natalie","Austin","Scarlette"};
    //generating random number between 0 and name.length
    int random = (int) (Math.random() * name.length);

    //print random name from the array
    System.out.println(name[random]);

   }

}

答案 1 :(得分:0)

您可以使用Java的Random类nextInt(int) method。它以整数作为参数,并返回一个随机整数,范围从0到(但不包括)您的参数。这使得它非常适合访问数组中的随机索引。

sumColumn