gpt4 book ai didi

java - 输入数组列表时遇到问题,尝试了一切

转载 作者:行者123 更新时间:2023-12-02 06:00:04 25 4
gpt4 key购买 nike

我正在尝试将数据输入到包含股票对象的股票数组列表中。股票由代码、股票数量和每股成本组成。这是我的代码,我已经被困了几个小时,无法弄清楚为什么我的输入没有进入数组列表。这是我的代码:

import java.util.*;
import java.util.Scanner;

public class stock {

String sym;
int amt;
double cost;

public stock(String sym, int amt, double cost){
sym = this.sym;
amt = this.amt;
cost = this.cost;
}

public String getSym() {
return sym;
}


public int getAmt() {
return amt;
}


public double getCost() {
return cost;
}

@Override
public String toString() {
return ("sym: "+this.getSym()+
" amt : "+ this.getAmt() +
" cost: "+ this.getCost());
}


public static void main(String[] args) {

int choice = 0;
ArrayList<stock> Stocks = new ArrayList<stock>();

while (choice == 0){
System.out.println("Enter 1 to input a new stock, or 2 to query a stock's price, 3 to quit: ");
Scanner sc1 = new Scanner (System.in);
choice = sc1.nextInt();
}

if(choice==1){
Scanner sc2 = new Scanner (System.in);
System.out.println("Please enter the stock symbol: ");
String sym = sc2.next();
System.out.println("Please enter the number of shares: ");
int amt = sc2.nextInt();
System.out.println("Please enter the price per share: ");
double cost = sc2.nextDouble();

stock list = new stock(sym, amt, cost);

Stocks.add(list);

System.out.println(Stocks.toString());

}
}
}

这是我的输出:

[sym: null amt : 0 cost: 0.0]

最佳答案

您的字段分配是从右到左

sym = this.sym;

应该是

this.sym = sym;

其他Stock字段也是如此

关于java - 输入数组列表时遇到问题,尝试了一切,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22751354/

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