我刚刚开始学习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;
        }

    }

最佳答案

您可以这样尝试,错过了不到早上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";
}

10-06 02:34