0

When I was putting this code for input three name and mark. but the name doesn't looping 3 time just once I could input, directly the code jumped to input mark1. how can I check to input three name please!

public void in_array(String x[], float x2[], float x3[])
{
    for(i=0; i<x.length;i++)
    {
        System.out.println("Enter name: ");
        x[i] = in.nextLine();
        System.out.println("Enter  Mark one:  ");
        x2[i] = in.nextFloat();
        System.out.println("Enter  Mark two:  ");
        x3[i] = in.nextFloat();
    }
}

Output:

enter name:
Enter mark one:

1 Answers1

0

The problem is that the nextFloat() method does not consume the newline character. You'll either have to consume that character manually after, or read a full line and parse your float manually.

A quick fix using solution #1 could look like this:

for(i=0; i<x.length;i++)
{
    System.out.println("Enter name: ");
    x[i] = in.nextLine();
    System.out.println("Enter  Mark one:  ");
    x2[i] = in.nextFloat();
    in.nextLine();   // consume newline character
    System.out.println("Enter  Mark two:  ");
    x3[i] = in.nextFloat();
    in.nextLine();   // consume newline character
}

Solution #2 would look like this:

for(i=0; i<x.length;i++)
{
    System.out.println("Enter name: ");
    x[i] = in.nextLine();
    System.out.println("Enter  Mark one:  ");
    x2[i] = Float.parseFloat(in.nextLine());
    System.out.println("Enter  Mark two:  ");
    x3[i] = Float.parseFloat(in.nextLine());
}
bgse
  • 8,237
  • 2
  • 37
  • 39