数量超出范围示例

时间:2018-04-19 01:47:58

标签: java exception

我有一个除了Number Out of Range示例之外的代码,我无法弄清楚我做错了什么。

import java.util.*;
public class Project11
{
    public static void main( String args[] )
    {
       //declare an integer num
       int num=0;
       //Scanner object
       Scanner kbd = new Scanner(System.in);
       //do -while loop
       do          
       {
           //calling try-catch block
           try
           {
               System.out.print("Enter int in range 1..100 inclusive: ");
               //read num value from keyboard
               num=kbd.nextInt();
               //read new line and ignore
               kbd.nextLine();

               //throw user defined exception , NumberOutOfRangeException
               if(num<1 || num>100)
                   throw new NumberOutOfRangeException("Number out of range. 
Must be in 1..100 inclusive:"+num);
           }
           //thorw system defined , InputMismatchException exception
           catch (InputMismatchException e) {
               System.out.println("Input was not an integer");
               //read new line and ignore
               kbd.nextLine();
           }
           //thorw system defined , NumberOutOfRangeException exception
           catch (NumberOutOfRangeException e) {
               System.out.println(e.getMessage());
           }
           catch (Exception e) {
               System.out.println(e);
               System.exit(0);
           }
       } while(num<1 || num>100);
       System.out.format("Thank you. You entered %d\n",num );
   } //END main
} //END CLSS

public class NumberOutOfRangeException extends Exception
{
    public NumberOutOfRangeException(String msg) {
       super(msg);
    }
}

1 个答案:

答案 0 :(得分:0)

只做

kbd.nextInt();

并删除

kbd.nextLine(); 

调用kbd.nextInt();

之后