0

My string array's first element is always blank for some reason and I cannot seem to figure out the error in my array input and display code :

import java.util.Scanner;
public class Source {
public static void main(String args[] ) throws Exception {      
    int i=0,size=0,j=0,flag1=0;
    Scanner in = new Scanner(System.in);
    System.out.println("Input Size");
    if(in.hasNextLine()){
        size = in.nextInt();
    }
    System.out.println("Input Elements");
    String[] input = new String[size];      
    i=0;
    String blank = in.nextLine();
    while(i<size){          
        if(in.hasNextLine()) {
        System.out.println("i ="+i);            
        input[i]=in.nextLine();
        i++;
        }           
    } 
    i=0;
    System.out.println("Input Array is");
    while(i<size){          
        System.out.println("Input"+i+"= "+input[i]);
        i++;
    }
  }
}

The gives me the following output in the terminal Terminal Output

What do I seem to be doing incorrectly ? Would love to understand what is my error is here.

1 Answers1

1

Put System.out.println("i ="+i); outside of if.

while(i<size){ 
    System.out.println("i ="+i); 
    if(in.hasNextLine()) {
        input[i]=in.nextLine();
        i++;
    }           
} 

Also, in.nextLine(); is enough to skip newline. No need to store it String blank = in.nextLine();.

Scanner skipping nextLine() is taken care of by String blank = in.nextLine();, but yet it still takes one extra blank.
The reason is if(in.hasNextLine()), if there's no input given it'll be stuck there and won't print the i=0, and I assume you have press enter which makes the condition true and prints i=0 but that enter blank new line is considered as input for i=0. Then followed by input string1 which is input for i=1 and so on.

sittsering
  • 1,219
  • 2
  • 6
  • 13
  • 1
    Ah I see,thank you ! is there a specific reason the scanner takes one extra blank line as input ? afaik shouldn't it just take the next string input for `input[0]` ? – udbhav shrivastava Mar 30 '22 at 18:10
  • 1
    @udbhav for question in previous comment see [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/q/13102045/16320675) – user16320675 Mar 30 '22 at 19:19
  • @udbhavshrivastava sorry for the late reply, I've added an explanation in the answer. you can check. – sittsering Mar 31 '22 at 04:41