【发布时间】:2014-01-15 17:52:08
【问题描述】:
我需要检查List a 中的所有元素是否肯定。我的方法使用(尝试使用)递归来检查元素是否 > 0。
我的错误消息抱怨列表为空。我显然在这里遗漏了一些简单的东西,所以请帮助我了解正在发生的事情。
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;
}
这是 List 类,我认为很标准:
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;
}
错误提示:
线程“主”java.lang.IllegalStateException 中的异常:尝试 访问空列表的头部
但我使用的列表是在这里创建的:
List a = List.cons(1, List.cons(2, List.cons(3, List.cons(4, List.empty()))));
【问题讨论】: