简体   繁体   English

错误在Java中处理InputMismatchException

[英]Error Handling InputMismatchException in Java

Im creating a lift simulation but am having trouble with the error handling. 我正在创建一个升力模拟,但我遇到了错误处理问题。 When a user inputs a letter instead of a integer it throws a InputMismatchException. 当用户输入一个字母而不是整数时,它会抛出一个InputMismatchException。 How do i fix this? 我该如何解决? Here is the code below: 以下是代码:

System.out.println("Please define... ");
        System.out.println("Number of floors:");
        Building building = new Building(in.nextInt()); 
        System.out.println("Number of lifts:");
        building.setNoOfLifts(in.nextInt());
        building.setLifts();
        System.out.println("Maximum number of people to enter building at one time:");
        building.setMaxPeople(in.nextInt());
        System.out.println("Maximum capacity of the lifts:");
        int maxLiftCapacity = in.nextInt();
        System.out.println("Simulation will now begin.");
        Queue queue = new Queue();

Here's some code that may help a bit. 这里有一些代码可能有所帮助。 Read the integer and catch the exception in a loop. 读取整数并在循环中捕获异常。 When the input is an integer, the loop exits. 当输入是整数时,循环退出。 When an exception is thrown, the loop continues. 抛出异常时,循环继续。

  Scanner sc = new Scanner(System.in);
  int i=0;
  while(true) {
      System.out.println("enter an integer:");
      try {
          int i = sc.nextInt();          
          break;
     } catch(InputMismatchException ignore){}
 }

 // i has been read successfully

nextInt() is only applicable if you know for certain that you will get an integral value next. nextInt()仅适用于您确定接下来将获得积分值的情况。 (That is, the input is from a source more reliable than a user.) (也就是说,输入来自比用户更可靠的源。)

What do I suggest? 我有什么建议? The broadest scope of input is a String , so take one of those. 最广泛的输入范围是String ,所以请选择其中一个。 That might look something like the below. 这可能类似于下面的内容。

String strFloors = in.nextLine();
strFloors = strFloors.replaceAll("[^\\d]", ""); // Strip non 1234567890 characters
intFloors = Integer.valueOf(strFloors);
Building building = new Building(intFloors);

Or if you want to fit it into just the one line, you could put it together like 或者如果你想把它放在一行中,你就可以把它放在一起

Building building = new Building(Integer.valueOf(in.nextLine().replaceAll("[^\\d]", "")));

The best error handling is certainty of none arising. 最好的错误处理是确定没有出现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM