gpt4 book ai didi

java - Java编码-程序在运行时挂起

转载 作者:行者123 更新时间:2023-12-02 11:09:19 25 4
gpt4 key购买 nike

我的Java代码遇到问题,并且知道问题出在哪里,但是我似乎无法弄清楚该如何解决。有人可以帮忙吗?这是导致该问题的那行,我不确定如何解决。 小计= sc.nextDouble();

import java.text.NumberFormat;
import java.util.InputMismatchException;
import java.util.Scanner;

public class InvoiceApp
{
private static double subtotal;
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String choice = "y";

while (!choice.equalsIgnoreCase("n"))
{
// get the input from the user
String customerType = getValidCustomerType(sc);
try
{
System.out.print("Enter subtotal: ");
subtotal = sc.nextDouble();
}
catch (InputMismatchException e)
{
sc.next();
System.out.println("Error! Invalid number. Try again. \n");
continue;
}
// get the discount percent
double discountPercent = 0.0;
double subtotal = sc.nextDouble();

if (customerType.equalsIgnoreCase("R"))
{
if (subtotal < 100)
discountPercent = 0;
else if (subtotal >= 100 && subtotal < 250)
discountPercent = .1;
else if (subtotal >= 250)
discountPercent = .2;
}
else if (customerType.equalsIgnoreCase("C"))
{
if (subtotal < 250)
discountPercent = .2;
else
discountPercent = .3;
}
else
{
discountPercent = .1;
}

// calculate the discount amount and total
double discountAmount = subtotal * discountPercent;
double total = subtotal - discountAmount;

// format and display the results
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
System.out.println(
"Discount percent: " + percent.format(discountPercent) + "\n" +
"Discount amount: " + currency.format(discountAmount) + "\n" +
"Total: " + currency.format(total) + "\n");

// see if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
}
private static String getValidCustomerType(Scanner sc)
{
String customerType = "";
boolean isValid = false;
while (isValid == false)
{
System.out.print("Enter customer type (r/c): ");
customerType = sc.next();
if (!customerType.equalsIgnoreCase("r") && !customerType.equalsIgnoreCase("c"))
{
System.out.println("Invalid customer type. Try again. \n");
}
else
{
isValid = true;
}
sc.nextLine();
}
return customerType;
}
}

最佳答案

程序在执行时不会挂起:

subtotal = sc.nextDouble();

而是只是等待控制台输入 double 值。输入一个值,其余的程序魔术应紧随其后。

关于java - Java编码-程序在运行时挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28121339/

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