Trouble creating a simple array in Java -
i'm having bit of trouble creating simple array in java random number generated every time loops. code follows:
public class q1 { public static void main(string[] args) { scanner listscan = new scanner(system.in); system.out.println("size of list sort?"); int j = listscan.nextint(); int listarray[] = new int[j]; (int = 0; <= j; i++){ listarray[i] = (int)(math.random() * 100 +1); } system.out.println(listarray); } }
but code gives me this:
exception in thread "main" java.lang.arrayindexoutofboundsexception: 3 @ lab3.q1.main(q1.java:18) @ sun.reflect.nativemethodaccessorimpl.invoke0(native method) @ sun.reflect.nativemethodaccessorimpl.invoke(nativemethodaccessorimpl.java:57) @ sun.reflect.delegatingmethodaccessorimpl.invoke(delegatingmethodaccessorimpl.java:43) @ java.lang.reflect.method.invoke(method.java:601) @ com.intellij.rt.execution.application.appmain.main(appmain.java:120)
take @ part of code:
int listarray[] = new int[j]; (int = 0; <= j; i++){ listarray[i] = (int)(math.random() * 100 +1); } it should changed this:
int listarray[] = new int[j]; (int = 0; < j; i++){ listarray[i] = (int)(math.random() * 100 +1); } notice how <= changed <:
for (int = 0; <= j; i++){ vs:
for (int = 0; < j; i++){ for pretty coding, including java, counting starts @ 0. 5, in coding 4.
let's length of array 3, meaning contains 0, 1, , 2. so, when doing this:
for (int = 0; <= j; i++){ j = length of array, 3.
for (int = 0; <= 3; i++){ now, loop threw numbers 0, 1, 2, , 3. yet, our array not contain 3, contains 0, 1, , 2. so, if this:
for (int = 0; < j; i++){ j = 3
for (int = 0; < 3; i++){ using new code, loop threw 0, 1, , 2, same size of our array, 0, 1, , 2.
Comments
Post a Comment