尝试随机化我的数组列表中的数字索引



我当前正在尝试运行一个程序,该程序让用户输入一个数字并让程序选择单词。但是,我似乎无法使程序正常运行。我能够在不更改索引的情况下运行程序。我在这里缺少什么吗?我已经导入了随机函数,但在弄清楚最后一部分时遇到了麻烦。所有这些都是在 NetBeans 中完成的。

package arraywords;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Random;
public class Arraywords {
    public static void main(String[] args) {
        ArrayList<String>words = new ArrayList();
        words.add("Token");
        words.add("Magic");
        words.add("People");
        words.add("Racecar");
        words.add("Xbox");
        words.add("Puppy");
        words.add("Destiny");
        words.add("Knowledge");
        words.add("Home");
        words.add("Professional");
        System.out.print("Choose a random number between 1 and 10 "
        + "to recieve a random word:n");
        int choice = 0;
        Scanner scanner = new Scanner(System.in);//Scanner program
        while (choice < 1 || choice > 10) {//The parametors for the users
            System.out.println("Input a number:");
            String message = scanner.next();//Prompt for user to input a number
            try{
                choice = Integer.parseInt(message);
            } 
            catch(NumberFormatException e){
                System.out.print("Please use numbers");
            } /* The while loop watches the users input and is waiting for the user to input a number. Once they select a number. The word should be displayed. */
        }
        Integer index = choice -1; /* Since arrays begin with zero I had to account for that by adding the -1.  */
        System.out.printf("You entered #%d:n> %s.", choice, words.get(index)); //Once the user has chosen a number the word will be displayed
    } 
}

你正在导入随机类,但你没有在你发布的代码中使用它......

你可以让一个随机元素做

words.get(r)

哪里是

Random rnd = new Random();
int r = rnd.nextInt(words.size());

还有其他方法可以做到这一点(昂贵的方法),例如洗牌列表并在该操作后获取第一个元素。

您可以尝试在 Java 1.7+ 中使用随机函数

package arraywords;
import java.util.ArrayList;
import java.util.concurrent.ThreadLocalRandom;

public class Arraywords {
    public static void main(String[] args) {
        ArrayList<String>words = new ArrayList();
        words.add("Token");
        words.add("Magic");
        words.add("People");
        words.add("Racecar");
        words.add("Xbox");
        words.add("Puppy");
        words.add("Destiny");
        words.add("Knowledge");
        words.add("Home");
        words.add("Professional");
        int index = ThreadLocalRandom.current().nextInt(0, words.size());
        System.out.printf("Random Word Index:#%d:n> %s.", (index+1), words.get(index));
    } 
}

参考:如何在 Java 中生成特定范围内的随机整数?

最新更新