gpt4 book ai didi

java - 如何编辑程序以便将变量分配给数组列表

转载 作者:行者123 更新时间:2023-12-02 09:14:54 25 4
gpt4 key购买 nike

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

Eclipse 正在突出显示一个特定行,并显示以下错误:

“赋值的左侧必须是变量”

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

我尝试了几种不同的方法来解决这个问题,但都遇到了困难。我附上了导致我出现问题的代码部分的副本,我希望这个问题不会太模糊。

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) = new ArrayList (tmpSymbol, startPrice, priceRightNow);

这行代码从 ArrayList 中获取一个项目。未设置。

此外,即使它是设置而不是获取,您也会将 ArrayList 中的一个项目分配为另一个 ArrayList...但是您的 ArrayList <> 不是 ArrayList 的 ArrayList (跟我来)?它是一个 ArrayList (股票列表)。

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

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

// OR

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

关于java - 如何编辑程序以便将变量分配给数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59076789/

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