exception when trying to print an array in Java - java

I have this very little program in Java (just started to learn this language):
package hellojava;
public class Hellojava {
public static void main(String[] args) {
System.out.println("Hello World");
int[] nums = {1,2,3,4,5,6,7,8,9,10};
int[] revs = reverse(nums);
for (int i : revs) {
System.out.println(revs[i]);
}
}
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i=0, j=result.length-1; i<list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
}
It throws this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10 at hellojava.Hellojava.main(Hellojava.java:9).
So I pretty know what's wrong and know how to fix it, but my question is about that for loop. I thought that this enhanced for loop will work here, but it doesn't. Why's that?

The problem is that the enhanced for loop gives the values of the array, not the indexes. So, 10 the value is returned, which is an invalid index.
Your loop beginning:
for (int i : revs) {
is equivalent to
for (int index = 0; index < revs.length; index++)
{
int i = revs[index];
}

The enhanced for loop gives you the values in an array, not the indexes. Try
for (int i : revs) {
System.out.println(i);
}

Simple:
for (int i : revs) {
System.out.println(i);
}
You are using a foreach statement instead of a for indexed loop. The foreach loop iterates the array for you and assign the element of the array to i so don't consider it as an index of an array.
Here is an Oracle documentation on the For-Each Loop.

Replace
System.out.println(revs[i]);
with
System.out.println(i);
Explanation: The variable i is the integer element and not an index.

Related

Initializing multidimensional arrays with enhanced for loop in java

I'm just playing around with my code, and was wondering if initializing a multidimensional array with the enhanced for loop is possible.
How do I fix this?
double[][] array2 = new double[2][5];
int b=1;
counter=0;
for(double[] x:array2)
{
for(double a:x)
{
array2[][counter]=b; //<- errors here
counter++;
b+=2;
}
}
//output what it contains
for(double[] x:array2)
{
for(double a:x)
{
System.out.println(a);
}
}
How would you guys do it with 3 dimensions?
double[][][] array3 = new double[4][5][6];
I know I could use Collections for this stuff but I was just trying things out.
Since you need an index to write into an array, you can’t use the enhanced for loop for updates. However, you are modifying only the innermost arrays in the case of a multi-dimensional array in Java. Therefore you can use the enhanced for loop for the outer arrays:
double[][] array2 = new double[2][5];
int b=1;
for(double[] x:array2) {
for(int index = 0; index < x.length; index++) {
x[index]=b;
b+=2;
}
}
The same applies to any number of dimensions:
double[][][] array3 = new double[4][5][6];
int b=1;
for(double[][] outer: array3)
for(double[] inner: outer)
for(int index = 0; index < inner.length; index++) {
inner[index]=b;
b+=2;
}
What you are trying to do makes no sense, since you must know the indices of the array in order to assign values to it.
The enhanced for loop hides those indices from you, so you'll have to maintain your own indices, which makes using the enhanced for loop pointless.
Sure, you can do something like this :
int b=1;
int row=0;
for(double[] x:array2)
{
int col=0;
for(double a:x)
{
array2[row][col]=b;
col++;
b+=2;
}
row++;
}
But since you are not using x and a, you can just use a regular for loop :
int b=1;
for(int row=0;row<array2.length;row++)
{
for(int col=0;col<array2[row].length;col++)
{
array2[row][col]=b;
b+=2;
}
}
You tell me which version is more readable.

printing a modified array from a void method

I saw the below code in a book. I know that the void method cannot return a value. when I ran the code, the compiler could not print the modified array, while in the book, the values are shown. How can I fix the code to print the modified array?
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
System.out.println("The values of original array are:");
for(int value: array)
{
System.out.print(value + "\t");
}
modifyArray(array);
System.out.println("The values after modified array are:");
for (int value:array)
{
System.out.print(value + "\t");
}
}
public static void modifyArray(int[] b)
{
for (int counter=0; counter<=b.length; counter++)
{
b[counter] *=2;
}
}
If I am not mistaken, you should be getting an ArrayIndexOutOfBoundsException for your modifyArray() method. change the for loop in the method to
for (int counter=0; counter<b.length; counter++) // use < not <=
{
b[counter] *=2;
}
for (int counter=0; counter<=b.length; counter++)
This code runs for 6 times thus trying to access the 6th element of your array which doesn't exist. It must be ArrayIndexOutOfBoundsException error.
Change above line to:
for(int counter = 0; counter<b.length; counter++)
This will work!
The code actually works but there is an error in the method for loop that cause a IndexOutOfBound Exception this is the correct version.
public static void modifyArray(int[] b)
{
for (int counter=0; counter<b.length; counter++)
{
b[counter] *=2;
}
}
The method returns void but you can read the modify values inside the array because you are passing as method argument the reference of the array not a copy of the array. this is a very basic concept of the Java Language you should start reading
Passing Information to a Method or a Constructor.

I get an exception when trying to find smallest value array

I am trying to find the smallest value in an array of integers, but when I do I get an arrayindexoutofbounds on a place which, as far as I know, there shouldn't be a counting of array-index, only a comparison of the index and a min-value.
Part of code in question underneath:
}
System.out.println(sum);
int minste=tall[0];
for (int i : tall){
if(tall[i]<tall[0]){ //This is where the exception is made. But why?
minste=tall[i];
}
}
System.out.println(minste);
}
}
i is already an element, just use it. No need to tall[i]:
if(i < minste) {
This loop means: "For each int in tall".
In order to better understand the enhanced loop, think about it this way:
for(int i = 0; i < tall.length; i++) {
System.out.println(tall[i]);
}
Will print the same thing as:
for(int i : tall) {
System.out.println(i);
}
That's why it's recommended to use a meaningful name for the variable, instead of i, use item, so it'll be like "for each item in tall"...
Alternative solution to find the smallest value:
Use Arrays#sort
Return the first element in the array
When you're using the for-each loop, why use the indexes?
if(tall[i]<tall[0]){
tall[i] - gives the ArrayIndexOutOfBoundsException because i is an element in your array and not an index value. And that value i is definitely more than the length of your array.
All you need to do is thi
int minste = tall[0];
for (int i : tall) {
if(i < minste) {
minste = i;
}
}
You are using for-each loop, but try to use i as a index.
To work properly change your code to
int minste = tall[0];
for (int i : tall)
{
if(i < minste)
{
minste = i;
}
}
or
int minste = tall[0];
for (int i = 0; i<tall.length; i++)
{
if(tall[i] < minste)
{
minste = tall[i];
}
}

Using a for loop to copy one array to another

I've been working with arrays and I'm trying to find a way to copy one array to another solely with a for loop (I've seen things like arrayCopy and clone in other threads, but for this exercise I need to just copy from one array to another using a for loop).
Right now my code executes, but just spits this out: "[D#133c5982". The code I'm using is:
public class sorted
{
public static void main(String[] args)
{
int [] unSortedArray = {8,12,6,5,19};
System.out.println(copyArray(unSortedArray));
//System.out.println(sortedArray(unSortedArray));
}
public static int[] copyArray(int[] array)
{
int [] copyArray;
copyArray = new int[array.length];
for (int i = 1; i < array.length; i++)
{
copyArray[i] = array[i];
}
return copyArray;
}
First of all, you are not copying whole array, as you starting your index with 1
as in your code
for (int i = 1; i < array.length; i++)
{
copyArray[i] = array[i];
}
start the index with 0
and second you can make use of Arrays.deepToString(array) or Arrays.toString(array) to print array in readable format
Your code is OK, it does copy the array. When you do System.out.println it prints out the default implementation of the array's toString() method). To see that it is indeed copied, you can do
for (int i = 0; i<unsortedArray.length; i++) {
System.out.println(unsortedArray[i]);
}
for (int i = 0; i<copiedArray.length; i++) {
System.out.println(copiedArray[i]);
}
EDIT: see the comments for what you code actually prints out
copyArray returns an array and that's what you are printing. What you see is the Java Virtual Machine way of representing objects as strings. #12345 is the object's ID.
There is nothing wrong with the code provided, except a } at the end (possibly omitted while copying).
When printing you are using the arrays default toString which doesn't print the content of the Strings.
Since Java 1.5 you can use Arrays.toString(array) to get a nice String representation of the array.
See the API here.
Use this with System.out.println to get a nice printout.
What you have done is correct. But if you print an array using System.out.println(copyArray(unSortedArray)); it only prints out the location of the array. Instead, try printing each element of the array in a for loop.
for (int i = 1; i < array.length; i++)
{
system.out.println(array[i]);
}
//Arrays.toString(<arrayname>) can also be used in place of the for loop.
Also, array index starts at 0. So, your method should be as follows.
public static int[] copyArray(int[] array)
{
int [] copyArray;
copyArray = new int[array.length];
for (int i = 0; i < array.length; i++)
{
copyArray[i] = array[i];
}
return copyArray;
try this
package naveed.workingfiles;
import java.util.Arrays;
public class Array
{
public static void main(String[] args)
{
int [] unSortedArray = {8,12,6,5,19};
int [] unSortedCopyArray =new int [unSortedArray.length];
//System.out.println(sortedArray(unSortedArray));
for(int i=0;i<unSortedArray.length;i++)
{
unSortedCopyArray[i]=unSortedArray[i];
}
System.out.println(Arrays.toString(unSortedArray));//exist array
System.out.println(Arrays.toString(unSortedCopyArray));//copied array
}
}

printing all the array value

class ArrayApp{
public static void main(final String[] args){
long [] arr;
arr= new long[100];
int i;
arr[0]=112;
arr[1]=111;
for(i=0;i<arr;i++) {
System.out.println(arr[i]);
}
}
}
I get this error,
ArrayApp.java:10: operator < cannot be applied to int,long[]
for(i=0;i<arr;i++) {
^
You need to use the size of the array, which would be arr.length.
for (int i = 0; i < arr.length; ++i)
As of Java 1.5, you can also use the for each loop if you just need access to the array data.
for ( long l : arr )
{
System.out.println(l);
}
arr is an object of long[] , you can't compare int with it.
Try arr.length
Alternatively You should go for
for(long item:arr){
System.out.println(item);
}
You want arr.length
The question has to be seen in the context of a previous question!
From this former question I remember that you actually have a logical array inside a physical array. The last element of the logical array is not arr.length but 2, because you've "added" two values to the logical array.
In this case, you can't use array.length for the iteration but again need another variable that store the actual position of "the last value" (1, in your case):
long[] arr;
arr= new long[100];
int i;
arr[0]=112;
arr[1]=111;
int nElem = 2; // you added 2 values to your "logical" array
for(i=0; i<=nElem; i++) {
System.out.println(arr[i]);
}
Note - I guess, you're actually learning the Java language and/or programming. Later on you'll find it much easier to not use arrays for this task but List objects. An equaivalent with List will look like this:
List<Integer> values = new ArrayList<Integer>();
values.add(112);
values.add(111);
for (Integer value:values)
System.out.println(value);
Long arr = new Long[100];
arr[0]=112;
arr[1]=111;
for(int i=0;i<arr.length;i++) {
if (arr[i] != null ) {
System.out.println(arr[i]);
}
}
if you want to show only those which are filled.
You can solve your problem using one line of code:
Arrays.asList(arr).toString().replace("[", "").replace("]", "").replace(", ", "\n");
See http://java.dzone.com/articles/useful-abuse for more similar tricks.

Categories

Resources