使用一种方法通过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 提供