java array using scanner -
in program, want display array using scanner
, i.e user enters array values during runtime.
public class namecomparator { public static void main(string args[]) { scanner sn = new scanner(system.in); int n = sn.nextint(); system.out.println("the array size is" + n); int[] = new int[7]; (int = 0; >= a.length; i++) { a[i] = sn.nextint(); system.out.println("the value of a[i]" + a[i]); } sn.close(); system.out.println("array values are"); } }
here, have got array size scanner
, using for
loop each array value, don't know why array block hasn't executed. jvm skips for
loop. scanner
works well
this:
for(int i=0;i>=a.length;i++)
should be:
for (int = 0; < a.length; i++)
you want loop long i
smaller a.length
(i.e. size of array). loop exited (or skipped) if termination condition returns false
. since you're initializing i
0
, i>=a.length
(i.e. 0 >= 7
) instantly false
.
please note, i've wrote i < a.length
, not i <= a.length
. array size set 7
, therefore valid indices 0
6
. you'll arrayindexoutofboundsexception
if try access index 7
.
and forgot use variable n
set array size:
int[] a= new int[n];
Comments
Post a Comment