gpt4 book ai didi

java - 我会只使用 do while 循环吗?

转载 作者:行者123 更新时间:2023-11-29 06:01:35 26 4
gpt4 key购买 nike

我希望用户能够搜索这个短列表,但我不希望 JOptionPane 在输入错误数字时关闭。另外我将如何设置一个终止词,即如果用户键入“退出”,循环将结束并且程序将退出。我会使用 do while 循环吗?

  int key, list[] = {8,22,17,24,15};
int index;

key = Integer.parseInt(JOptionPane.showInputDialog(null,"Input the integer to find"));

index = searchList(list, key);

if(index < list.length)
JOptionPane.showMessageDialog(null,"The key " + key + " found the element " + index);
else
JOptionPane.showMessageDialog(null,"The key " + key + " not found");

System.exit(0);


}

private static int searchList(int[] n, int k) {
int i;
for (i = 0; i < n.length; i++)
if(n[i] == k)
break; //break loop if key found
return i;

最佳答案

你可以尝试这样的事情:

import javax.swing.JOptionPane;


public class Key {

public static void main(String[] args){

int key, list[] = {8,22,17,24,15};
int index;

String userOption = "null";

while(!userOption.equals("quit")){
userOption = JOptionPane.showInputDialog(null,"Input the integer to find");

//Take the cancel action into account
if(userOption == null){
break;
}

//Try to get valid user input
try{
key = Integer.parseInt(userOption);

index = searchList(list, key);

if(index < list.length){
JOptionPane.showMessageDialog(null,"The key " + key + " found the element " + index);
//uncommented the break below to exit from the loop if successful
//break;
}
else
JOptionPane.showMessageDialog(null,"The key " + key + " not found");

} catch (Exception e){
//Throw an exception if anything but an integer or quit is entered
JOptionPane.showMessageDialog(null,"Could not parse int", "Error",JOptionPane.ERROR_MESSAGE);
}
}
System.exit(0);
}

private static int searchList(int[] n, int k) {
int i;
for (i = 0; i < n.length; i++)
if(n[i] == k)
break; //break loop if key found
return i;

}
}

这不是完美的代码,但它应该可以完成工作。如果您有任何疑问,我非常乐意为您提供帮助。

快乐编码,

海登

关于java - 我会只使用 do while 循环吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9916677/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com