I need to write a program that will prompts user to input 5 persons' name and age one by one and store them into an array of Person class.
The problem of the code below is that, the program will not prompts the user to key in the name for 2nd - 5th persons after successfully insert name and age for 1st person.
I found a solution is that instead of using scanner.nextLine(), using a scanner.next() will solve the problem. But instead of reading person name of 1 word, I want to read the name with spaces in between as well.
Sorry for bad english.
Any help?
import java.util.Scanner; class PersonList { public static void main (String[] args) { Person [] list = new Person [5]; Scanner scanner = new Scanner(System.in); for (int i=0; i<list.length; i++) { System.out.print("Enter name: "); String name = scanner.nextLine(); System.out.print("Enter age: "); int age = scanner.nextInt(); Person p = new Person(name,age); add(list, i, p); } display(list); } public static void add(Person [] persons, int i, Person p) { persons[i] = p; } public static void display(Person [] persons) { for(int i=0; i<persons.length ; i++) { System.out.println(persons[i].getName()+ " " + persons[i].getAge() ); } } }