Java练习题:员工信息数组创建及类传参代码问题排查求助
Hey there! Let's walk through the issues in your code one by one and fix them up:
1. 重复Scanner实例与输入残留问题
You created two Scanner objects (input and scan) which is unnecessary and causes input reading chaos. More critically, methods like nextInt() and nextDouble() only read numeric values and leave the trailing newline character in the input buffer. This makes subsequent nextLine() calls read empty strings directly, so you can't correctly get employee names and birth dates.
2. Invalid Employee object initialization
In Java, you must use the new keyword to call a constructor when creating an object. Your code E[i] = (name, bday, salary, overtime); is invalid syntax. The correct way is E[i] = new Employee(name, bday, salary, overtime); (assuming your Employee class has a corresponding 4-parameter constructor).
3. Redundant loop condition
i <= E.length-1 can be simplified to i < E.length—this makes the code cleaner and more readable while keeping the logic exactly the same.
Fixed Complete Code
// Only need one Scanner instance Scanner input = new Scanner(System.in); // Get the number of employees from user input System.out.println("How many employees are there: "); int numberOfEmployees = input.nextInt(); // Consume the newline left by nextInt() to avoid empty nextLine() reads input.nextLine(); // Create Employee array with the corresponding size Employee[] E = new Employee[numberOfEmployees]; // Fill the array with employee information for(int i = 0; i < E.length; i++){ System.out.println("Enter employee " + i + "'s name: "); String name = input.nextLine(); System.out.println("Enter employee " + i + "'s birth date: "); String bday = input.nextLine(); System.out.println("Enter employee " + i + "'s salary: "); double salary = input.nextDouble(); System.out.println("Enter employee " + i + "'s overtime: "); int overtime = input.nextInt(); // Consume the newline left by nextInt() for the next loop's nextLine() calls input.nextLine(); // Correctly initialize the Employee object E[i] = new Employee(name, bday, salary, overtime); } System.out.println("Employee's Information" + "\n----------------------" + "\n----------------------"); for(int i = 0; i < E.length; i++){ E[i].print(); }
Key Details Explained
- Single Scanner Instance: Use one
Scannerfor all input operations to avoid resource waste and reading conflicts. - Handle Trailing Newlines: After each
nextInt()ornextDouble()call, addinput.nextLine()to consume the newline character in the buffer, ensuring subsequentnextLine()calls can read user input correctly. - Proper Object Instantiation: Using
new Employee(...)to call the constructor is the standard way to create objects in Java.
内容的提问来源于stack exchange,提问作者Tareq El-Sayyed

