gpt4 book ai didi

java - Java 中的错误处理 InputMismatchException

转载 作者:行者123 更新时间:2023-12-02 05:55:13 34 4
gpt4 key购买 nike

我正在创建电梯模拟,但在错误处理方面遇到问题。当用户输入字母而不是整数时,它会抛出 InputMismatchException。我该如何解决?下面是代码:

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();

最佳答案

这里有一些代码可能会有所帮助。读取整数并在循环中捕获异常。当输入是整数时,循环退出。当抛出异常时,循环继续。

  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

关于java - Java 中的错误处理 InputMismatchException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23163764/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com