0

I'm using a for loop to ask a user for a name and a salary. This is all the code I have for it so far so you can get the full context:

import java.util.List;
import java.util.Scanner;
import java.util.ArrayList;

import static java.util.Collections.max;

public class EmployeeReport {

    public static void main(String args[]){

        Scanner sc = new Scanner(System.in);


        //Ask for given number of employees
        System.out.print("Enter number of employees: ");
        int number = sc.nextInt();

        Employee[ ] employeeCollection = new Employee[number];
        Employee worker = new Employee();


        List<Double> salaries = new ArrayList<>();
        for (int i = 0; i < number; i++){

            System.out.println("Enter data for employee # " + (i + 1));

            System.out.print("Enter name of employee: ");
            String name = sc.nextLine();


            System.out.print("Enter employee's salary: ");
            String sal = sc.nextLine();
            double salary = Double.parseDouble(sal);


            worker.setName(name);
            worker.setSalary(salary);

            salaries.add(salary);
            employeeCollection[i] = new Employee(name, salary);
        }
    }
}

This is just a sample output:

Enter number of employees: 3  
Enter data for employee # 1                      
Enter name of employee: Enter employee's salary: 12000
Enter data for employee # 2
Enter name of employee: Iron Man
Enter employee's salary: 140000
Enter data for employee # 3
Enter name of employee: Peter Parker
Enter employee's salary: 5000

For some reason, the output always prints out the Enter name of employee line on the first loop but doesn't ask for a input and just asks for the salary instead. I've tried using sc.next() but I need to have the first and last name.

smoothlee
  • 1
  • 1
  • Using `Scanner sc = new Scanner(System.in);` I am unable to reproduce any issue with the code in your question. Are you sure that this is exactly the code that is skipping a line? Can you show us some sample input – sorifiend Mar 10 '22 at 22:36
  • 1
    You're likely using some other `next...()` call prior to this loop. Be sure to add `nextLine()` after it just like you do after the `sc.nextDouble()` in the loop. – Ivar Mar 10 '22 at 22:38
  • you could also just use nextLine() and then convert the value to a double for the salary – RAZ_Muh_Taz Mar 10 '22 at 22:42

0 Answers0