在int中输入小数时打印出错误

时间:2014-10-09 03:49:03

标签: java int java.util.scanner

我正在编写一个名为Revenue的程序,除了一个之外我满足了所有要求。

  System.out.print("\t Enter quantity(ies): ");
    quantity = keyboard.nextInt();
    if (quantity < 0 || quantity > 150 || quantity == '.'){

        System.out.println();
        System.out.println("\t Invalid item price.");
        System.out.println("\t Please run the program again");
        System.out.println();
        System.out.println("Thank you for using \"Temple\" store");
        System.exit(0);

我们必须询问用户他们购买的商品的数量,并且不能有小数或'。'在里面。例如,当要求用户输入他们想要购买的商品数量时,他们将输入该数字。如果他们输入带小数的数字,则应打印出

     Invalid item price.
     Please run the program again

Thank you for using "Temple" store

3 个答案:

答案 0 :(得分:1)

keyboard.nextInt()不允许小数。如果输入类似“3.14.15”的内容,则会抛出异常。对于错误处理,您需要捕获此异常并打印出比默认情况下看到的堆栈跟踪更好的错误消息。

答案 1 :(得分:1)

使用try-catch块来完成你想要的任务:

  System.out.print("\t Enter quantity(ies): ");
  try{
    quantity = keyboard.nextInt();
    if (quantity < 0 || quantity > 150)
     throw new IllegalArgumentException();
  } catch (IllegalArgumentException e) {
     System.out.println();
     System.out.println("\t Invalid item price.");
     System.out.println("\t Please run the program again");
     System.out.println();
     System.out.println("Thank you for using \"Temple\" store");
     System.exit(-1); //-1 signs an error to the application that launched the program
  }

答案 2 :(得分:0)

使用以下代码:

  String quantity = keyboard.next();  // use keyboard.next() instead of keyboard.nextInt() 
                 // because it will throw Exception if value is other 
                                       //than int   

   boolean flag = quantity.matches("[0-9]+");
    if (flag) {
        if (Integer.parseInt(quantity) < 0
                || Integer.parseInt(quantity) > 150) {
            flag = false;
        }
    }

    if (!flag) {
        System.out.println();
        System.out.println("\t Invalid item price.");
        System.out.println("\t Please run the program again");
        System.out.println();
        System.out.println("Thank you for using \"Temple\" store");
        System.exit(0);
    }