我如何编辑程序以将变量分配给数组列表 [英] How do I edit my program in order to assign a variable to an array list

查看:78
本文介绍了我如何编辑程序以将变量分配给数组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我目前正在为一个学校项目工作.我的初始程序运行良好,然后被告知将数组重构为数组列表.

so I am currently working on a project for school. My initial program ran fine and then I was told to refactor my array into an array list.

Eclipse突出显示了一行特定的错误

Eclipse is highlighting one specific line with the error that

分配的左侧必须是变量" .

程序中的其他所有内容似乎都没有其他问题.

Everything else in the program seems to have no other issues.

我尝试了几种其他方法来解决此问题,并且碰壁了.我已经附上了导致我出现问题的代码部分的副本,希望这个问题不要太含糊.

I have tried a few different things to fix this problem and have hit a wall. I've attached a copy of the section of code causing me issue, and I hope this question isn't too vague.

import java.util.ArrayList;
import java.util.concurrent.ThreadLocalRandom;

public class StockPrices {

    static final int MAX_STOCK_COUNT = 24;
    static final int MIN_STOCK_PRICE = 10;
    static final int MAX_STOCK_PRICE = 100;

    // Create the array of Stock Objects
    ArrayList<Stock> myStocks = new ArrayList<Stock>();

    public StockPrices() {
        char startChar = 'A';
        String tmpSymbol = null;
        int startPrice = 0;
        int priceRightNow = 0;

        for (int idx = 0; idx < MAX_STOCK_COUNT; ++idx) {
            // Generate stock symbol for testing
            tmpSymbol = "" + (char) (startChar + idx) + (char) (startChar + idx + 1) + (char) (startChar + idx + 2);
            // Generate random data for pricing
            startPrice = ThreadLocalRandom.current().nextInt(MIN_STOCK_PRICE, MAX_STOCK_PRICE + 1);
            priceRightNow = ThreadLocalRandom.current().nextInt(MIN_STOCK_PRICE, MAX_STOCK_PRICE + 1);
            myStocks.get(idx) = new ArrayList <Stock>(tmpSymbol, startPrice, priceRightNow); //The issue is with this line starting with "myStocks"**
            System.out.println(myStocks.get(idx));
        }
    }
}

推荐答案

myStocks.get(idx)=新的ArrayList(tmpSymbol,startPrice,priceRightNow);

myStocks.get(idx) = new ArrayList (tmpSymbol, startPrice, priceRightNow);

此行代码从ArrayList中获取一个项目.没有设置.

This line of code is getting an item from your ArrayList. Not setting.

此外,即使它是 setting 而不是获取,您正在将ArrayList中的项目分配为另一个ArrayList ...,但您的ArrayList<>不是ArrayLists的ArrayList(跟随我)?它是一个ArrayList<股票>(股票清单).

Furthermore, even if it was setting instead of getting, you are assigning an item in your ArrayList to be another ArrayList... but your ArrayList<> is not an ArrayList of ArrayLists (follow me)? It is an ArrayList< Stock > (list of Stocks).

如果要添加新库存或更新,则需要执行以下操作:

If you want to add a new stock, or update, you need to do:

myStocks.add(new Stock(tmpSymbol, startPrice, priceRightNow); // add new

// OR

myStocks.set(idx, new Stock(tmpSymbol, startPrice, priceRightNow); // update at index

这篇关于我如何编辑程序以将变量分配给数组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆