I have been trying to make a clock that the user can set. I wanted the user to be asked questions and they answer in words like yes or no. I have done it for things that don't change using this code such as whether or not the user wants seconds to be displayed or not, but it doesn't work as well when I want the string to change, say from AM to PM when hours exceeds 12. Here is what I am using:
System.out.println("AM or PM?");
Scanner TimeOfDayQ = new Scanner(System.in);
TimeOfDayStringQ = TimeOfDayQ.next();
if(!TimeOfDayStringQ.equals("AM") || !TimeOfDayStringQ.equals("PM")) {
System.out.println("Sorry, incorrect input.");
System.exit(1);
}
...
if(Hours == 13){
if (TimeOfDayStringQ.equals("AM")) {
TimeOfDayStringQ.equals("PM");
} else {
TimeOfDayStringQ.equals("AM");
}
Hours = 1;
}
}
Every time I enter anything when it prompts me, whether I put AM, PM, or other wise, it gives me the error I wrote and then exits. When I remove the section of code that terminates the program with the error it will not change the string from AM to PM when hours equals 13. Thank you for your help, it is much appreciated.
This question is related to
java
string
time
if-statement
user-input
you'll want to use && to see that it is not equal to "AM" AND not equal to "PM"
if(!TimeOfDayStringQ.equals("AM") && !TimeOfDayStringQ.equals("PM")) {
System.out.println("Sorry, incorrect input.");
System.exit(1);
}
to be clear you can also do
if(!(TimeOfDayStringQ.equals("AM") || TimeOfDayStringQ.equals("PM"))){
System.out.println("Sorry, incorrect input.");
System.exit(1);
}
to have the not (one or the other)
phrase in the code (remember the (silent) brackets)
Change your || to && so it will only exit if the answer is NEITHER "AM" nor "PM".
Source: Stackoverflow.com