-1

I am trying to solve a basic problem of finding people with over 5 years of experience. But the code is not running that way.

This is for running two user input command in the same for loop:

Scanner s = new Scanner(System.in);
int n = s.nextInt();

for (int i = 0; i <= n; i++) {
    String name = s.nextLine();
    System.out.println("enter experience");
    int e = s.nextInt();

    if (e > 5) {

    } else {

    }
}

The expected result is the number of people with over 5 years of experience but the actual is the code is asking for experience input only.

MTCoster
  • 5,307
  • 3
  • 25
  • 46
  • 2
    For start, check your loop - ```for(int i=0;i<=n;i++)```, Is this what you want? If user type 2 than loop will run 3 times – Aviza Jul 27 '19 at 15:28

4 Answers4

1

When you use nextInt() , you immediately press enter right ? What is actually happening is that nextInt() takes your integer input , you press enter , now this new line is consumed by String name = s.nextLine(); and the code immediately goes to your System.out.println("enter experience");

What you should be doing is to just simply add another s.nextLine() in the loop like

Scanner s = new Scanner(System.in);
                int n = s.nextInt();
                String name = s.nextLine();

                for (int i = 0; i <= n; i++) {
                        s.nextLine(); // put this here 
                        System.out.println("enter name");

In this way your new line key is consumed by this new statement and you can now enter your name .

0

Try this code:

Scanner s = new Scanner(System.in);
int n = Integer.parseInt(s.nextLine());

for (int i = 0; i <= n; i++) {
    String name = s.nextLine();
    System.out.println("enter experience");
    int e = Integer.parseInt(s.nextLine());

    if (e > 5) {

    } else {

    }
}
SamratV
  • 216
  • 2
  • 11
0

You need to clean the buffer somehow. This maybe helps you.

The following will solve it:

Scanner s = new Scanner(System.in);

int n = s.nextInt(); // the input       
s.next();            // clean the buffe
RobC
  • 16,905
  • 14
  • 51
  • 62
AName
  • 68
  • 4
0

What you want to do I think is to compare the years of experience after the users are registered. If that is the case then you need to store the users and their stats somewhere like in a HashMap and then filter that HashMap.