【问题标题】:Java "int cannot be dereferenced" ArraylistJava“int不能被取消引用”Arraylist
【发布时间】:2018-03-26 13:32:35
【问题描述】:

所以我有一个方法应该创建一个数组列表来保存骰子的随机滚动值。创建卷之后,它会将它们添加到循环中的数组列表的元素中。添加它们的行给了我错误“无法引用int”

然后,当我尝试在另一个循环中获取这些滚动的总和时,我得到了同样的错误。代码如下。我对java很陌生,我认为问题出在数据类型上,arraylist就是它,而dice、faces和sum是静态整数。谢谢! 我从我的开头包含了变量声明 上课以防万一。

 public class dice {
    static int dice, faces, max, min, mid, x,rolls,sum;

 public static void rollValues( int dice ) {

    //arraylist holding roll values
    ArrayList<Integer> rolls = new ArrayList<Integer>(dice);
    } 


    public static void rollRandomizer(int dice, int faces, int sum){
    //randomizing roll values 
    Random  r = new Random(); 
    for(x = 0; x < dice; x++){ 
        int roll = r.nextInt(faces)+1;
        rolls.add(x, roll); **<<<error here**
        } 


    System.out.println( "The roll values are: " + rolls);

    //summing roll values aka all the numbers in the rolls arraylist
    for(x=0; x <dice; x++){
           sum += rolls.get(x); **<<<error here**
    }

     System.out.println("The sum of the rolls is: " + sum);

    }

【问题讨论】:

  • 您的ArrayList 仅在您的static rollValues 方法中可见,在该方法之外您有一个具有该名称的static int 字段。
  • 顺便说一句,拥有 8 个可变静态字段是相当可疑的。

标签: java arraylist methods dereference


【解决方案1】:

ArrayList<Integer> rolls = new ArrayList<Integer>(dice); // this is method variable, it's available only inside rollValues()

还有这个: rolls.add(x, roll); 电话进来 static int dice, faces, max, min, mid, x,rolls,sum;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-08
    • 2013-10-07
    • 1970-01-01
    • 2015-05-21
    • 2023-03-31
    相关资源
    最近更新 更多