2013-04-25 53 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終止線應該由您來輸入,當你想關閉/終止掃描儀。