2014-03-30 5 views
0

주식 개체가 들어있는 주식 arraylist에 데이터를 입력하려고합니다. 주식은 기호, 주식 수 및 주당 비용으로 구성됩니다. 이것은 내 코드이며 몇 시간 동안 붙어있어 입력 내용이 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

관련 문제