gpt4 book ai didi

java - 如何添加 do-while 语句?

转载 作者:行者123 更新时间:2023-12-01 18:33:57 25 4
gpt4 key购买 nike

我需要让它重复要求用户输入 1 到 10 之间的数字,但当输入任何数字时它就会终止。

import javax.swing.*;

public class Demo {
public static void main (String [] args) {

int n;

n = Integer.parseInt(
JOptionPane.showInputDialog(null,
"Enter a number between 1 and 10"));

while (n < 1 && n > 10) {
JOptionPane.showMessageDialog(null,"Your number is not between 1 and 10");
n = Integer.parseInt(
JOptionPane.showInputDialog(null,
"Enter a number between 1 and 10"));
}

JOptionPane.showMessageDialog(null, "Good!\nClick OK to exit");
System.exit(0);
}
}

最佳答案

AND更改为OR:

while (n < 1 || n > 10) { ... }

...并考虑将其转换为 do-while 循环的可能性,因为您必须至少显示该提示一次。

int n;
do {
n = Integer.parseInt(JOptionPane.showInputDialog(null,
"Enter a number between 1 and 10"));
if (n >= 1 && n <= 10) {
break;
}
JOptionPane.showMessageDialog(null,"Your number is not between 1 and 10");
} while (true);

// do something useful with n, will you? )

关于java - 如何添加 do-while 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22887958/

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