2014-03-30 86 views
0

我想輸入數據到包含股票對象的股票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] 

回答

2

你的字段賦值是從右到左

sym = this.sym; 

應該

this.sym = sym; 

同爲其他Stock字段

+1

哇哈哈哈。非常感謝你,我會檢查標記,當我可以 – user2921899

相關問題