I have an assignment that uses arrays but I can not seem to get it to print the correct results. The assignment asks to create a class which has functions that allow the user to :
1- insert a name, age, and weight for an infinite number of people, until the name "FINISHED" has been entered.
2- It should be able to display all the peoples names, ages, and weights, sorted from lightest weight to the heaviest.
3- The user should also be able to display the age and weight of a person that they searched for (if exists).
Here's what I got so far:
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);
}
}
}
}
So, The first part works (except for little bugs).
The second part does not return the values as a string. I've tried using the toString()
method and converting the objects to a string with a loop but none of them work. I need some help with displaying the objects as strings instead of "lab04.Persons@14eac69".
The third part also has some issues, but I believe they are related to the second issue since the compiler probably won't like comparing strings to objects.
I know there a lot of things that look like garbage in my code, but they are there to hold things together or otherwise I'd get errors. I wanna fix the main functions before picking the small bugs and cleaning up the code.