2013-10-11 70 views
1

我試圖在java中實現System.exit(0);來終止我的程序,當單詞「exit」輸入到控制檯。我寫了下面的方法:這段代碼爲什麼不終止我的程序? Java

public static void exit(){ 

    Scanner input = new Scanner(System.in); 
    Str1 = input.next(String); 

    if (str1 = "exit"){ 

     System.exit(0); 
    } 

    else if (str1 = "clear"){ 

     System.out.println("0.0"); 
    }  
} 

它似乎並沒有工作。有沒有人有什麼建議?

謝謝 P.S「清除」只是應該返回0.0當「清除」進入控制檯,如果你不能告訴。

+0

如果你想用Google如何比較你會得到字符串你的答案。 :) – NewUser

+0

btw除了等於(),我認爲你的代碼有一些小錯誤。 Str1和str1是不同的。 – gjman2

+1

你有沒有放過它?無論如何都調用System.exit(0)? – JulianG

回答

5

將字符串與equals()比較而不是與==比較。

原因是==只比較對象引用/基元,其中as String的.equals()方法檢查相等性。

if (str1.equals("exit")){ 

} 

並且還

else if (str1.equals("clear")){ 

} 

強權有用:What are the benefits of "String".equals(otherString)

+0

更好 - ''退出「.equals(str1)' – sanbhat

+1

@sanbhat補充說。Thankyou :) –

1
if(str.equals("exit")) 

if(str.equalsIgnoreCase("exit")) 

if(str == "exit") 

代替

if (str1 = "exit"){ 
1

使用String.equals(String other)功能比較字符串,而不是==操作。

函數檢查字符串的實際內容,==運算符檢查對象的引用是否相等。請注意,字符串常量通常是「interned」的,這樣兩個具有相同值的常量實際上可以與==進行比較,但最好不要依賴它。

所以使用:

if ("exit".equals(str1)){ 

} 
+0

這些都非常有幫助,謝謝。但是,我實現了這些更改,並且控制檯仍在拋出異常而不是終止程序。 –

+0

投擲什麼異常? @CharlieTidmarsh – gjman2

+0

@CharlieTidmarsh你能告訴我你的例外嗎? –

1

隨着if (str1 = "exit")您使用,而不是一個比較的分配。 您可以使用equals()方法進行比較。

0

此外equals(),該input.next(String pattern);需要的圖案不是String數據類型

你的代碼更改爲:

public static void exit(){ 

Scanner input = new Scanner(System.in); 
str1 = input.next(); //assumed str1 is global variable 

if (str1.equals("exit")){ 

    System.exit(0); 
} 

else if (str1.equals("clear")){ 

    System.out.println("0.0"); 
} 

} 

注:http://www.tutorialspoint.com/java/util/scanner_next_string.htm

+2

將'str1 = input.next();'改爲'String str1 = input.next();',除非'str1'是一個全局變量 – JulianG

+0

@JulianG注意。謝謝 – gjman2