我正在尝试将数据输入到包含股票对象的Stocks arraylist中。股票由符号,股票数量和每股成本组成。这是我的代码,我已经被困了几个小时,无法弄清楚为什么我的输入不会进入arraylist。这是我的代码:
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]
答案 0 :(得分:2)
您的字段分配是从右到左
sym = this.sym;
应该是
this.sym = sym;
其他Stock
字段