-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;
}
}
当小时<6时,你有什么问候? – user3486184
@ user3486184表示为所有其他小时添加'else'语句或添加一个else if(小于6)'。另外,你不需要'cal.setTime(date)',因为一旦你调用[Calendar.getInstance()](https://developer.android.com/reference/java/util/Calendar.html#getInstance())它会将您的日历初始化为当前时间。 – ArtiomLK