如何根据时间

时间:2017-12-11 06:27:13

标签: java android

我需要根据时间在android中显示一条消息。我的编码如下:

package com.example.lenovo.timegreetfriends;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
        Button greetButton;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            greetButton = (Button) findViewById(R.id.greetButton);

            greetButton.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            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);
            Date date = new Date();
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            int hour = cal.get(Calendar.HOUR_OF_DAY);
            int min = date.getMinutes();
            String friendName = editFriendName.getText().toString();

            switch (v.getId()) {
                case R.id.greetButton:
                    if(hours>=1 || hours<=12) {
                        Toast.makeText(this, "Good Morning", Toast.LENGTH_SHORT).show();
                    } else if(hours>=12 || hours<=16) {
                        Toast.makeText(this, "Good Afternoon", Toast.LENGTH_SHORT).show();
                    } else if(hours>=16 || hours<=21) {
                        Toast.makeText(this, "Good Evening", Toast.LENGTH_SHORT).show();
                    } else if(hours>=21 || hours<=24) {
                        Toast.makeText(this, "Good Night", Toast.LENGTH_SHORT).show();
                    }
                    textMessage.setText("Good Day "+friendName+"!");
                    break;
                default:
                    break;
  • 案例:1 如果用户输入文字(比如约翰)并在上午9点按一个按钮。
    • 输出 Good morning john
  • 案例2:如果用户输入文字(例如hari)并在下午3点按下按钮
    • 输出 Good evening Hari. I dont get like that.

1 个答案:

答案 0 :(得分:2)

对于所有条件,您需要使用&&代替||

hours>=1 && hours<=12

否则16&gt; = 1所以第一种情况将被执行,控制权不会再进一步​​

||:表示OR条件,需要任何一个条件true才能继续

&&:表示AND条件,要求每个条件true继续

并且还将上限和下限正确定义为

 if(hours>=1 && hours<=12) {} 
 else if(hours>12 && hours<=16) {} 
 //          ^^^ 

并且@Dileep Patel提到使用包含hour而不是hours的值的适当变量,尽管它没有定义hours变量