Java - Write code to set Extension name

Requirements

Write code to set Extension name

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String filename = "book2s.com";
        String ext = "book2s.com";
        System.out.println(setExtension(filename, ext));
    }/*from w  w w. jav  a  2s.  c om*/

    public static String setExtension(String filename, String ext) {
        if (hasExtension(filename, ext))
            return (filename);
        int index = filename.lastIndexOf(".");
        if (index == -1)
            return (filename + "." + ext);
        return (filename.substring(0, index + 1) + ext);

    }

    public static boolean hasExtension(String filename, String ext) {
        int index = filename.lastIndexOf(".");
        if (index == -1)
            return (false);
        return (filename.substring(index + 1).compareTo(ext) == 0);
    }
}

Related Exercise