我正在设置一个聊天机器人程序。你能告诉我如何改变吗 代码中的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++) {
答案 0 :(得分:2)
我们可以尝试以下逻辑:
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
循环之外定义的,并且增量步骤也作为循环内的单独行发生。
答案 1 :(得分:0)
允许这个
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循环,而两者都相同...
在for循环中,所有三个参数(初始化;决定; inc / dec)都在同一行 但是在While循环中,您必须拆分所有三个参数。
但逻辑上,&while是相同的。.
希望它会帮助您..
继续学习