-1

Im currently in the process of creating a program and stores data and I'm running into an issue where its printing out a statement twice and counting it as two in an array(its hard to explain so ill show it)

So this is the code

public static void GetData()
   {
     Scanner input = new Scanner(System.in);
     System.out.println("How many names do you want to enter?");
                int num = input.nextInt();
                int array[] = new int[num];
                for (int i = 0  ; i < array.length ; i++ ) 
                    {
                        String[] names = new String[num];


                        System.out.println("enter employee's name: ");

                        names[i] = input.nextLine();   
                    }
                for(int j = 0; j < array.length;j++)
                    {
                    double[] payrate = new double[num];
                    System.out.println("enter employee's payrate: ");

                     payrate[j] = input.nextDouble();
                     }

   }

}

the problems is its printing out :

How many names do you want to enter?
4
enter employee's name: 
enter employee's name: 
harry
enter employee's name: 
larry
enter employee's name: 
mary
enter employee's payrate: 

twice right away so when the user declares let says the array size of 4 it'll print that twice and it'll count that as two spots already so now it only counts 3 of the data and switches to the next array, I'm honestly not sure whats causing this, I tried to debug it but it tells me nothing, any help would be loved!

forgivenson
  • 4,234
  • 2
  • 16
  • 28
kyle
  • 5
  • 1

1 Answers1

0

The first names[i] = input.nextLine(); will read the \n from the line containing the number which you read with input.nextInt(), so you'll get an empty name there.

You could read the num as follows:

String strNum = input.nextLine();
int num = Integer.parseInt(strNum);
Martin C.
  • 10,762
  • 6
  • 38
  • 52