2017-08-07 23 views
-1

的問候語我剛開始學習Android Studio,這是我的第一個項目(Hello World Application)。該項目將創建一個應用程序,我必須根據一天中的時間返回問候語。我面臨的問題是,當我輸入名稱時,顯示「空(姓名)」而不是適當的問候語。 我不明白爲什麼會發生這種情況。我只需要在正確的方向提示或微調。根據一天中的時間(Android)

這裏是在模擬器上的結果:(https://prnt.sc/g5lc7e

這裏是我的按鈕按下事件代碼:

@Override 
    public void onClick(View v) { 

     // get a reference to the TextView on the UI 
     TextView textMessage = (TextView) findViewById(R.id.textMessage); 

     //get a reference to the EditText so that we can read in the value typed 
     // by the user 
     EditText editFriendName = (EditText) findViewById(R.id.editFriendName); 

     // get the name of the friend typed in by the user in the EditText field 
     String friendName = editFriendName.getText().toString(); 

     //Get the time of day 
     Date date = new Date(); 
     Calendar cal = Calendar.getInstance(); 
     cal.setTime(date); 
     int hour = cal.get(Calendar.HOUR_OF_DAY); 

     //Set greeting 
     String greeting = null; 
     if(hour>=6 && hour<12){ 
      greeting = "Good Morning"; 
     } else if(hour>= 12 && hour < 17){ 
      greeting = "Good Afternoon"; 
     } else if(hour >= 17 && hour < 21){ 
      greeting = "Good Evening"; 
     } else if(hour >= 21 && hour < 24){ 
      greeting = "Good Night"; 
     } 

     //Change string displayed by TextView 
     switch (v.getId()) { 

     case R.id.greetButton: 

     //set the string being displayed by the TextView to the greeting 
     //message for the friend 
     textMessage.setText(greeting + " " + friendName + "!"); 

     break; 

     default: 
      break; 
     } 

    } 
+2

當小時<6時,你有什麼問候? – user3486184

+0

@ user3486184表示爲所有其他小時添加'else'語句或添加一個else if(小於6)'。另外,你不需要'cal.setTime(date)',因爲一旦你調用[Calendar.getInstance()](https://developer.android.com/reference/java/util/Calendar.html#getInstance())它會將您的日曆初始化爲當前時間。 – ArtiomLK

回答

1

你可以嘗試這樣,你錯過了不到6點。

if(hour>= 12 && hour < 17){ 
    greeting = "Good Afternoon"; 
} else if(hour >= 17 && hour < 21){ 
    greeting = "Good Evening"; 
} else if(hour >= 21 && hour < 24){ 
    greeting = "Good Night"; 
} else { 
    greeting = "Good Morning"; 
} 
+0

它的工作!非常感謝 沒有意識到我錯過了一個條件。 –

相關問題