Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
414 views
in Technique[技术] by (71.8m points)

java - Try-Catch inside a loop

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

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...