udbhav shrivastava
udbhav shrivastava

Reputation: 63

String Array's first item is always blank when using scanner input

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.

Upvotes: 0

Views: 236

Answers (1)

Sither Tsering
Sither Tsering

Reputation: 1308

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.

Upvotes: 1

Related Questions