【发布时间】:2015-03-16 23:14:10
【问题描述】:
我有一个使用数组的作业,但我似乎无法让它打印正确的结果。该作业要求创建一个具有允许用户的功能的类:
1- 为无数人插入姓名、年龄和体重,直到输入姓名“FINISHED”。
2- 它应该能够显示所有人的姓名、年龄和体重,从最轻到最重排序。
3- 用户还应该能够显示他们搜索的人的年龄和体重(如果存在)。
这是我目前得到的:
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
ArrayList<Persons> peopleAr = new ArrayList<Persons>();
Persons ewPeople = new Persons();
ewPeople.name = "Peter";
ewPeople.age = 20;
ewPeople.weight = 70.0;
peopleAr.add(ewPeople);
for (int i = 0; i < peopleAr.size()+5; i++) {
System.out
.println("Enter the number of the action you'd like to preform:");
System.out.println("1. Add new profile.");
System.out.println("2. View all prfiles (lightest to heaviest).");
System.out.println("3. Search for a person.");
System.out.println("4. Exit.");
int key = kb.nextInt();
switch (key) {
case 1:
System.out
.println("Enter the required information. Enter 'finished' in the name field to "
+ "return to main menu. ");
Persons newPeople = new Persons();
newPeople.name = "abc";
while (!newPeople.name.equals("finished")) {
System.out.println("Enter name: ");
newPeople.name = kb.next();
System.out.println("Enter age: ");
newPeople.age = kb.nextInt();
System.out.println("Enter weight: ");
newPeople.weight = kb.nextDouble();
peopleAr.add(newPeople);
}
break;
case 2:
for (int j = 0; j < peopleAr.size(); j++) {
System.out.println(peopleAr.get(i) + " "
+ peopleAr.get(i) + " " + peopleAr.get(i + 2));
}
break;
case 3:
String nameTemp = "abc";
while (!nameTemp.equalsIgnoreCase("done")) {
System.out
.println("Enter the name you'd like to search. Enter 'done' to return to main menu. ");
nameTemp = kb.next();
boolean check = peopleAr.contains(nameTemp);
if (check = true) {
int p = peopleAr.indexOf(nameTemp);
System.out.println(peopleAr.get(p) + " "
+ peopleAr.get(p + 1) + " "
+ peopleAr.get(p + 2));
} else {
System.out
.println("There is no match for your search.");
}
}
break;
case 4:
System.exit(0);
}
}
}
}
所以,第一部分有效(除了小错误)。
第二部分不将值作为字符串返回。我尝试使用 toString() 方法并将对象转换为带有循环的字符串,但它们都不起作用。在将对象显示为字符串而不是“lab04.Persons@14eac69”时,我需要一些帮助。
第三部分也有一些问题,但我相信它们与第二个问题有关,因为编译器可能不喜欢将字符串与对象进行比较。
我知道我的代码中有很多看起来像垃圾的东西,但它们的作用是把东西放在一起,否则我会出错。我想在挑选小错误和清理代码之前修复主要功能。
【问题讨论】:
-
一定要用数组吗?
-
“声明时数组大小不是必须指定的吗?” 有也没有。是的,您必须提供数组的“a”大小,但是您可以通过多种方式来增加数组,无论是手动(您对其进行编码)还是通过可用的 API
-
详细说明您可以使用哪些集合或结构
-
好的,我明白你的意思了。 @MadProgrammer 我应该使用数组,因为我还没有学习任何数据结构。我们刚刚谈到了链接列表,但对于这个分配,数组是首选。