Pergunta

I need to check that all the elements in my List a are positive. My method uses (tries to use) recursion to check elements are > 0.

My error message complains that the list is empty. I am obviously missing something simple here so please help me understand what is happening.

static boolean allPositive(List a) {

    // If list is empty, show a warning message.
    if (a.isEmpty()){
        System.out.println("No elements in list!");
    }
      // If both head and tail are less than 0, return false.
       if (a.getHead() >= 0 && allPositive(a.getTail())) {
          return true;
      }
      // If there are elements < 0, return false.   
    return false;
    }

Here is the List class, pretty standard I think:

public class List {

private boolean empty;
private int head;
private List tail;

// Constructor for List, creates a head and tail(another List).
public List(int head, List tail) {
    this.empty = false; 
    this.head = head;
    this.tail = tail;
}

public List() {
    this.empty = true;
}

// To add tail when creating List.
public static List cons(int head, List tail) {
    return new List(head,tail);
}

// Empty list.
public static List empty() {
    return new List();
}

public boolean getEmpty() {
    return this.empty;
}

public boolean isEmpty() {
    return empty;
}

The error says:

Exception in thread "main" java.lang.IllegalStateException: Trying to access head of an empty list

But the List I am using is created here:

List a = List.cons(1, List.cons(2, List.cons(3, List.cons(4, List.empty()))));
Foi útil?

Solução

allPositive recurses and will eventually reach the tail which triggers the empty message. It will also call getHead on empty elements.

If you consider an empty list to be all positive, and you don't need the warning message, use:

static boolean allPositive(List a) {
    if (a.isEmpty()) {
        return true;
    } else {
        return (a.getHead() >= 0 && allPositive(a.getTail())
    }
}

If you need the warning message on empty lists, you would need to do something like:

static boolean allPositive(List a) {
    if (a.isEmpty()) {
        System.out.println("No elements in list!");
    }
    // This internal method won't warn on the empty list encountered during recursion.
    return allPositiveInternal(a);
}

static boolean allPositiveInternal(List a) {
    if (a.isEmpty()) {
        return true;
    } else {
        return (a.getHead() >= 0 && allPositiveInternal(a.getTail())
    }
}   
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top