如何处理BigDecimal的错误用户输入



我正在编写JAVA代码,用户输入是BigDecimal。以前我写过这样的在检查整数输入时做:

int number= 0;
do {
System.out.print("Enter number: ");
number= scan.nextInt();
}
while (number< 0);

现在我有BigDecimal用户输入

BigDecimal price = scan.nextBigDecimal();
scan.nextLine();

如何处理错误的用户输入,如int,例如,如果用户输入-10,00或输入10.00(应该是10,00(?

Scanner类具有扫描不同区域设置中的数字的功能,为此您可以使用方法useLocale((和reset((。此外,您可以调用hasNextBigDecimal((方法,该方法返回true/false。

<运算符在BigDecimal中未定义,因此必须使用compareTo((方法。compareTo((的返回值分别为0、-1和1。

返回: -101,因为此BigDecimal在数字上小于、等于或大于值。

查看下面的代码。

  1. 首先,将价格作为输入,转换为BigDecimal
  2. 然后使用compareTo((方法比较转换后的价格,以检查价格是正还是负
  3. 如果价格为正,则将价格保留为正,否则将其转换为负
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter price");
BigDecimal price = scan.nextBigDecimal();
if (price.compareTo(BigDecimal.ZERO) > 0) {
System.out.println("Price is greater than 0(positive)");
/*....Write your business logic....*/
} else if (price.compareTo(BigDecimal.ZERO) < 0) {
System.out.println("Price is less than 0(negative)");
/* This line converts negative price to positive */
price = price.multiply(new BigDecimal("-1"));
/*....Write your business logic....*/
}
}

最新更新