繁体   English   中英

List.add()预期的类

[英]List.add() Class Expected

我在大学上Java课程。 我的老师实际上是一位从C派生的语言的老师,所以她不知道这段代码是怎么回事。 我在此页面上阅读了http://docs.oracle.com/javase/6/docs/api/java/util/List.html ,可以将语法“ list []。add(int index,element)”用于在特定的索引中添加特定的对象或计算,从而减少了所需的编码量。 我要创建的程序是用于D&D的随机统计生成器,以供练习。 给出错误的方法如下:

// StatGenrator与ActionListener一起使用

private String StatGenerator ()
{
        int finalStat;
        String returnStat;

        //Creates an empty list.
        int[] nums={};

        //Adds a random number from 1-6 to each list element.
        for (int i; i > 4; i++)
            nums[].add(i, dice.random(6)+1); //Marks 'add' with "error: class expected"

        //Sorts the list by decending order, then drops the
        //lowest number by adding the three highest numbers 
        //in the list.            
        Arrays.sort(nums);
        finalStat = nums[1] + nums[2] + nums[3]; 

        //Converts the integer into a string to set into a 
        //texbox.
        returnStat = finalStat.toString();
        return returnStat;
}

我的最终目标是使用某种排序列表或删除集合中最低值的方法。 该方法的重点是从1-6生成4个随机数,然后删除最低的数字并将三个最高的数字相加。 最终的数字将是文本框的文本,因此它将转换为字符串并返回。 其余代码可以正常工作,但我在使用此方法时遇到了麻烦。

如果有人有什么主意,我会很高兴。 我研究了一下,发现了一些有关使用ArrayList制作新的List对象的信息,但是我不确定它的语法。 最后一点,我尝试在另一个问题中寻找该语法,但在stackoverflow上的任何地方都找不到它。 如果我错过了某处的地方,我深表歉意。

'int nums []'不是列表,而是一个数组。

List<Integer> intList = new ArrayList<>();

例如,创建一个新的ArrayList。

您可以使用以下语法直接访问列表中的Elements:

intList.get(0); // Get the first Element

您可以使用Collections类对列表进行排序:

Collections.sort(intList);

以下是有关Java中集合的一些信息: http : //docs.oracle.com/javase/tutorial/collections/

数组是固定大小的,因此您需要在开始时为所有插槽分配空间。 然后将数字放入数组中,分配给nums[i] 不需要add()方法。

int[] nums = new int[4];

for (int i = 0; i < 4; i++)
    nums[i] = dice.random(6) + 1;

Arrays.sort(nums);
finalStat = nums[1] + nums[2] + nums[3]; 

另外,如果您确实需要动态大小的数组,请使用ArrayList。 ArrayList可以增长和收缩。

List<Integer> nums = new ArrayList<Integer>();

for (int i = 0; i < 4; i++)
    nums.add(dice.random(6) + 1);

Collections.sort(nums);
finalStat = nums.get(1) + nums.get(2) + nums.get(3); 

请注意,由于ArrayList是类而不是内置类型,因此语法有何不同。

nums []。add(i,dice.random(6)+1); //将“添加”标记为“错误:预期类别”

您正在尝试在数组上使用add List是一个动态数组,但这并不意味着array == List 您应该改用List。

 List<Integer> nums=new ArrayList<Integer>();

//Adds a random number from 1-6 to each list element.
for (int i; i > 4; i++)
    nums.add(i, dice.random(6)+1); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM