-2

I'm new in java programming and was learning input via scanner class. My program accepts a string array of capacity 5, and displays it back to the user.

However, the array is only accepting 4, and I can't figure out why. Any help would be appreciated.

My code

Accepting string array

    String n[] = new String[5];

    for (int i = 0 ; i<5 ; i++)
    {
        n[i] = sc.nextLine();
    }

Displaying the string array

    for(int i=0 ; i<5 ; i++)
    {
        System.out.println(n[i]);
    }

The 5th string is being accepted and printed as blank for some reason, as in instead of 5 only 4 strings are being accepted and printed.

Mark Rotteveel
  • 82,132
  • 136
  • 114
  • 158
  • 2
    I created a test script which includes your code and it works for me. What is your input and what is the corresponding output? – Adder Jan 09 '20 at 15:59
  • 2
    Works for me. Can you copy/paste your whole `main()` method? – Matthieu Jan 09 '20 at 16:00
  • 2
    Something tells me that this is yet another case of [skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/q/13102045) – Pshemo Jan 09 '20 at 16:24
  • @ Pshemo yes i am using the next().charAt(0) function of the scanner class before accepting the array it is accepting a character array... i had no idea this would be an issue how to go around this ? – Learningman Jan 11 '20 at 13:59
  • Edit your question with that information, and the *code*. – Matthieu Jan 12 '20 at 04:53

2 Answers2

1

Maybe you read from a file, and the last line does not end with a line break.

From a Scanner you may first test whether a next line is available:

String[] n = new String[5];
for (int i = 0; i < 5; i++) {
    if (!sc.hasNextLine()) {
        System.out.println("Failing to read line at index " + i);
        break;
    }
    n[i] = sc.nextLine();
}

Notice that String[] n is the usual way to write an array variable. String n[] is for C programmers.

Joop Eggen
  • 96,344
  • 7
  • 73
  • 121
0

It would be helpful if you provided information on what your input source is. However, sc.nextLine() always progresses the scanner to the next line (excluding any line separators at the end of the line).

Your code is correct given (for example) an input file such as "test.txt":

Line1

Line2

Line3

Line4

Line5

I would make sure there's no spaces between your input and that you don't accidentally call sc.nextLine() (or any of the scanner next methods) somewhere earlier in your code.

Wyatt
  • 31
  • 6
  • have used the next().charAt(0) function before this to accept a character array prior to calling the nextline() func i did not know it would be a problem, how do i counter this ? – Learningman Jan 11 '20 at 14:00