java - 如何将代码中的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++) {
解决方案
我们可以试试下面的逻辑:
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
循环外定义的,并且增量步骤在循环内作为单独的行发生。
推荐阅读
- c# - ReCaptcha 3 HTML Helper 在按钮中单击 ASP.NET MVC
- ios - iOS MapBox 适合相机到多个坐标 [纬度和经度] 或注释
- javascript - Javascript不将类添加到标签
- react-native - React Native - 从没有库的命令行切换 .env
- algorithm - 以最小成本断开无向加权图中的两个节点
- python - 由于 Python 中的破折号,我无法导入库
- blogs - 本地或 Netlify 上的 Hugo 站点未检测到我的内容文件夹
- python - 从延迟加载页面中提取href
- oop - 理解抽象类 OOD -> 关系模式
- python - 如何更改 cv2 矩形的角度?