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();
}
}
Asked
Active
Viewed 48 times
1
Madhawa Priyashantha
- 9,633
- 7
- 33
- 60
pramod kumar
- 275
- 2
- 12
-
Especially in the for loop!! – pramod kumar Aug 08 '15 at 15:49
2 Answers
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
- 15,474
- 8
- 50
- 61
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 ofnextInt();.
OR
just skip the
"\n"by usingnextLine();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,892
- 2
- 21
- 26
-
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