Java:如何将用户定义属性的值放入数组?
例如,如果这是我的班级Java:如何将用户定义属性的值放入数组?,java,arrays,class,Java,Arrays,Class,例如,如果这是我的班级 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 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.
}
}
}
import javax.swing.JOptionPane;
类Myclass{
公共静态void main{String[]args){
字符串用户输入;
内特阿莱伦;
Person bob=新的Person();
双[]myarray;
userInput=JOptionPane.showInputDialog(“您有多少高度
列入?);
arraylen=Integer.parseInt(userInput);
myarray=新的双精度[arraylen];
对于(int i=0;i您似乎想要做的事情,将bob
的高度设置为一个值,然后将数组中的条目设置为bob
的高度,可以通过添加以下行来完成:
myarray[i] = bob.getHeight();
将bob
的高度设置为一个值,然后将数组中的条目设置为bob
的高度,可以通过添加以下行来完成您想要做的事情:
myarray[i] = bob.getHeight();
到for
循环的末尾。myarray[i]=Double.parseDouble(userInput);
?或myarray[i]=bob.getHeight()
?你是不是每次在循环中都故意设置了鲍勃的身高?@khelwood我同意你的答案。但是我是新来的,所以请原谅我的无知。你为什么不把它作为一个答案发布?@aguibert是的,我是故意设置身高的。@khelwood谢谢,第二个嫁给了[I]=bob.getHeight();成功了!我一直在想这个问题,但我想确定一下。myarray[I]=Double.parseDouble(userInput);?或者myarray[I]=bob.getHeight()
?你是不是每次在循环中都故意设置了鲍勃的身高?@khelwood我同意你的答案。但是我是新来的,所以请原谅我的无知。你为什么不把它作为一个答案发布?@aguibert是的,我是故意设置身高的。@khelwood谢谢,第二个嫁给了[I]=bob.getHeight();成功了!我一直在想这方面的事情,但我想确定一下。