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();
}
}
最佳答案
正如Eric爵士所说:
List<Person> = new ArrayList<Person>();
另外:在
nextLine();
之后使用nextInt();
方法时,nextLine();
将在下一次迭代中将"\n"
作为其输入,因为nextInt();
仅获取下一个整数令牌,而不获取Enter Button ("\n")
,然后由nextLine();
提取下一个iteration
中的code
案件。无论使用
Integer.parseInt(nextLine());
代替nextInt();
。要么
只需使用
"\n"
跳过nextLine();
,如下所示: 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();
}
关于java - 对于以下代码,即使即时消息提供了正确的输入,我也会收到错误的InputMismatch异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31895755/