如何理解java核心技术卷1中散列集的例子。
Set<String> words = new HashSet<>();
long totalTime = 0;
Scanner in = new Scanner(System.in);
System.out.println(in);
while (in.hasNext())
{
String word = in.next();
long callTime = System.currentTimeMillis();
words.add(word);
callTime = System.currentTimeMillis()-callTime;
totalTime +=callTime;
}
这里的in.hasNext判断是否为空,但是缺少next向后移动(set应该是无序的),这里的in.next是用来从控制台读取数据。那么这个循环又该如何进行,我的调试也是卡在这个地方,无法正常向后执行。希望可以得到一个详细的解释是我理解错误还是这个例子有点问题。
始音カイト
9 years, 5 months ago
Answers
碰到这种情况,请先去翻API文档:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNext()
public boolean hasNext()
Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input.
它在等待你下一个输入的时候会阻塞
如果你希望某个特定的条件退出循环,可以这么做:
Set<String> words = new HashSet<>();
long totalTime = 0;
Scanner in = new Scanner(System.in);
System.out.println(in);
while (in.hasNext())
{
String word = in.next();
if (word.equals("exit")) {
break;
}
long callTime = System.currentTimeMillis();
words.add(word);
callTime = System.currentTimeMillis()-callTime;
totalTime +=callTime;
}
System.out.print(words);
也就是当你输入exit的时候退出循环,你可以修改这个if的逻辑来结束循环
住在碉堡里的人
answered 9 years, 5 months ago