-1

I can't figure out why I am getting this runtime error. Java is telling me that line 17 is the issue.

import java.util.Scanner;

public class whatIsWrong {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        int size = 0;
        String[] names;
        names = new String[size];
        System.out.printf("%nEnter number of names desired names:  ");
        size = input.nextInt();

        for(int i = 0; i < size; i++) {
           System.out.printf("%nName #%d:  ", i +1);
           names[i] = input.nextLine();
        }
    }
}
Atomzwieback
  • 528
  • 7
  • 14
  • 7
    Move `names = new String[size];` after the line `size = input.nextInt();` – janos Dec 15 '18 at 11:47
  • 1
    Voting to close as *"This question was caused by a problem that can no longer be reproduced or a simple typographical error. While similar questions may be on-topic here, this one was resolved in a manner unlikely to help future readers."* – T.J. Crowder Dec 15 '18 at 11:48
  • `names = new String[size]; ` you declared `size = 0;` – Nafis Islam Dec 15 '18 at 11:48
  • Possible duplicate of [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – Joe C Dec 15 '18 at 12:03

2 Answers2

1

It's quite easy the problem currently is that you initialize an array with the size 0. In the for loop you get the new size so the array length isn't equal to the size.

You need to initialize the array after the size = input.nextInt() line.

So it should look like that:

import java.util.Scanner;

public class whatIsWrong {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int size = 0;

        System.out.printf("%nEnter number of names desired names:  ");
        size = input.nextInt();

        String[] names = new String[size];

        for(int i = 0; i < size; i++) {
            System.out.printf("%nName #%d:  ", i +1);
            names[i] = input.nextLine();
        }
    }
}
CodeMatrix
  • 2,080
  • 1
  • 15
  • 26
0

For short:

Changing the value of size will not affect the size of the array names, which is 0.

Detailed explanation:

When names = new String[size]; is executed, the value of size is 0, so the sieze of the String array names is 0, eventhough size is changed afterwards, that will not change the size of names. So it is an empty array. By visiting names[0] in the first round of the for loop, you are assuming that it has at lest one element.

ZhaoGang
  • 3,447
  • 18
  • 28