gpt4 book ai didi

java - 我的循环有些东西不工作。它可以运行但不循环

转载 作者:行者123 更新时间:2023-11-30 03:09:20 25 4
gpt4 key购买 nike

while (input != '1'){
String customer;
customer = JOptionPane.showInputDialog("Enter customer's name: ");

String type;
type = JOptionPane.showInputDialog("Choose type of photocopy: G/C");

if (type.equals("G")) {
noOfPhotocopy = Integer.parseInt(JOptionPane
.showInputDialog("Enter no of photocopy: "));

if (noOfPhotocopy < 10) {
totalprice = noOfPhotocopy * 0.10;
} else if (noOfPhotocopy >= 10) {
totalprice = noOfPhotocopy * 0.05;
}
} else if (type.equals("C")) {
noOfPhotocopy = Integer.parseInt(JOptionPane
.showInputDialog("Enter no of photocopy: "));

if (noOfPhotocopy < 10) {
totalprice = noOfPhotocopy * 0.20;
} else if (noOfPhotocopy >= 10) {
totalprice = noOfPhotocopy * 0.10;
}
}

JOptionPane.showMessageDialog(null, "Customer name : "+customer+"\nType of Photocopy : "+type+"\nNumber of Photocopy : "+noOfPhotocopy+"\nTotal Price : RM"+ (float)totalprice);

String input1;
input1 = JOptionPane.showInputDialog( "Press 1 to stop or press anything to continue ");
input = Integer.parseInt(input1);
break;
}
JOptionPane.showMessageDialog(null, "Program finished ^^");

请帮我解决这个代码。我无法确定这段代码有什么问题。当我运行这个程序时,循环似乎不起作用。这是我的作业项目,需要提前提交。

为什么我的循环不循环?

最佳答案

你无条件地打破break 将始终退出封闭循环。

此外,您的循环条件中 charint 之间存在类型混淆。由于类型强制,它是合法的(int 将转换为 char 进行比较,反之亦然),但它不会执行您想要的操作。

'1'

是一个字符。它是一个 UTF-16 字符,其 int 值为 49

1

是一个int

你真的想要这个:

while (input != 1) {

这是解决此问题的另一种方法,当程序出现梨形问题(不按预期工作)时,您可以普遍应用该方法。

备份此代码并启动一个新的 Java 类。在该类中创建一个较小的示例。也许是这样的:

while (input != '1') {
String input1;
input1 = JOptionPane.showInputDialog( "Press 1 to stop or press anything to continue ");
input = Integer.parseInt(input1);
break;
}
JOptionPane.showMessageDialog(null, "Program finished ^^");

这个程序有同样的错误,但要小得多。你能看出那个小程序中的问题吗?

这种通过删除代码或注释掉代码的方法可以让您通过反复试验来隔离错误。随着时间的推移,您将对错误产生直觉并立即看到它们,但这种方法为您提供了到达这一点的途径。

关于java - 我的循环有些东西不工作。它可以运行但不循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33949790/

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