1
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Person {
    public enum Sex {
        Male, Female
    }
    String Name;
    int Age;
    Sex Gender;
    String EmailAddress;
    public int getAge() {
        return Age;
    }
    static public Person getInstance() {
        return new Person();
    }
    public String getPerson() {
        return Name;
    }
}
public class TestPerson {
    public static void main(String...args) {
        List list = new ArrayList();
        list.add(Person.getInstance());
        list.add(Person.getInstance());
        Scanner s = new Scanner(System. in );
        for (int i = 0; i < 1; i++) {
            System.out.println(list.get(i).Name = s.nextLine());
            System.out.println(list.get(i).Age = s.nextInt());
        }
        s.close();
    }
}
Madhawa Priyashantha
  • 9,208
  • 7
  • 28
  • 58
pramod kumar
  • 225
  • 2
  • 10

2 Answers2

1

You need to use generics when declaring your list.

List<Person> = new ArrayList<Person>();

Now the compiler knows that you intend to populate this list with your Person object, and not regular Objects. Without generics, it assumes the list will be populated with Objects, which don't have Name and Age as variables, thus the compiler complains.

Eric Guan
  • 13,320
  • 7
  • 34
  • 53
1

Use Generics as Sir Eric said:

List<Person> = new ArrayList<Person>();

Also: When you are using nextLine(); method after nextInt();,

the nextLine(); will take "\n" as its input in next iteration because nextInt(); only takes the next integer token and not the Enter Button ("\n"), which is then taken by nextLine(); of next iteration in your code case.

Either use

  • Integer.parseInt(nextLine()); instead of nextInt();.

OR

  • just skip the "\n" by using nextLine(); like follows:

     public static void main(String...args) {
            List<Person> = new ArrayList<Person>();
            list.add(Person.getInstance());
            list.add(Person.getInstance());
            Scanner s = new Scanner(System. in );
            for (int i = 0; i < 1; i++) {
                System.out.println(list.get(i).Name = s.nextLine());
                System.out.println(list.get(i).Age = s.nextInt());
                s.nextLine(); //skips the "\n" 
            }
            s.close();
        }
    
rhitz
  • 1,742
  • 2
  • 17
  • 25
  • why is the problem of \n is arising in the loop,is that due to the println method? – pramod kumar Aug 09 '15 at 04:35
  • no, as I said nextInt() will only take the next integer token. And we usually input a number and then press enter ("which is actually a new line - '\n'').... now nextLine() takes all input up to new line ( excluding '\n') . Hence in the next iteration will only contain - `""` . see here for more details - http://stackoverflow.com/questions/13102045/skipping-nextline-after-using-next-nextint-or-other-nextfoo-methods . – rhitz Aug 09 '15 at 05:06