Understanding try & catch and error handling

前端 未结 3 1399
我在风中等你
我在风中等你 2020-12-20 07:25
import java.util.Scanner;

public class Lab4_5 {
    public static void main(String[]args) {
        Scanner scan= new Scanner(System.in);

        int rows=0;
              


        
3条回答
  •  鱼传尺愫
    2020-12-20 07:45

    You can create a try-catch block like so:

    try {
        int num = scan.nextInt();
    } catch (InputMismatchException ex) {
        // Exception handling here
    }
    

    If you want to implement this in your code, I suggest doing this:

    while (true) {
        try {
            rows = scan.nextInt();
            if (rows<5||rows>21) {
                break;
            }
            else {
                System.out.println("That is either out of range or not an integer, try again! ");
            }
        } catch (InputMismatchException ex) {
            System.out.println("That is either out of range or not an integer, try again! ");
        }
    }
    

    See here for more details.

提交回复
热议问题