Problem Description
輸入若干行字符串,判斷每行字符串是否可以作為JAVA語法的合法標識符。 判斷合法標識符的規則:由字母、數字、下划線“_”、美元符號“$”組成,並且首字母不能是數字。
Input
輸入有多行,每行一個字符串,字符串長度不超過10個字符,以EOF作為結束。
Output
若該行字符串可以作為JAVA標識符,則輸出“true”;否則,輸出“false”。
Sample Input
abc
_test
$test
a 1
a+b+c
a’b
123
變量
Sample Output
true
true
true
false
false
false
false
true
Hint
Source
houxq
1 import java.util.*; 2
3 public class Main { 4 public static void main(String[] args) { 5 Scanner sc = new Scanner(System.in); 6 while (sc.hasNext()){ 7 String str = sc.nextLine(); 8 char ch; 9 int flag = 1; 10 for (int i = 0; i < str.length(); i++) { 11 ch = str.charAt(i); 12 if (i == 0){ 13 if (Character.isJavaIdentifierStart(ch)) // 使用面向對象思想,調用方法
14 flag = 1; 15 else{ 16 flag = 0; 17 break; 18 } 19 } 20 else { 21 if (Character.isJavaIdentifierPart(ch)) 22 flag = 1; 23 else{ 24 flag = 0; 25 break; 26 } 27 } 28 } 29 if (flag == 1){ 30 System.out.println("true"); 31 } 32 else{ 33 System.out.println("false"); 34 } 35 } 36 } 37 }