简体   繁体   中英

recursive call from a method in a linked list

public class Dene {

    private char ch;
    private Dene next;

    public Dene(char c) {
        this.ch = c;
    }

    public void add(Dene next) {
        this.next = next;
    }

    public boolean isWriteable(String s) {

        if (this.next == null) {
            if (s.contains(Character.toString(this.ch))) {
                return true;
            } else {
                return false;
            }
        } else {
            return this.next.isWriteable(s);
        }
    }
}


public static void main(String[] args) {
    Dene d = new Dene('a');
    Dene e = new Dene('e');
    Dene f = new Dene('f');
    d.add(e);
    e.add(f);
    System.out.println(d.IsWriteable("afb"));
}

IsWriteable gets a string as a parameter and sees recursively if its possible to write that string from the chars which are connected in the linked list.. but it is not working..any ideas?

At first I had Problems to understand your code. In my opinion you should create a isWriteable(char c) function, so you can check a character recursively:

public bool isWriteable(char c){
    if (this.x == null){
        return c == this.ch;
    else {
        return this.ch == c && this.x.isWriteable(c);
    }
}

To check a string you just have to check every character of your string.

Added the code of character checking:

public bool isWriteable(String s){
    char[] chars = s.toCharArray();
    int i;
    char c;
    for (i = 0; i < chars.length; i++){
        if (!isWriteable(c)){
            return false;
        }
    }
    return true;
}

(i hope this is correct because i havent used Java for some time now)

I saw i could have made it so much easier: 我看到我可以让它变得如此简单:

public bool isWriteable(String s){
    if (this.x == null){
        return s.contains(this.ch);
    }
    else {
        return this.x.isWriteable(s) & s.contains(this.ch);
    }
}

This is recursive and serves its purpose.

It looks like you are lacking open and closing braces to clearly define what belongs in each if/else block. As a general rule even though Java allows you not to, you should always put an open and closing brace on if statements and also loops to make your code easier to read, follow, and debug.

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