Determine Java source file name (Java)

Determine the Java source file name
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description

Enter several lines of strings, and determine whether each line of strings can be used as the source file name of Java. in:

Naming rules for Java source files: legal Java identifier + ".java";

Naming rules for Java identifiers: can contain letters, numbers, underscores, $, but numbers cannot be used as the first letter.
Input

The input has multiple lines, one string per line.
Output

If the line string can be used as the source file name of Java, output "true"; otherwise, output "false".
Sample Input

abc.java
_test
t e s t . j a v a 12.java
a 1.java
a+b+c.java
a’b.java
123.java
变量.java
Main.java.java
ab abc.java

Sample Output

true
false
true
true
false
false
false
false
true
false
false

Hint
Source
zhouxq


import java.util.*;
import java.util.Scanner;

public class Main22 {
    public static void main(String args[]){
        Scanner input = new Scanner(System.in);
        while(input.hasNext()) {
            String ss = input.nextLine();
            if(legal(ss)) {
                System.out.println("true");
            }
            else {
                System.out.println("false");
            }
        }
        input.close();
    }
    public static boolean legal(String str) {
        int a = str.indexOf(".");
        String end = str.substring(a+1);     //把"."后面的字符串分离出来
        boolean last = false;
        if(end.equals("java")) {              //若后缀名为Java则为true
            last = true;
        }
        if(Character.isJavaIdentifierStart(str.charAt(0)) && last && a != -1) {     //判断首字符是否符合命名规则且后缀名满足条件并且有后缀名
            for(int i = 1;i < a;i++) {
                if(Character.isJavaIdentifierPart(str.charAt(i)) != true) {         //判断首字母之外的其他部分是否满足命名规则
                    return false;
                }
            }
            return true;
        }
        return false;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324904914&siteId=291194637