0

I have problem with Scanner When I run the program it skips this one after

System.out.println("name");
n1=s.nextLine();

This is the program "CEmploye " is a class

package Ex5_2;
import java.util.*;

public class XXXX {
    public static void main(String[] args) {

        int input;
        int c1 ;
        String n1;
        Date d1 = null;
        float p1;
        float [] t = new float[3];

        System.out.println("give nb of emp");

        Scanner s = new Scanner(System.in);

        input=s.nextInt();
        Vector v = new Vector(input);

        for(int i=0 ;i <input;i++)
        {   
            System.out.println("cin");
            c1=s.nextInt();

            System.out.println("name");
            n1=s.nextLine();

            System.out.println("price");
            p1=s.nextFloat();

            for(int k=0 ; k<3;k++)
            {
                System.out.println("nb of hour");

                CEmploye.tab[k]=s.nextFloat();
            }

            CEmploye emp = new CEmploye(c1,n1,d1,p1);
            emp.CalculSalaire();

            System.out.println(emp.salaire);
        }       
    }
}

Can anyone give me solution ?

Walery Strauch
  • 6,792
  • 8
  • 50
  • 57
Malek Djelassi
  • 85
  • 1
  • 10

4 Answers4

0

You can't use n1=s.nextLine(); with n1=s.nextInt(). Use n1=s.next();

Masudul
  • 21,823
  • 5
  • 43
  • 58
0

System.in's buffer isn't flushed until it gets a newline. So you can't use nextInt() or nextFloat() because they block until a newline.

You'll need to read everything on a line by itself then parse it (with some validation as needed):

cl = Integer.parseInt(s.nextLine());

and

pl = Float.parseFloat(s.nextLine());

and

CEmploye.tab[k]=Float.parseFloat(s.nextLine());
Jon Lin
  • 142,182
  • 29
  • 220
  • 220
0

nextInt() only reads the next integer available and leaves a newline character in the inputstream. Your s.nextLine() then gets consumed thus not prompting for additional inputs.

Simply add another nextLine() to read more lines

Jack Jiang
  • 522
  • 3
  • 11
0
     c1=s.nextInt();

This just reads the integer value not the end of line. So when you do

      n1=s.nextLine();

it just reads the end of line that you provided by pressing the enter while providing the integer input for the previous variable (c1) and thus seems like it skipped the input. (If you put an integer and some string in the same line when taking c1 input, you will get values for c1 and n1 both. You can check the same)
In order to fix it, either put nextLine() input after each nextInt(). Hope it helps.

shallOvercome
  • 386
  • 2
  • 10