猿问

嵌套while循环迭代

巢式while循环发生问题,导致以下问题:

线程“主”中的异常java.lang.ArrayIndexOutOfBoundsException:Chatbot.main中为2(Chatbot.java:25)

我不太确定是什么引起了ArrayIndexOutOfBoundsException。
这样做的部分要求是,我不允许使用while循环以外的任何其他形式的循环。也不能使用任何continue,break等

任何见解将不胜感激。

尼克

下面的代码:

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]);


 }


}


阿波罗的战车
浏览 148回答 1
1回答

HUH函数

更改topics[numTopics]到topics[numTopics-1]你的最后一行的代码,因为指数在0阵列启动String&nbsp;dialog1&nbsp;=&nbsp;JOptionPane.showInputDialog("Tell&nbsp;me&nbsp;more&nbsp;about&nbsp;"&nbsp;+&nbsp;topics[numTopics-1]);
随时随地看视频慕课网APP

相关分类

Java
我要回答