1

I was doing an assignment the other day that required using String Arrays and faced an interesting problem. Below is a part if my code

int i;
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
String[] array = new String[n];

for ( i = 0; i < array.length; i++) {
    array[i] = sc.nextLine();
}

On running the above code i found that i was not able to input to all arrays always one less i.e for n=2 i was able to input only one string array. The problem was fixed when I changed n to String variable

int i;
Scanner sc=new Scanner(System.in);
String n=sc.nextLine();
String[] array = new String[Integer.parseInt(n)];

for ( i = 0; i < array.length; i++) {
    array[i] = sc.nextLine();
}

I couldn't figure out the reason for this.

Tunaki
  • 116,530
  • 39
  • 281
  • 370

0 Answers0