简体   繁体   中英

A file name in java ends in .java. Given the name of the file, return true if its a java file, else return false

public boolean isJavaFile(String str1){

        String str="";
        for(int i=0;i<str1.length();i++){
            char ch=str1.charAt(i);
            if(ch!='.')
            return false;
            else
            str=str+ch;


        }
        if(str == .java)
        return true;
        return false;


    }   

I want to do logic, without using other string functions like if i want to solve it i can solve it by using endsWith() .

There is a error in your if statement. Since .java is a string,it should be enclosed in double quotes. It should be ".java" and your code should be as follows

public boolean isJavaFile(String str1){

    String str="";
    for(int i=0;i<str1.length();i++){
        char ch=str1.charAt(i);
        if(ch!='.')
            continue;
        else 
            while(i!=str1.length()){
                str=str+str1.charAt(i);
        i++;
            }
    }

    if(str.equals(".java"))
    return true;
    return false;


}   

used this code :-

public boolean isJavaFile(String filename)
{
    int index = filename.lastIndexOf(".");
    String str = "";
    for(int i=index;i<=filename.length() -1;i++)
    {
        str += filename.charAt(i);
    }

    return str.equals(".java");
}

You can do it in reverse order.

public boolean isJavaFile(String str1) {
    String str="";
    for(int i=str1.length()-1; i >=0; i--){
        char ch = str1.charAt(i);
        if(ch=='.') {
            str=str+ch;            
            break;
        }
        else
            str=str+ch;            
    }

    if(str.equals("avaj."))
        return true;
    return false;        
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM