2012-02-23 40 views
0

我有一些if語句,我不知道如何在屏幕上顯示結果。 以下是我嘗試過的兩件事。我知道system.out進入日誌。用if語句顯示文本

if (Enter == "1") { 
    // tv.setText("This is the display 1"); 
    System.out.println("The 1"); 
} 
else if (Enter == "2") { 
    System.out.println("The 2"); 
} 
+0

輸入是一個java.lang.String嗎?如果是這樣,你需要使用'.equals()'。 – hmjd 2012-02-23 22:21:13

+0

我已經使用.equals,現在我只需要替換system.out – Pra 2012-02-23 22:34:12

回答

1

什麼是Enter?如果它是一個對象的實例,請使用小寫字母名稱,因此這將是enter

要回答這個問題,您可能會比較String s。您應該使用.equals而不是==

所以:

String enter = "1"; //your variable 
if(enter.equals("1")){ 
    System.out.println("The 1"); 
}else if(enter.equals("2"){ 
    System.out.println("The 2"); 
} 

當比較基本數據類型(如intcharboolean),可以使用==!=
當比較對象(如StringCar等),你需要使用.equals()方法。

See also this page.

編輯

使用吐司:

Toast.makeText(this, "The 1", Toast.LENGTH_SHORT).show(); 

See here

+0

我已經使用了正確的形式,我只是需要它現在在屏幕上顯示,那麼我應該如何替換system.out部分? – Pra 2012-02-23 22:23:08

+0

查看修改。 :) – nhaarman 2012-02-23 22:26:17

+0

我應該用每個if語句的toast替換system.out.println? – Pra 2012-02-23 23:01:17

0

改爲使用Toast

Toast是Android中的彈出式元素,在屏幕上顯示預定義持續時間的短消息。

String enter = "whatever value enter has"; 

int duration = Toast.LENGTH_SHORT; 
Context context = getApplicationContext(); 

String message = "The Nothing"; 
if (enter.equals("1")) { 
    message = "The 1"; 
} else if (enter.equals("2")){ 
    message = "The 2"; 
} 

Toast messageToast = Toast.makeText(context, message, duration); 
messageToast.show(); 
+0

你不能使用'=='比較字符串。相反,使用'.equals' – waqaslam 2012-02-23 22:25:10

+0

你當然是對的。 – Matthew 2012-02-23 22:29:01