2013-04-25 84 views
7
public static void main(String[] args) { 

     Scanner scan = new Scanner(System.in); 
     try { 
      while (scan.hasNextLine()){ 

       String line = scan.nextLine().toLowerCase(); 
       System.out.println(line); 
      } 

     } finally { 
      scan.close(); 
     } 
    } 

想知道如何在完成输入后终止程序? 由于扫描仪仍然会继续几经“回车”假设我要继续下面的输入... 我想:如何在输入完成后终止扫描仪?

if (scan.nextLine() == null) System.exit(0); 

if (scan.nextLine() == "") System.exit(0); 

他们没有工作....该程序继续和初始意图混淆,

回答

18

问题是,一个程序(像你的)不知道用户已经完成输入输入,除非用户...不知何故...告诉它。

有两种方式,用户可以这样做:

  • 输入一个标记“文件结束”。在UNIX上(通常是)CTRL + D和Windows CTRL + Z。这将导致hasNextLine()返回false

  • 输入一些被程序认为是“我完成了”的特殊输入。例如,它可能是一个空行,或者像“退出”这样的特殊值。该程序需要专门针对此进行测试。

(你也可以想见,使用定时器,并假设,如果他们不为N秒,或N分钟输入任何输入的用户已经完成了。但是,这不是一个用户友好的方式做这一点)。


当前版本失败的原因是您正在使用==测试空字符串。您应该使用equalsisEmpty方法。

其他要考虑的事项是区分大小写(例如“退出”与“退出”)以及前导或尾随空白(例如“退出”与“退出”)的效果。

0

使用此方法,您必须显式创建一个退出命令或退出条件。例如:

String str = ""; 
while(scan.hasNextLine() && !((str = scan.nextLine()).equals("exit")) { 
    //Handle string 
} 

此外,还必须处理字符串等于与.equals()没有==案件。 ==比较两个字符串的地址,除非它们实际上是相同的对象,否则永远不会是真的。

3

字符串比较使用.equals()而不是==完成。

因此,请尝试scan.nextLine().equals("")

1

你将不得不寻找指示例如您输入的到底说特定模式“##”

// TODO Auto-generated method stub 
    Scanner scan = new Scanner(System.in); 
    try { 
     while (scan.hasNextLine()){ 

      String line = scan.nextLine().toLowerCase(); 
      System.out.println(line); 
      if (line.equals("##")) { 
       System.exit(0); 
       scan.close(); 
      } 
     } 

    } finally { 
     if (scan != null) 
     scan.close(); 
    } 
+0

非常感谢:) – user2318175 2013-04-25 10:43:53

0

在这种情况下,我建议你使用做的,而循环,而不是一段时间。

Scanner sc = new Scanner(System.in); 
    String input = ""; 
    do{ 
     input = sc.nextLine(); 
     System.out.println(input); 
    } while(!input.equals("exit")); 
sc.close(); 

为了退出程序,您只需指定一个字符串头,例如出口。如果输入等于退出,则程序将退出。此外,用户可以按Ctrl + C退出程序。

0

您可以检查控制台的下一行输入,并检查您的终止条目(如果有)。

假设你的终止项“跳槽”,那么你应该试试这个代码: -

Scanner scanner = new Scanner(System.in); 
    try { 
     while (scanner.hasNextLine()){ 

      // do your task here 
      if (scanner.nextLine().equals("quit")) { 
       scanner.close(); 
      } 
     } 

    }catch(Exception e){ 
     System.out.println("Error ::"+e.getMessage()); 
     e.printStackTrace(); 
}finally { 
     if (scanner!= null) 
     scanner.close(); 
    } 

试试这个code.Your终止线应该由您来输入,当你想关闭/终止扫描仪。