gpt4 book ai didi

java - 当试图循环回到开头时陷入无限循环。 java

转载 作者:行者123 更新时间:2023-12-02 04:09:28 29 4
gpt4 key购买 nike

如果用户输入无效的大小,我试图让代码循环。但它陷入了无限循环。我尝试将“while”添加到底部并添加“do”来启动循环,但我要么得到相同的结果,要么代码停止而不循环回到开头。

import javax.swing.JOptionPane;
import java.text.DecimalFormat;

public class BarkingLotJOP5
{
public static void main(String[] args)
{
String size;
Double sm = 8.00, md = 12.00, lg = 17.00, total, tax = .09;
DecimalFormat df = new DecimalFormat("$###,###.##");

JOptionPane.showMessageDialog(null,"Welcome to BarkingLot.com.");
JOptionPane.showMessageDialog(null, "It is $5 for small, $10 for medium, and $15 for large.");

size = JOptionPane.showInputDialog("Enter the dog's size.");

while
(!size.equals("small") || size.equals("medium")|| size.equals("large"))
{
if
(size.equalsIgnoreCase("small"))
{
total = (sm*tax)+sm;
JOptionPane.showMessageDialog(null,"For a small dog, your total is "+ df.format(total)+
"\nThank you, have a great day!");
}
else
if
(size.equalsIgnoreCase("medium"))
{
total = (md*tax)+md;
JOptionPane.showMessageDialog(null,"For a medium dog, your total is "+ df.format(total)+
"\nThank you, have a great day!");
}
else
if
(size.equalsIgnoreCase("Large"))
{
total = (lg*tax)+lg;
JOptionPane.showMessageDialog(null,"For a large dog, your total is "+ df.format(total)+
"\nThank you, have a great day!");
}
else
JOptionPane.showMessageDialog(null,"Error");
}
}
}

最佳答案

while(!(size.equals("small") || size.equals("medium")|| size.equals("large")))

(注意大括号)。基本上你的代码检查如下:

如果满足以下条件,则继续循环:

大小不等于:

大小等于:

大小等于:

但你想要:

如果满足以下条件,则继续循环:

尺寸等于(小、中、大)

编辑:

在 else 条件中而不是:

else
JOptionPane.showMessageDialog(null,"Error");

您可以使用:

else{
JOptionPane.showMessageDialog(null,"Error, try again");
size = JOptionPane.showInputDialog("Enter the dog's size.");
}

这将使输入框再次出现,并将 size 值再次设置为新值。

关于java - 当试图循环回到开头时陷入无限循环。 java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33929367/

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