import java.util.*;
public class TimeFormat {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter your Name.");
String name=sc.nextLine();
System.out.println("Enter the time format either it is AM or PM");
String format=sc.nextLine();
System.out.println("Enter hour time.");
int hrs=sc.nextInt();
System.out.print(":");
int min=sc.nextInt();
if(format.equals("PM")&&format.equals("pm")) {
if(hrs>=12&&hrs<=5&&min>1) {
System.out.println("Good afternoon "+name);
}
else if(hrs>=5&&hrs<=8) {
System.out.println("Good evening "+name);
}
else if(hrs<=12&&hrs>=8&&min<59) {
System.out.println("Goodnight "+name);
}
}
else {
System.out.println("Good Morning "+name);
}
}
}
请命令行始终跳过if条件。我是java新手,请帮帮我。好的但是如果声明已经创造了问题那么我认为。请问我该如何改进此代码。
答案 0 :(得分:5)
format
永远不能等于“pm”和(&&
)“PM”。使用OR(||
),或者更好的是,使用:
if (format.equalsIgnoreCase("PM"))
将涵盖“PM”,“pm”,“Pm”和“pM”。
答案 1 :(得分:1)
您需要检查格式是否为&#34; PM&#34; 或&#34; pm&#34;。您正在查看和
if(format.equals("PM")||format.equals("pm"))
答案 2 :(得分:0)
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your Name.");
String name = sc.nextLine();
System.out.println("Enter the time format either it is AM or PM");
String format = sc.nextLine();
System.out.println("Enter hour time.");
int hrs = sc.nextInt();
System.out.print(":");
int min = sc.nextInt();
if (format.equals("PM") || format.equals("AM")) {
if (hrs >= 12 && hrs <= 5 && min > 1) {
System.out.println("Good afternoon " + name);
} else if (hrs >= 5 && hrs <= 8) {
System.out.println("Good evening " + name);
} else if (hrs <= 12 && hrs >= 8 && min < 59) {
System.out.println("Goodnight " + name);
}
} else {
System.out.println("Good Morning " + name);
}
}
你有一个&amp;&amp; (AND)条件,你需要一个|| (或)条件,+你的选择是AM或PM,而不是PM或pm尝试从那里