我需要根据时间在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;
Good morning john
Good evening Hari. I dont get like that.
答案 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
变量