繁体   English   中英

如何在我的股票投资组合中增加头寸,当前遇到有关不兼容类型的错误,无法将其转换为int或String

[英]How to add position to my stock portfolio, currently getting an error about incompatible types cannot be converted to int or String

我在将股票添加到投资组合时遇到了麻烦。 我尝试了没有新Stock的情况,只使用stock而不是stock.tickersymbol,它仍然不起作用。 我需要更改什么以将库存和数量添加到头寸中?

我得到的错误是

错误:类型不兼容:股票无法转换为字符串

错误:不兼容的类型:库存不能转换为int头寸。add(新库存(stock.tickerSymbol),数量);

  positions.add(new Stock(stock), 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;        
}

以下是我的最低可行代码

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;

  }




}

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

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

暂无
暂无

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

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