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  ww w .  jav  a  2 s  .com

    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