一个关于容器的问题,求帮助
package com.TextStatic;
import java.util.*;
class Employee{
Employee(String name, int age){
this.name = name;
this.age = age;
this.ID = nextID;
nextID ++;
}
public static int getNextID() {
return nextID;
}
public String toString(){
return "Name " + name + " Age " + age + " ID " + ID;
}
private String name;
private int age;
private int ID;
private static int nextID = 1;
}
public class TextStatic {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
Collection<Employee> person = new ArrayList<Employee>();
step:
for(int i=0; i<3; i++){
//在这个循环里,我想往容器person内添加三个对象,可是每次添加到第二个对象的name后,再输入age回车就会抛出异常InputMismatchException,捕获之后就只能添加一个对象
System.out.println("Please enter name and age:");
try{
person.add(new Employee(in.nextLine(), in.nextInt()));
}catch(InputMismatchException e){
System.out.println("The input is wrong!");
break step;
}
}
for(Iterator<Employee> i = person.iterator(); i.hasNext();){
System.out.println(i.next());
}
int n = Employee.getNextID();
System.out.println("The nextID is " + n);
}
}
这个程序我调试了很长时间了,可是一直没有找到解决的问题所在,希望大神给予帮助,具体问题我已经在程序中注释起来了,谢谢
------解决方案--------------------上一行 nextInt()运行完后,还有回车换行遗留。
用in.nextLine() 把它清除了。