我正试图在新类中使用for循环 我创建了一个简单的java程序,它将从一个数字一直打印到 另一个。我似乎无法掌握for循环 以下是我测试它的示例代码:
import java.util.Iterator;
public class Try {
public static void main(String[] args) {
for (int i : new IntegerLoop(1, 9)) {
System.out.print(i + " ");
}
System.out.println();
for (int i : new IntegerLoop(-3, 3)) {
System.out.print(i + " ");
}
System.out.println();
}
}
这是IntergerLoop类,它只处理要打印的第一个和最后一个数字 import java.util.Iterator;
public class IntegerLoop implements Iterable<Integer>, Iterator<Integer> {
int first, last;
int nextInt;
public IntegerLoop(int f, int l) {
first = f;
last = l;
nextInt = first;
}
public boolean hasNext() {
return nextInt >= first && nextInt <= last;
}
public Integer next() {
if (hasNext()) {
int result = nextInt; // needs Iterator
nextInt++;
return result;
}
return null;
}
@Override
public void remove() {
// TODO Auto-generated method stub
}
@Override
public Iterator<Integer> iterator() {
// TODO Auto-generated method stub
return null;
}
}
答案 0 :(得分:2)
您正在获得NullPointerException
因为您从null
方法返回iterator
...
@Override
public Iterator<Integer> iterator() {
// TODO Auto-generated method stub
return null;
}
iterator
方法每次调用时都应返回iterator
的新实例。
您可以使用Iterator
的内部类,但是对于此示例,我将其分开,因为这使得IntegerIterator
更容易重复使用(恕我直言)...
IntegerLoop
上课......
public class IntegerLoop implements Iterable<Integer> {
int first, last;
public IntegerLoop(int f, int l) {
first = f;
last = l;
}
@Override
public Iterator<Integer> iterator() {
return new IntegerIterator(first, last);
}
}
IntegerIterator
上课......
public class IntegerIterator implements Iterator<Integer> {
int first, last;
int nextInt;
public IntegerIterator(int first, int last) {
this.first = first;
this.last = last;
this.nextInt = first;
}
@Override
public boolean hasNext() {
return nextInt >= first && nextInt <= last;
}
@Override
public Integer next() {
if (hasNext()) {
int result = nextInt; // needs Iterator
nextInt++;
return result;
}
return null;
}
@Override
public void remove() {
// TODO Auto-generated method stub
}
}