使用随机数在java中列出

时间:2010-03-01 11:23:50

标签: java

我有以下代码

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

请帮我解决错误。谢谢....

5 个答案:

答案 0 :(得分:1)

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

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

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

其次,您的'services'引用不使用泛型类型,因此其内容具有编译时类型Object而不是String。相反,你想要:

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

第三,你的变量的名称是'services'而不是'list',所以:

Collections.shuffle(services);

同样在最后的声明中。在这种情况下,编译器几乎可以告诉您问题的确切原因。你读过它的输出了吗?

答案 1 :(得分:0)

尝试:

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

{
    List services = 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);
  }
} 

看看你是否仍然收到你的rnd错误消息,如果你这样做,你可以发布完整的消息,似乎有部分内容被切断。

答案 2 :(得分:0)

此外,您尚未声明列表变量:Collections.shuffle(list);

答案 3 :(得分:0)

对我来说很好。在洗牌和打印时使用服务而不是列表

答案 4 :(得分:0)

这解决了所有错误:

    List<String> services = Arrays.asList("COMPUTER", "DATA", "PRINTER");
    Random rnd = new Random();
    String s = services.get(rnd.nextInt(services.size()));
    Collections.shuffle(services);
    // Collections.sort(services);
    System.out.println("List sorting :" + services);

BTW String s不在任何地方使用。