gpt4 book ai didi

Java简单的PizzaOrder

转载 作者:行者123 更新时间:2023-12-01 11:59:05 25 4
gpt4 key购买 nike

我被困住了,这里有一个错误。我正在制作一个简单的披萨订购程序。该程序只是输入披萨的大小和配料,然后它会显示价格和所有内容。我想做的是,当我在顶部选择中按 Enter 键而不输入任何内容时,它应该返回零。这是代码

    <pre>
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter The Size of Pizza you " + "want: (S/M/L/C)");
String option = keyboard.nextLine().trim()
.toUpperCase();

if(!option.isEmpty())
option = option.substring(0, 1);


double pizzaPrice;
double pizzaSize;


if(option.equals(PIZZA_MEDIUM))
{
pizzaPrice = PRICE_MEDIUM;
pizzaSize = MEDIUM_DIAMETER;
}
else if (option.equals(PIZZA_LARGE))
{
pizzaPrice = PRICE_LARGE;
pizzaSize = LARGE_DIAMETER;
}
else if (option.equals(PIZZA_COLOSSAL))
{
pizzaPrice = PRICE_COLOSSAL;
pizzaSize = COLOSSAL_DIAMETER;
}
else
{
option = PIZZA_SMALL;
pizzaPrice = PRICE_SMALL;
pizzaSize = SMALL_DIAMETER;
}


System.out.println("Pizza Size: " + option);
System.out.println("Enter The Number of Toppings" +
"you want:(0-8)");
int pizzaTopping=0;


if(keyboard.hasNextInt())
pizzaTopping = keyboard.nextInt();


if(pizzaTopping < MIN_TOPPINGS)
{
pizzaTopping = MIN_TOPPINGS;
}
else if(pizzaTopping > MAX_TOPPINGS)
{
pizzaTopping = MAX_TOPPINGS;
}
else
{
pizzaTopping = pizzaTopping;
}

我已经使用披萨尺寸的字符串来完成它

   if(!option.isEmpty())

我认为它不适用于整数。我该怎么办?

谢谢

最佳答案

如果没有值(或任何其他无效值),请尝试以下代码将其设置为零 (0):

String toppingsString = keyboard.nextLine().trim();
int toppings = 0;
try
{
toppings = Integer.parseInt(toppingsString);
}
catch(NumberFormatException nfe)
{
toppings = 0;
}

关于Java简单的PizzaOrder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28122369/

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