gpt4 book ai didi

java - 如何向我的股票投资组合添加头寸,目前收到有关不兼容类型无法转换为 int 或 String 的错误

转载 作者:行者123 更新时间:2023-12-02 11:35:09 26 4
gpt4 key购买 nike

我在将股票添加到投资组合时遇到问题。我尝试过不使用 new Stock,只使用 stock 而不是 stock.tickersymbol,但它仍然不起作用。我需要更改什么才能将库存和数量添加到仓位?

我收到的错误是

错误:不兼容的类型:库存无法转换为字符串

错误:不兼容的类型:Stock 无法转换为 int Positions.add(new Stock(stock.tickerSymbol), 数量);

  positions.add(new Stock(stock), quantity);

我正在努力让这条线正常工作。

positions.add(new Stock(stock.tickerSymbol), 数量);

public boolean buy(Stock stock, int quantity, double price) {
double total = price * quantity;

if (cash >= total) {
cash -= total;
positions.add(new Stock(stock.tickerSymbol), quantity);
return true;
}

return false;
}

以下是我的最小可行代码

import java.io.*;
import java.util.*;
import java.util.stream.*;
import org.junit.*;
import org.junit.runner.*;
import static org.junit.Assert.*;

class Stock {

public String tickerSymbol;

public Stock(String tickerSymbol) {
this.tickerSymbol = tickerSymbol;
}

}

class Position {

public Stock stock;
public int quantity;

public Position(Stock stock, int quantity) {
this.stock = stock;
this.quantity = quantity;
}

}

class Portfolio {



public double cash;
public List<Position> positions;


public Portfolio(double cash, List<Position> positions) {
this.cash = cash;
this.positions = new ArrayList<>(positions);
}

/*
If the buy is viable (sufficient cash), executes it and returns true,
else returns false
*/
public boolean buy(Stock stock, int quantity, double price) {



double total = price * quantity;

if (cash >= total)
{
cash -=total;
positions.add(new Stock(stock.tickerSymbol), quantity);
return true;

}
return false;

}




}

最佳答案

如果 buy 方法要访问 Position 变量,则该方法必须是 Portfolio 类的一部分(我将继续假设它是...)。然后,您需要定义一个新的 Position 来添加到头寸列表中,因为这是对象 Position 的列表,而不是 Stock:

positions.add(new Position(stock, quantity));

关于java - 如何向我的股票投资组合添加头寸,目前收到有关不兼容类型无法转换为 int 或 String 的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49000104/

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