user1762169
user1762169

Reputation: 29

input, arrays and NextLine

I'm sorry if a similar question has been posted, I just couldn't find it. Here is my code:

import java.util.*;

public class InputArraysNextLine
{
    static Scanner q = new Scanner(System.in);

    public static void main(String[] args)
    {
        System.out.print("n = ");
        int n = q.nextInt();

        int[] a = new int[n];
        String[] b = new String[n];

        for (int i = 0; i < n; i++)
        {
            System.out.print("Enter student name: ");
            b[i] = q.nextLine();

            q.next();
            System.out.print("Enter student number: ");

            a[i] = q.nextInt();
        }


        for (int i : a)
            System.out.print(i + " ");
        System.out.println();
        for (String j : b)
            System.out.print(j + " ");
    }
}

I intended to display on the console both arrays a and b, but only a is shown. I believe the nextLine() method has something to do with this; even though I can actually input something when the console displays "Enter student name:", the program doesn't store the input into the b Strings.

Upvotes: 1

Views: 9284

Answers (3)

Iskar Jarak
Iskar Jarak

Reputation: 5325

Scanner.nextInt() does not consume the newline, so you need to call nextLine() after grabbing the int to skip over it. You also don't need to call next() after calling nextLine().

for (int i = 0; i < n; i++)
{
    System.out.print("Enter student name: ");
    b[i] = q.nextLine().trim(); // b is the whole line, trim() removes leading and trailing whitespace

    System.out.print("Enter student number: ");
    a[i] = q.nextInt();
    q.nextLine(); // nextInt() does not 
}

You should also be aware that just running a loop that expects to be able to grab a number of things is also a bit dodgy - you really should check for things before you try to grab them to avoid crashing (e.g. if the input stream terminates early). Checking can be done using the has functions - hasNext() for tokens, hasNextLine() for lines, hasNextInt() for integers, and so on.

Upvotes: 1

CodeDreamer
CodeDreamer

Reputation: 444

q.nextLine javadoc states "Advances this scanner past the current line and returns the input that was skipped." Your functionality to get the input that user enters.

So you need to reverse what is captured in b[i]

b[i] = q.nextLine(); q.next()

to

b[i] = q.next(); q.nextLine();

Upvotes: 0

dan
dan

Reputation: 13272

You should try and replace:

b[i] = q.nextLine();
q.next();

with:

b[i] = q.next();

Since q.nextLine() returns the input that was skipped in the stream, not the case here.

Upvotes: 0

Related Questions