【发布时间】:2016-10-10 18:02:10
【问题描述】:
我正在尝试验证应该只接受 customerType 作为 R 或 C 的输入。它不区分大小写。我的代码出错,它说我的String customerType 丢失:
import java.text.NumberFormat;
import java.util.InputMismatchException;
import java.util.Scanner;
public class InvoiceApp
{
public static void main(String[] args)
{
// Begin input
Scanner sc = new Scanner(System.in);
String choice = "y";
while (!choice.equalsIgnoreCase("n"))
{
// get the input from the user
// create catch block for customerType(r or c)
try
{
System.out.print("Enter customer type (r/c): ");
String customerType = sc.next();
}
catch (InputMismatchException e)
{
if (customerType != "r" || "c")
{
sc.next();
System.out.println("Enter a valid customer type r or c");
continue;
}
else
{
System.out.print("Enter subtotal: ");
}
}
double subtotal = sc.nextDouble();
// get the discount percent
double discountPercent = 0;
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();
}
}
}
【问题讨论】:
-
您已将声明
String customerType放入您的try中,因此它仅在try中具有范围。在你的try之前声明String customerType;,然后在你的try中使用customerType = sc.next(); -
也不要使用
==或!=来比较Strings:customerType != "r" || "c"。使用.equals()或.equalsIgnoreCase()... -
并且必须在运算符的两侧进行比较。它应该是这样的:
( !customerType.equalsIgnoreCase("r") || !customerType.equalsIgnoreCase("c") ) -
next()实际上cannot throwInputMismatchException,但即使可以,异常也意味着customerType = sc.next()执行失败,这意味着没有读取任何内容来自输入,因此尝试在 catch 块中验证customerType是完全没有意义的,即使您确实获得了要编译的代码。 --- 好奇:是什么让你认为你需要在这样的 catch 子句中编写所有代码?
标签: java validation