当我将 Scanner 类的一个对象用于用户定义类的两个对象时。编译器会跳过一些输入行。如下所述。
1) Scanner obj = new Scanner(System.in);
2) GradeBook book1 = new GradeBook();
3) GradeBook book2 = new GradeBook();
//input for book1
4) variable1 = obj.nextInt();
5) book1.variable1 = variable1;
6) variable2 = obj.nextInt();
7) book1.variable1 = variable2;
8) variable3 = obj.nextInt();
9) book1.variable1 = variable3;
//input for book2
10) variable1 = obj.nextInt();
11) book2.variable1 = variable1;
12) variable2 = obj.nextInt();
13) book2.variable1 = variable2;
14) varibale3 = obj.nextInt();
15) book2.variable1 = variable3;
它跳过第 10 行(它不读取此行variable1 = obj.nextInt();
)。
但是当我使用 Scanner 类的两个不同对象时,一个用于 book1,第二个用于 book2,那么它工作正常。
什么问题,为什么会这样?
import java.util.Scanner;
public class GradeTest {
/**
* @param args
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try{
Employee employee1 = new Employee();
Employee employee2 = new Employee();
String fName,lName;
double salary;
System.out.print("Enter first name:");
fName = input.nextLine();
employee1.SetFName(fName);
System.out.print("\nEnter last name:");
lName = inp.nextLine();
employee1.SetLName(lName);
System.out.print("\nEnter salary:");
salary = inp.nextDouble();
employee1.SetSalary(salary);
System.out.printf("\n1:Updated Value \n FName : %s LName : %s Salary : %.2f ", employee1.GetFName(),employee1.GetLName(),employee1.GetSalary());
Systm.out.println("Enter data for second employee. \n");
System.out.print("Enter first name:");
lName = input.nextLine();
employee2.SetFName(fName);
System.out.print("\nEnter last name:");
lName = input.nextLine();
employee2.SetLName(lName);
System.out.print("\nEnter salary:");
salary = input.nextDouble();
employee2.SetSalary(salary);
System.out.printf("\n2:Initial Value \n FName : %s LName : %s Salary : %.2f ", employee2.GetFName(),employee2.GetLName(),employee2.GetSalary());
}
finally{
inp.close();
}
}
}
预期输出:
Enter first name: First Name1
Enter last name: Last Name1
Enter salary: 1500.00
Enter data for second employee.
Enter first name: First Name2
Enter last name: Last Name2
Enter salary: 1200.00
实际输出:
Enter first name: First Name1
Enter last name: Last Name1
Enter salary: 1500.00
Enter data for second employee.
Enter first name:
Enter last name: Last Name2
Enter salary: 1200.00