这是我正在从事的学校项目的最小化版本。该项目的详细信息如下。 好的。所以我对 Java 还很陌生,所以我真的需要一些帮助。如何查看我的 Map> 中的值?我有编码器 block ! 我尝试过 peek,各种 System.out.println() 我不记得如何做到这一点。
正在从事学校项目。到目前为止,该项目要求要么购买、出售,要么退出。选择购买时,它会要求提供股票代码、购买数量和每股价格。然后它再次询问购买、出售或退出。当再次选择购买时,它会再次询问股票代码、数量、每股价格。并再次要求但是、出售或退出。当选择出售我购买的所有股票(第一轮输入+第二轮输入)时,它会询问股票代码,出售数量,每股价格,输入股票代码后,它会告诉你出售数量和每股价格我只有 y 股,y 是第一轮输入的数量。我无法弄清楚如何更新 map 值以等于我的所有输入数量、价格。有人可以帮助我吗?
import java.util.*;
class LinkedHashMap2{
public static Map<String, Deque<Block>> maintainStocks = new LinkedHashMap<>();
public static void main(String args[]){
var x = 0;
while (x<2) {
System.out.print("Enter the stock code: ");
var scanner = new Scanner(System.in);
var stockCode = scanner.nextLine();
System.out.print("Enter quantity to purchase: ");
scanner = new Scanner(System.in);
var quantity = scanner.nextInt();
System.out.print("Enter stock price per share: ");
var price = scanner.nextDouble();
var block = new Block(stockCode, quantity, price);
if (!maintainStocks.containsKey(stockCode)) {
maintainStocks.put(stockCode, new ArrayDeque<>());
}
maintainStocks.get(stockCode).add(block);
x++;
}
for (var stockName : maintainStocks.entrySet()) {
System.out.printf("%s", stockName.getKey());
for (var stockQuantity : stockName.getValue()){
System.out.println();
}
}
}
private static void getStockCode(String s) {
}
public static class Block {
private String stockCode;
private double price;
private int quantity;
public Block(String stockCode, int quantity, double price) {
this.setCode(stockCode);
this.setQuantity(quantity);
this.setPrice(price);
}
private void setPrice(double price) {
this.price = price;
}
private void setQuantity(int quantity) {
this.quantity = quantity;
}
private void setCode(String stockCode) {
Objects.requireNonNull(stockCode);
this.stockCode = stockCode;
}
public int getQuantity() {
return this.quantity;
}
public double getPrice() {
return this.price;
}
}
}
最佳答案
要获取特定的股票代码,只需执行以下操作。
Deque<Block> blocks = getStockCode("stockCode");
if (blocks == null) {
System.out.println("StockCode `" + s + "` does not exist.");
} else {
for (Block blk : blocks) {
System.out.println(blk);
}
}
这是你的方法
private static Deque<Block> getStockCode(String s) {
return maintainStocks.get(s);
}
在您的 Block
类中,添加 toString 函数以在打印 block 时列出信息。您可以根据需要更改它,但这是一个示例。
@Override
public String toString() {
return "[" + stockCode ", " + quantity + ", " + price +"]";
}
关于java - 无法更新我的 Map<String, Deque<Block>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61763562/