当我第一次调用stream.next()时,如何返回我输入的值?
> StringStream stream= new StringStream("pez");
> stream.next()
"pfa"
> stream.next()
"pfb"
例如,当我第一次调用stream.next()时,它应该是“pez”,并且“pfa”应该出现,直到我第二次调用stream.next()。
import java.io.*;
//the class produces a continuous sequence of strings that consist of lower case letters.
public class StringStream extends stream {
//@param FirtsV is the first value we input
private String FirstV;
//the constructor that represents the first value returned by the stream.
public StringStream(String FirstV) {
this.FirstV = FirstV;
}
//the method returns the next value of the stream.
public String next() {
StringBuilder sb = new StringBuilder(FirstV);
int l = sb.length();
if(sb.charAt(l-1) < 'z') {
sb.setCharAt(l-1, (char)(sb.charAt(l-1) + 1));
FirstV = sb.toString();
}else{
if(sb.charAt(l-1) == 'z') {
sb.setCharAt(l-1, 'a');
sb.setCharAt(l-2, (char)(sb.charAt(l-2) + 1));
FirstV = sb.toString();
}
}
return FirstV;
}
@Override
public String data() {
return FirstV;
}
}
答案 0 :(得分:0)
通过在开头添加以下行来修改next()方法:
String originalV = FirstV;
然后将您的return语句更改为
return originalV;