2013年12月15日星期日

What loop termination condition of this program is ?

If the title is basically a program book, has been in the black window, input state , input what end?

import java.util.*;

public class Test
{
public static void main(String[] args)
{
     Set<String> words = new HashSet<String>();
     long totalTime = 0;

      Scanner in = new Scanner(System.in);
      while(in.hasNext())              //这个循环的终止条件是什么       
                                                     //呀,怎么在黑窗口中一直是输入状态?输入一 
                                                      //个什么会终止?
      {
  String s = in.next();
  long callTime = System.currentTimeMills();
  words.add(s);
  callTime = System.currentTimeMills() - callTime;
  totalTime = totalTime + callTime;
      }

     Iterator<String> it = words.iterator();
     for(int i=1; i<=20 && it.hasNext(); i++)
     {
 System.out.println(it.next());
     }

}
}


------ Solution ------------------------------------- -------
this cycle does not terminate , should you end up manually input stream on the line .. looks like Ctrl + z. Try
------ Solution -------------------------------------- ------

import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

public class Test {
public static void main(String[] args) {
Set<String> words = new HashSet<String>();
long totalTime = 0;

Scanner in = new Scanner(System.in);
while (in.hasNext()) // 这个循环的终止条件是什么
// 呀,怎么在黑窗口中一直是输入状态?输入一
// 个什么会终止?
{
String s = in.next();
long callTime = System.currentTimeMillis();
words.add(s);
callTime = System.currentTimeMillis() - callTime;
totalTime = totalTime + callTime;
if(s.equals("exit")){ // 加个判断条件
break;
}
}

Iterator<String> it = words.iterator();
for (int i = 1; i <= 20 && it.hasNext(); i++) {
System.out.println(it.next());
}

}
}


------ Solution ---------------------------- ----------------
own prices termination conditions such as when you knock into the character equals ** This is on break out of the loop .
------ For reference only -------------------------------------- -
Thank you , indeed either manually ctrl + z, or add a judgment conditions . Meanwhile my original program has a word wrong currentTimeMills, in front of one less s i. Causing me good looking.

没有评论:

发表评论