gpt4 book ai didi

java - java中使用随机数的列表

转载 作者:行者123 更新时间:2023-12-01 16:07:19 25 4
gpt4 key购买 nike

我有以下代码

public class ShufflingListAndArray
{
public static void main(String[] args) throws IOException

{
List services = new ArrayList (


Arrays.asList("COMPUTER", "DATA", "PRINTER"));

Random rnd=new Random();
String s = services.get(rnd.nextInt(services.size()));

Collections.shuffle(list);


//Collections.sort(list);


System.out.println("List sorting :"+ list);
}
}

编译上述程序时出现以下错误。

C:\>javac ShufflingListAndArray.java
ShufflingListAndArray.java:12: asList(java.lang.Object[]
nnot be applied to (java.lang.String,java.lang.String,ja
Arrays.asList("COMPUTER", "DATA", "PRINTER"));


^
ShufflingListAndArray.java:15: cannot resolve symbol
symbol : variable rnd
location: class ShufflingListAndArray
String s = services.get(rnd.nextInt(services.size()));
^
ShufflingListAndArray.java:15: incompatible types
found : java.lang.Object
required: java.lang.String
String s = services.get(rnd.nextInt(services.size()));
^
ShufflingListAndArray.java:17: cannot resolve symbol
symbol : variable list
location: class ShufflingListAndArray
Collections.shuffle(list);
^
ShufflingListAndArray.java:19: cannot resolve symbol
symbol : variable list
location: class ShufflingListAndArray
System.out.println("List sorting :"+ list);
^
5 errors

请帮我解决错误。非常感谢......

最佳答案

...
Arrays.asList("COMPUTER", "DATA", "PRINTER"));

从编译器错误中可以看出,它接受一个数组作为输入,而不是一系列字符串。您可以通过:

...
Arrays.asList(new String[] {"COMPUTER", "DATA", "PRINTER"}));

其次,您的“服务”引用不使用泛型类型,因此其内容具有编译时类型“对象”而不是“字符串”。相反,你想要:

List<String> services = new ArrayList<String>(

第三,变量的名称是“services”而不是“list”,因此:

Collections.shuffle(services);

最后的声明也是如此。在这种情况下,编译器几乎可以准确地告诉您问题是什么。你读过它的输出吗?

关于java - java中使用随机数的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2355405/

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