gpt4 book ai didi

java - 尝试随机化 Arraylist 中的数字索引

转载 作者:行者123 更新时间:2023-12-02 12:05:40 25 4
gpt4 key购买 nike

我当前正在尝试运行一个程序,让用户输入一个数字并让程序选择该单词。但是我似乎无法让程序正常运行。我可以在不更改索引的情况下运行程序。我在这里缺少什么吗?我已经导入了 Random 函数,但无法弄清楚最后一部分。所有这些都是在 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)

其中 r 是

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

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

关于java - 尝试随机化 Arraylist 中的数字索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46923366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com