How do you check if a string is not equal to an object or other string value in java?

213,115

Solution 1

Change your code to:

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 = "PM"; // <--
    } else {
        TimeOfDayStringQ = "AM"; // <--
    }
            Hours = 1;
    }
 }

Solution 2

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)

Solution 3

Change your || to && so it will only exit if the answer is NEITHER "AM" nor "PM".

Share:
213,115
Pillager225
Author by

Pillager225

Updated on July 09, 2022

Comments

  • Pillager225
    Pillager225 almost 2 years

    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.

  • Pillager225
    Pillager225 over 12 years
    Thank you very much. I am kind of new to java and that is probably why I made such a simple error. Thank you very much.