Try-Catch inside a loop

百般思念 提交于 2019-12-13 09:35:47

问题


In the below code, I ask the user to give an integer input and if the input is 0 or a negative number, it loops again until the positive number is given. The thing is that if the users presses a letter, my code crashes and despite the fact that I used try-catch in a lot of ways nothing really worked. Any ideas? I used try-catch inside the loop, but it only worked for one letter input and not correctly.

System.out.print("Enter the number of people: ");

numberOfPeople = input.nextInt();

while (numberOfPeople <= 0) {

      System.out.print("Wrong input! Enter the number of people again: ");

      numberOfPeople = input.nextInt();

}

回答1:


The problem in your current code is that you're always trying to read an int so when receiving a non-integer input you can't handle the error in the right way. Modify this to always read a String and convert it into an int:

int numberOfPeople = 0;
while (numberOfPeople <= 0) {
    try {
        System.out.print("Enter the number of people: ");
        numberOfPeople = Integer.parseInt(input.nextLine());
    } catch (Exception e) {
        System.out.print("Wrong input!");
        numberOfPeople = 0;
    }
}
//continue with your life...


来源:https://stackoverflow.com/questions/16861633/try-catch-inside-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!