Home > front end >  String Array's first item is always blank when using scanner input
String Array's first item is always blank when using scanner input

Time:03-31

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.

CodePudding user response:

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();.

  • Related