NeedHelp
NeedHelp

Reputation: 27

Reverse Array Error

I keep getting same error message when I changed code to while loop from for loop. For loop code works fine but not this one. Only thing I added is extra method called printArray because without another method it keep saying your i already defined in method 'reverseNumbersWhile' when I define i for second while loop.

import java.util.*;
public class ReverseNumbersWhile
{

  //Declare Variables
  public static final int num = 10;
  public static int nums[] = new int[num];

  public void reverseNumbersWhile(int num) 
  {
    //Create scanner and user input
    Scanner input = new Scanner(System.in);
    System.out.print("Enter 10 numbers : ");

    //Define i
    int i = 0;

    //For loop to fill the array
    while(i < nums.length) 
    {
      i++;
      nums[i] = input.nextInt();
    }
      } //end of reverseNumbersFor

  public void printArray(int num)
  {
    //Define var result and i
    String result = new String();
    int i = nums.length - 1;

    //for loop to print the array's elements reversed
    while (i >= 0 ) 
    {
      result += (nums[i] + " ");
    }
    System.out.print("In reverse order : " + result);
  } //end of printArray 

  public static void main(String[] args)
  {
    ReverseNumbersWhile sc = new ReverseNumbersWhile();
    sc.reverseNumbersWhile(num);
  } // end of main

} //end of public class

and here is my output. Scanner still works but seems other codes doesn't.

> run ReverseNumbersWhile
Enter 10 numbers :  [1 2 3 4 5 6 7 8 9 10]

java.lang.ArrayIndexOutOfBoundsException: 10
    at ReverseNumbersWhile.reverseNumbersWhile(ReverseNumbersWhile.java:34)
    at ReverseNumbersWhile.main(ReverseNumbersWhile.java:55)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:267)

Upvotes: 1

Views: 113

Answers (2)

Srikanth Chekuri
Srikanth Chekuri

Reputation: 2274

Your while loop code needs a simple modification.It should be something like this..

while(i < nums.length) {

    nums[i] = in.nextInt() ;

    i++ ;

}

pre incrementing is the cause for IndexOutOfBounds Exception.

Upvotes: 1

inafalcao
inafalcao

Reputation: 1452

The error is here:

while(i < nums.length) 
    {
      i++;
      nums[i] = input.nextInt();
    }

Imagine when i = 9, and it's still going to enter the loop, since nums.length = 10, and 9 < 10:

  1. you'll first do i++, so i = 10
  2. After that, nums[i] = input.nextInt();, but i = 10!

You can't do nums[10], since the array's index is only ranged in 0 - 9.

To correct this, just postpone the i++ line.

while(i < nums.length) 
{
  nums[i] = input.nextInt();
  i++;
}

Upvotes: 3

Related Questions