控制台程序。
java.util.Scanner类定义的对象使用正则表达式来扫描来自各种源的字符输入,并把输入显示为各种基本类型的一系列标记或者显示为字符串。
默认情况下,Scanner对象读取标记时,假定它们用空白分隔开。对于空白对应的任意字符,Character类中的isWhitespace()方法都返回true。因此,读取标记时,要跳过分隔符,找到不是分隔符的字符,然后尝试以要求的方式解释那些不是分隔符的字符序列。
1 import java.util.Scanner; 2 import java.util.InputMismatchException; 3 4 public class TryScanner { 5 public static void main(String[] args) { 6 Scanner kbScan = new Scanner(System.in); // Create the scanner 7 int selectRead = 1; // Selects the read operation 8 final int MAXTRIES = 3; // Maximum attempts at input 9 int tries = 0; // Number of input attempts 10 11 while(tries<MAXTRIES) { 12 try { 13 switch(selectRead) { 14 case 1: 15 System.out.print("Enter an integer: "); 16 System.out.println("You entered: "+ kbScan.nextLong()); 17 ++selectRead; // Select next read operation 18 tries = 0; // Reset count of tries 19 20 case 2: 21 System.out.print("Enter a floating-point value: "); 22 System.out.println("You entered: "+ kbScan.nextDouble()); 23 ++selectRead; // Select next read operation 24 tries = 0; // Reset count of tries 25 26 case 3: 27 System.out.print("Enter a boolean value(true or false): "); 28 System.out.println("You entered: "+ kbScan.nextBoolean()); 29 } 30 break; 31 } catch(InputMismatchException e) { 32 String input = kbScan.next(); 33 System.out.println("""+ input +"" is not valid input."); 34 if(tries<MAXTRIES) { 35 System.out.println("Try again."); 36 } else { 37 System.out.println(" Terminating program."); 38 System.exit(1); 39 } 40 } 41 } 42 } 43 }