2014/07/11

[Java] 讀取鍵盤輸入




怎麼用:

?
1
2
3
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
int in = scanner.nextInt();


輸入後如果要比對標準格式? -> 結合正規表達式

正規表達式筆記:http://goo.gl/vcN8vs

例如:

?
1
2
3
4
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
boolean check = str.matches("([0-9]){8}");
//比對輸入是否為連續八位數字,是則check為true,否為false

要比對輸入有無關鍵字? -> 結合Matcher和正規表達式

傳送門:http://goo.gl/UpWjYb

例如:

?
1
2
3
4
5
6
7
8
9
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
String keyword = new String("關鍵字");
Pattern pattern = Pattern.compile(keyword);
Matcher matcher = pattern.matcher(str);
While (matcher.find()){
    System.out.print("有此關鍵字");
}