RuuddR
RuuddR

Reputation: 941

Java String doesn't get replaced

I have made this small script to test something, but I can't get it working. I want it to replace the "%20" in the string to " ". This gets printed out: Ravenous%20Cache.zip

package test;

public class Test {

    public static void main(String[] args) {
        System.out.println(getArchivedName());
    }

    private static String cacheLink = "https://dl.dropboxusercontent.com/u/Ravenous%20Cache.zip";

    private static String getCacheLink() {
        return cacheLink;
    }

    private static String getArchivedName() {
        String name = cacheLink.replace("%20", " ");
        int lastSlashIndex = name.lastIndexOf('/');
        if (lastSlashIndex >= 0 
            && lastSlashIndex < getCacheLink().length() -1) { 
            return getCacheLink().substring(lastSlashIndex + 1);
        } else {
            System.err.println("Error Downloading Game Files.");
        }
        return "";
    }

}

Upvotes: 0

Views: 81

Answers (3)

Rajesh
Rajesh

Reputation: 2155

public class Test {

    public static void main(String[] args) {
        System.out.println(getArchivedName());
    }

    private static String cacheLink = "https://dl.dropboxusercontent.com/u/Ravenous%20Cache.zip";

    private static String getCacheLink() {
        return cacheLink;
    }

    private static String getArchivedName() {
        cacheLink = cacheLink.replace("%20", " ");
        int lastSlashIndex = cacheLink.lastIndexOf('/');
        if (lastSlashIndex >= 0 && lastSlashIndex < getCacheLink().length() - 1) {
            return getCacheLink().substring(lastSlashIndex + 1);
        } else {
            System.err.println("Error Downloading Game Files.");
        }
        return "";
    }
}

Upvotes: 0

Forseth11
Forseth11

Reputation: 1438

Try this:

public static void main(String[] args) {
        System.out.println(getArchivedName());
    }

    private static String cacheLink = "https://dl.dropboxusercontent.com/u/Ravenous%20Cache.zip";

    private static String getCacheLink() {
        return cacheLink;
    }

    private static String getArchivedName() {
        String name = cacheLink.replace("%20", " ");
        int lastSlashIndex = name.lastIndexOf('/');
        if (lastSlashIndex >= 0 
            && lastSlashIndex < getCacheLink().length() -1) { 
            return name.substring(lastSlashIndex + 1);//Changed
        } else {
            System.err.println("Error Downloading Game Files.");
        }
        return "";
    }

You were returning getCacheLink() not name.

Upvotes: 0

JP Moresmau
JP Moresmau

Reputation: 7403

You're calling getCacheLink() again when you take the substring that gives you back the original string

return name.substring(lastSlashIndex + 1);

Upvotes: 2

Related Questions