集册 Java实例教程 使用一种方法通过catch块从用户获取有效整数,该catch块捕获错误并强制循环重复。

使用一种方法通过catch块从用户获取有效整数,该catch块捕获错误并强制循环重复。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

464
使用一种方法通过catch块从用户获取有效整数,该catch块捕获错误并强制循环重复。

import java.util.*;

/*
 from n o w j a v a . c o m - 时代Java 
*/

public class GetInteger

{

    static Scanner sc = new Scanner(System.in);


    public static void main(String[] args)

    {

        System.out.print("Enter an integer: ");

        int i = GetInteger();

        System.out.println("You entered " + i);

    }


    public static int GetInteger()

    {

        while (true)

        {

            try

            {

                return sc.nextInt();

            } catch (InputMismatchException e) {/*时 代      J a v a   公   众 号 - nowjava.com 提供
展开阅读全文