0

My professor asked me to do the following homework in Java, but I'm getting error while trying to execute the code.

Please take a look at the code and let me know what's causing the error? The code is saved into Reverse.java file.

package javaapplication44;
import java.util.Scanner;
public class Reverse {
    public static void main (String[] args) {
        String Fname[] = new String[4];
        Scanner s = new Scanner(System.in);
        for (int i=0; i<=4; i++) {
            System.out.println("\n Enter Something: ");
            Fname[i] = s.nextLine();
        }
        System.out.println ("*** The String has been Reversed ***");
        for (int i=4; i>0; i--) {
            System.out.println (Fname[i]);
        }
    }
}

error text:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at javaapplication44.Reverse.main(Reverse.java:14)

3 Answers 3

3

When u take 4 elements array then u have to count less then 4 Not less than and equal 4. first loop will be conditioned i< 4

And also the second loop will be conditioned i>3

Hope it will work

Sign up to request clarification or add additional context in comments.

1 Comment

Second loop should be conditioned as i=3
1

Array indexes start from zero

change

 for (int i=0; i<=4; i++) {

to

 for (int i=0; i<4; i++) {

also, in your second for loop, start the loop from i=3

  for (int i=3; i>0; i--) {

say if your array is of length 4, the last index would be 3.

just remember this:

 LastINdexOfAnArray = Array_Length -1;

Comments

0

Change...

for (int i=0; i<=4; i++) {

...to...

for (int i=0; i<4; i++) {

You're iterating one beyond the size of your array, getting the ArrayIndexOutOfBoundsException exception.

You also need to account for this in your second loop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.