• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Tim Cooke
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
Saloon Keepers:
  • Piet Souris
Bartenders:

Issue with reversing an array in Java

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi everyone,
I am learning Java and trying to write a program to reverse an array. My goal is to take user input and print the array elements in reverse order.
However, I am getting an error and the output is not as expected.
What I am trying to do
Take input from the user
Store it in an array
Print the array in reverse order


I am getting this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
 
Greenhorn
Posts: 10
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi there Sankar Sridhar,

The IndexOutOfBoundsException shown in the output is an exception indicating that you are trying to make an access outside the bounds of your array. arrays in java are 0 indexed meaning if you have an array with n elements there are n cells indexed 0 to n - 1, this piece of code is the cause, specifically the "n -1" and "i = 0".

I am guessing you thought the for loop at will increment the i from 0 to 1 and therefore n - i would equal n - 1 (a valid inbound index). but for loops, for the first iteration will use the initialization value "i = 0" resulting in n - i = n which is an invalid out of bounds index, hence the exception. The incrementation "i++" will happen as part of the next iterations.  

Also just a small remark, the program that you are writing isn't really "Revering an Array" it is more accurately "Printing array elements in reversed order", reversing an array would actually be repositioning the elements in the array cells in reversed order.  

Hope this helps and enjoy your learning journey
 
Ranch Hand
Posts: 44
1
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Sankar Sridhar, hope you are doing well
First as Houcem Eddin Hrichi said

Houcem Eddin Hrichi wrote: Also just a small remark, the program that you are writing isn't really "Revering an Array" it is more accurately "Printing array elements in reversed order", reversing an array would actually be repositioning the elements in the array cells in reversed order.  


You are printing the array in reverse order.
When you encounter an exception try to search what it is then it becomes easier to fix.
An exception in Java is an event that occurs during the execution of a program and disrupts its normal flow(Google).

Sankar Sridhar wrote:

       // Attempt to reverse
       System.out.println("Reversed array:");
       for(int i = 0; i < n; i++) {
           System.out.print(arr[n - i] + " ");
       }
   
I am getting this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException


ArrayIndexOutOfBoundsException means that you are using an illegal index on array.

Array uses indexes to access its elemets.
Indexes start from 0.

Suppose that the "n" in your code is 5 (five elements).
With indexes you can access your elements in array, these are 0,1,2,3,4 = 5 elements.

On first step of execution of loop you are accessing array with index 5 because n - i = 5 - 0;

If you want to fix this error initialize variable "i" starting with 1 and try to use <= symbol on condition to access first element.

I hope you understood something.
 
Bartender
Posts: 1202
20
Mac OS X IntelliJ IDE Oracle Spring VI Editor Tomcat Server Redhat Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here's a version:



If you're using an IDE, then it's often good to run the code in debug mode and step through each line of code.  
 
Marshal
Posts: 82420
594
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Sankar Sridhar wrote:. . . int arr[] = new int[n]; . . .

Have you been taught to write that sort of code? The placement of the [] is correct for C, but incorrect usage for Java®, even if it will compile and run. The correct usage in Java® is to have the [] in the type, like this:-

int[] arr = new int[n];

It is also possible to use the Scanner#tokens() method to create a Stream and have that create the array.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic
Morty Proxy This is a proxified and sanitized view of the page, visit original site.