0

I'm having an issue with a nest while loop that is causing the following:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at Chatbot.main(Chatbot.java:25)

I'm not really sure what is causing the ArrayIndexOutOfBoundsException.
Part of the requirements of this, is that I'm not allow to use any other form of loop other than a while loop. Also can't use any continue,break etc.

Any insight would be highly appreciated.

Nik

Code Below:

import javax.swing.JOptionPane;

public class Chatbot {

public static void main(String[] args) {

    String[] topics;
    int numTopics = Integer.parseInt(JOptionPane.showInputDialog("How many topics would you like to talk about?"));

    while (numTopics < 1) {
        numTopics = Integer.parseInt(JOptionPane.showInputDialog("Error! Please enter a positive number of topics!"));

    }
    int i = 0;
    topics = new String[numTopics];
    while (i < topics.length) {
        topics[i] = JOptionPane.showInputDialog("Please enter topic " + i);
        while (topics[i].contains("?")) {
            topics[i] = JOptionPane.showInputDialog("I'll ask the questions here, Please enter topic " + i);

        }
        i = i + 1;

    }
    String dialog1 = JOptionPane.showInputDialog("Tell me more about " + topics[numTopics]);

 }

}
XNikXX
  • 15
  • 5

1 Answers1

1

Change topics[numTopics] to topics[numTopics-1] for your last line code,because indexes start at 0 in array

String dialog1 = JOptionPane.showInputDialog("Tell me more about " + topics[numTopics-1]);
flyingfox
  • 13,414
  • 3
  • 24
  • 39
  • 1
    Because `indexes start at 0` in Java, and therefore end at `n - 1`. – Mehdi Jul 04 '18 at 10:05
  • Thanks so much. That's exactly what it was. Wasn't aware that by calling it in the method I was, I was skipping the 0 index and going from 1. – XNikXX Jul 04 '18 at 11:26