首页 > 解决方案 > 如何将代码中的for循环更改为while循环?

问题描述

我正在设置一个聊天机器人程序。能否请您告诉我如何将代码中的 for 循环更改为代码中的 while 循环。

我努力了:

int j = 0;
while(j<numinputs()){
...
j++;
}

...

String[] inputs;
inputs = new String[numinputs];
int i = 0;
while (i < numinputs) {
    inputs[i] = JOptionPane.showInputDialog(null, "Please enter key word " + (i + 1) + " ");
    if (inputs[i].contains("?") || inputs[i].isEmpty()) {
        JOptionPane.showMessageDialog(null, "Invalid Response");
    } else
        i = i + 1;
}
System.out.println(Arrays.toString(inputs));
for (int j = 0; j < numinputs; j++) {
    String search = JOptionPane.showInputDialog("Tell me more about" + " " + inputs[j]);
    System.out.println(search);
    if (search.contains("exit")) {
        System.exit(0);
    }
}

}

这是我要更改的代码:

inputs = new String[numinputs];
int i = 0;
while (i < numinputs) {
    inputs[i] = JOptionPane.showInputDialog(null, "Please
System.out.println(Arrays.toString(inputs));
for (int j = 0; j < numinputs; j++) {

标签: javaeclipsewhile-loop

解决方案


我们可以试试下面的逻辑:

int j = 0;
while (j < numinputs) {
    String search = JOptionPane.showInputDialog("Tell me more about" + " " + inputs[j]);
    System.out.println(search);
    if (search.contains("exit")) {
        System.exit(0);
    }
    ++j;
}

上述循环在逻辑上应该与for您当前拥有的循环相同。不同之处在于虚拟变量循环计数器j是在while循环外定义的,并且增量步骤在循环内作为单独的行发生。


推荐阅读