How can I break out of a loop when the user enters "done" and print the contents of what the user entered? Also, I would like to be able to find the smallest eleme
The break
statement will make the program leave the for
loop. You have no code to print the array outside of the for
loop. In fact, there is no code outside of the loop. This will make your program exit since it is in the main
method. So you need code to print the array.
Complete Solution Given all comments below:
import java.util.ArrayList;
public class Array2 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
ArrayList<Person> persons = new ArrayList();
int numOfPeople = 10;
for (int i = 0; i < numOfPeople; i++) {
System.out.print("Enter the person's name: ");
String person = input.nextLine();
if (person.trim().equalsIgnoreCase("done")) {
break;
}
System.out.print("Enter the persons's age: ");
int age = Integer.parseInt(input.nextLine());
persons.add(new Person(person, age));
}
//Collections.sort(persons); //not sorting anymore
for (Person person : persons) {
System.out.println(person.name + ": " + person.age);
}
Person youngestPerson = getYoungest(persons);
Person oldestPerson = getOldest(persons);
System.out.println("Youngest: " + youngestPerson.name + ": " + youngestPerson.age);
System.out.println("Oldest: " +oldestPerson.name + ": " + oldestPerson.age);
}
public static Person getYoungest(ArrayList<Person> people) {
Person youngestPerson = null;
for (Person person : people) {
if (youngestPerson == null || person.age < youngestPerson.age) {
youngestPerson = person;
}
}
return youngestPerson;
}
public static Person getOldest(ArrayList<Person> people) {
Person oldestPerson = null;
for (Person person : people) {
if (oldestPerson == null || person.age > oldestPerson.age) {
oldestPerson = person;
}
}
return oldestPerson;
}
protected static class Person implements Comparable<Person> {
protected String name;
protected int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(Person o) {
return (this.age > o.age ? 1 : -1);
}
}
}