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

Pillager225 picture Pillager225 · Oct 16, 2011 · Viewed 211.5k times · Source

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.

Answer

Eng.Fouad picture Eng.Fouad · Oct 16, 2011

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;
    }
 }