例如,如果这是我的课...
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.
}
}
}
所以此时我的 height 属性中有一个值,我需要弄清楚如何将其移动到数组中。我确信将用户输入放入属性中然后将其移动到数组可能不是最好的方法,但这是为了学校,所以这就是我需要弄清楚的。请分享任何更好的方法的建议。不过,我主要关心的是如何做到这一点。
最佳答案
您似乎想要做什么,将 bob
的高度设置为一个值,然后将数组中的条目设置为 bob
的高度,可以通过添加以下行来完成:
myarray[i] = bob.getHeight();
到 for
循环的末尾。
关于Java:如何将用户定义的属性的值放入数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34123796/