[英]How to add position to my stock portfolio, currently getting an error about incompatible types cannot be converted to int or String
I'm having trouble adding the stock to the portfolio. 我在将股票添加到投资组合时遇到了麻烦。 I have tried without new Stock, with just stock instead of stock.tickersymbol and it still doesn't work.
我尝试了没有新Stock的情况,只使用stock而不是stock.tickersymbol,它仍然不起作用。 What would I need to change to add the stock and quantity to the positions?
我需要更改什么以将库存和数量添加到头寸中?
The error I am getting is 我得到的错误是
error: incompatible types: Stock cannot be converted to String 错误:类型不兼容:股票无法转换为字符串
error: incompatible types: Stock cannot be converted to int positions.add(new Stock(stock.tickerSymbol), quantity); 错误:不兼容的类型:库存不能转换为int头寸。add(新库存(stock.tickerSymbol),数量);
positions.add(new Stock(stock), quantity);
I am trying to get this line working. 我正在努力使这条线工作。
positions.add(new Stock(stock.tickerSymbol), quantity); position.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;
}
The following is my minimum viable code 以下是我的最低可行代码
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;
}
}
The buy method needs to be part of the Portfolio class if it is going to access the positions variable (I'm going to go ahead and assume it is...). 如果要访问position变量,则buy方法必须是Portfolio类的一部分(我将继续并假设它是...)。 Then you need to define a new Position to add to the positions list, as that is a List of the object Position, not Stock:
然后,您需要定义一个新的头寸以添加到头寸列表中,因为这是对象头寸的列表,而不是库存:
positions.add(new Position(stock, quantity));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.