我刚开始学习Android Studio,这是我的第一个项目(Hello World Application)。该项目是创建一个应用程序,我必须根据时间返回问候语。我面临的问题是,当我输入名称时,它显示“null(name)”而不是相应的问候语。 我不明白为什么会这样。我只需要在正确的方向上提示或轻推。
以下是模拟器上的结果:(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;
}
}
答案 0 :(得分:2)
你可以尝试这样,你错过了不到早上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";
}