asked on
public class ArrayTenElements {
public static void main(String[] args) {
// TODO Auto-generated method stub
//int i=4;
int a[]= new int[4];
a[0]=0;
a[1]=1;
a[2]=2;
a[3]=3;
for(int i=0;i<=3;i++)
{
//int a[]= new int[i];
System.out.println(a[i]);
}
/*for(int i=0;i<=9;i++)
{
//a[i];
System.out.println(a[5]);
//i--;
}*/
}
}
ASKER
public class ArrayTenElements {
public static void main(String[] args) {
// TODO Auto-generated method stub
//int i=4;
//int a[]= new int[4];
//a[0]=0;
//a[1]=1;
//a[2]=2;
//a[3]=3;
/*for(int i=0;i<=3;i++)
{
//int a[]= new int[i];
a[0]=0;
a[1]=1;
a[2]=2;
a[3]=3;
//a[i]=i;
System.out.println(a[i]);
}*/
for(int i=0;i<=3;i++)
{
int a[]= new int[i];
a[i]=i;
System.out.println(a[i]);
}
}
}
ASKER
for(int i=0;i<=3;i++)
{
int a[]= new int[4];
a[i]=i;
//a[0]=0;
//a[1]=1;
//a[2]=2;
//a[3]=3;
System.out.println(a[i]);
}
ASKER
ASKER
package Arrays;
public class ArrayTenElements {
public static void main(String[] args) {
// TODO Auto-generated method stub
int j=10; // 10 elements
for(int i=0;i<=(j-1);i++)
{
int a[]= new int[j];
a[i]=i;
System.out.println(a[i]);
}
}
}
And the same here; I have to put it inside the ????! Wow!
Java is a platform-independent, object-oriented programming language and run-time environment, designed to have as few implementation dependencies as possible such that developers can write one set of code across all platforms using libraries. Most devices will not run Java natively, and require a run-time component to be installed in order to execute a Java program.
TRUSTED BY
Are you saying that the code above works (which I agree with) but if you uncomment line 14 it fails? If so, then yes, because with line 14 uncommented, what you are asking it to do is...
- Loop around 4 times (i from 0 to 3 inclusive)
- For each loop, create an array whose size is determined from the index i
- Print out the ith element from the array just created
The problem is that on the first loop, i = 0 so you create a 0 length array, but then you attempt to print the array element with index 0 (which due to 0 based index is the FIRST element). But there is no first element because it has 0 length, i.e. there are 0 elements in the array, and so it fails on IndexOutOfBounds exception.
Even if it got past this first loop, the second would create an array of size = 1, but then you try to print the a[1] element which is the SECOND element but there is only 1 element, so it still throws an exception.
So, now to what you are trying to do... It not clear from "Next I want to initialize and print the array within the for loop" EXACTLY what you are trying to get it to do. If you can elaborate on this, then we can help further.