gpt4 book ai didi

Java 特定客户类型

转载 作者:行者123 更新时间:2023-12-01 13:16:15 24 4
gpt4 key购买 nike

我想制作一个代码,其中只有客户“R”、“C”和“T”可以进行小计。每当我输入另一个字母(即“S”、“L”、“A”等)时,我希望输出是无效条目。但是,当我输入不是 R、C 或 T 的字母时,系统仍会要求我输入小计。一如既往的帮助。谢谢。代码如下。

======================

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

public class ValidatedInvoiceApp
{

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
System.out.print("Enter customer type (r/c/t): ");
String customerType = sc.next();
System.out.print("Enter subtotal: ");
double subtotal = sc.nextDouble();

// call the DiscountPercent method
double discountPercent = getDiscountPercent(
customerType,subtotal);

// 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 double getDiscountPercent(String customerType,double subtotal)
{

double discountPercent = 0;

if (customerType.equalsIgnoreCase("R"))
{
if (subtotal < 100)
discountPercent = 0;
else if (subtotal >= 100 && subtotal < 250)
discountPercent = .1;
else if (subtotal >= 250 && subtotal < 500)
discountPercent = .25;
else
discountPercent = .30;
}
else if (customerType.equalsIgnoreCase("C"))
{
discountPercent = .20;
}
else if (customerType.equalsIgnoreCase("T"))
{
if (subtotal < 500)
discountPercent = .40;
else if (subtotal >= 500)
discountPercent = .50;
}
else

{
System.out.println("Error! Invalid Customer Type. Please Try Again. \n");
sc.nextLine();
}
return discountPercent;
}

private static class sc {

private static void nextLine() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}

public sc() {
}
}
}

最佳答案

您不对输入进行任何类型的检查。

System.out.print("Enter customer type (r/c/t): ");
String customerType = sc.next();
System.out.print("Enter subtotal: ");
double subtotal = sc.nextDouble();

你应该使用 do-while (或者如果你想要其他行为则使用其他东西)

String customerType;
do
{
System.out.print("Enter customer type (r/c/t): ");
customerType = sc.next();
}
while (!customerType.equalsIgnoreCase("r") && !customerType.equalsIgnoreCase("c") && !customerType.equalsIgnoreCase("t"));

使用此代码,直到他写入 r、c 或 t 为止,系统会要求他再次插入。

无论如何,您应该考虑使用 char 而不是 String。

关于Java 特定客户类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22442985/

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