Java基础之一组有用的类——使用Scanner对象(TryScanner)

控制台程序。

java.util.Scanner类定义的对象使用正则表达式来扫描来自各种源的字符输入,并把输入显示为各种基本类型的一系列标记或者显示为字符串。

默认情况下,Scanner对象读取标记时,假定它们用空白分隔开。对于空白对应的任意字符,Character类中的isWhitespace()方法都返回true。因此,读取标记时,要跳过分隔符,找到不是分隔符的字符,然后尝试以要求的方式解释那些不是分隔符的字符序列。

 import java.util.Scanner;
import java.util.InputMismatchException; public class TryScanner {
public static void main(String[] args) {
Scanner kbScan = new Scanner(System.in); // Create the scanner
int selectRead = 1; // Selects the read operation
final int MAXTRIES = 3; // Maximum attempts at input
int tries = 0; // Number of input attempts while(tries<MAXTRIES) {
try {
switch(selectRead) {
case 1:
System.out.print("Enter an integer: ");
System.out.println("You entered: "+ kbScan.nextLong());
++selectRead; // Select next read operation
tries = 0; // Reset count of tries case 2:
System.out.print("Enter a floating-point value: ");
System.out.println("You entered: "+ kbScan.nextDouble());
++selectRead; // Select next read operation
tries = 0; // Reset count of tries case 3:
System.out.print("Enter a boolean value(true or false): ");
System.out.println("You entered: "+ kbScan.nextBoolean());
}
break;
} catch(InputMismatchException e) {
String input = kbScan.next();
System.out.println("\""+ input +"\" is not valid input.");
if(tries<MAXTRIES) {
System.out.println("Try again.");
} else {
System.out.println(" Terminating program.");
System.exit(1);
}
}
}
}
}
上一篇:linux 共享内存 shmat,shmget,shmdt,shmctl


下一篇:python 操作手机