2015-12-06 20 views
1

例如,如果這是我的課...Java:如何將用戶定義的屬性的值放入數組中?

public class Person { 
    private double height; //Height in inches 

    //constructors 
    public Person(double newHeight) {height = newHeight;} 
    public Person() {} 

    //Getter 
    public double getHeight() {return height;} 

    //Setter 
    public void setHeight(double newHeight) {height = newHeight;} 

    } 

,然後這是我的司機......

import javax.swing.JOptionPane; 
class Myclass { 
    public static void main{String[] args) { 

    String userInput; 
    int arraylen; 

    Person bob = new Person(); 
    double[] myarray; 

    userInput = JOptionPane.showInputDialog("How many heights do you have 
    to list?"); 
    arraylen = Integer.parseInt(userInput); 

    myarray = new double[arraylen]; 

    for(int i=0;i<myarray.length;i++) { 

    userInput = JOptionPane.showInputDialog("What is the next height?"); 
    bob.setHeight(Double.parseDouble(userInput)); 
    // I need something here to put that attribute value into the array. 
    } 
    } 
} 

所以在這一點上,我有高度屬性和我的值需要弄清楚如何將其移入數組中。我確定把用戶輸入放到一個屬性中,然後將它移動到一個數組可能不是最好的辦法,但這是爲了學校,所以這是我需要弄清楚的。請分享任何更好的方法來做到這一點的建議。但是,我主要關心如何做到這一點。

myarray[i] = bob.getHeight(); 

+0

'myarray [i] = Double.parseDouble(userInput);'?或'myarray [i] = bob.getHeight();'? – khelwood

+0

你是否有意在循環中每次設置'bob'的高度? –

+0

@khelwood我同意你的回答。但我是新來的,請原諒我的無知。你爲什麼不把它作爲答案發布? – Mike

回答

0

你似乎想要做的bob高度設置爲一個值,然後設定一個數組的bob高度入門什麼,可以通過添加一行來完成到您的for循環的末尾。

相關問題