我正在尝试学习一些基本的方法来操纵编码的某些方面,这些方面偏离了单一用途,并使更多的东西变得更有活力"这可以在飞行中构建自己。
例如我想要完成的事情,我认为这将包括使用某种类型的对象和循环的空数组。我只是不知道如何写它。
让我们保持基本,并说我有Person Class
。
public class Person
{
String name;
String age;
}
因此,在我的TestDrive
中,我只会获得一个简单的用户输入来收集有关该人的信息。
比如......
import javax.swing.JOptionPane;
public class PersonTestDrive
{
public static void main(String[] args)
{
String name;
String age;
name = JOptionPane.showInputDialog(null, "Enter your name");
age = JOptionPane.showInputDialog(null, "Enter your age");
Person human = new Person();
human.name = name;
human.age = age;
JOptionPane.showInputDialog(null, "Would you like add another entry?");
/* At this point it would loop if the user wanted to add another entry.
I would just wrap it all in while loop that just checked if the user said yes or no.
However, if they do choose to add another entry
"IF" a human object already existed it would create a
new human2 object, and then human3, etc. */
}
}
答案 0 :(得分:1)
听起来你只需要一组对象,例如ArrayList<Person>
。
&#34;人类&#34;是变量的名称,在编译时你不知道有多少其他变量,所以你不能在代码中使用&#34; human2&#34;,&#34; human3&#来引用它们34;等等。您可以创建这些变量,但它们可能为空,您的输入也将限制为您拥有的变量数。另一个问题是跟踪要分配给下一个的变量。
使用List<Person> list
,您可以list.get(2)
获取第三个对象(如果少于3个,则会抛出异常)或list.size()
来检查到目前为止创建了多少个对象。
以下是有关Java集合的更多信息:http://docs.oracle.com/javase/tutorial/collections/