When I use one object of class Scanner for two object of user defined class. Compiler skips some input taking line. As mentioned below.
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;
It skips line No 10 (it does not read this line variable1 = obj.nextInt();).
But when I use two different objects of Scanner class, one for book1 and second for book2, then it works fine.
Whats the problem, why happens like this?
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();
}
}
}
Expected output:
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
Actual output:
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
obj.nextLine()in between those lines?