Leonne
Leonne

Reputation: 85

why is my program ignoring my if else statement?

My program should output ‘What is your name?’ only if “hi” and “hello” are typed, but it still outputs ‘What is your name?’ even if I type a number or a single character… I’m so frustrated. Can someone help me out with this? I think it has something to do with the !phrase.equals statement…

import java.util.Scanner;
public class prog2 {


public static void main(String[] args)throws Exception {



    String phrase;
    String name;
    char Letter;

    Scanner keyboard = new Scanner(System.in);
    System.out.print("Type a phrase: ");

    phrase = keyboard.nextLine();

    if(!phrase.equals("hi") || !phrase.equals("hello")){   
    System.out.print("What is your name?");               

    Scanner keyboard1 = new Scanner(System.in);

    name = keyboard1.nextLine();

    System.out.print("Your name is" +name);
    }else{

        Scanner keyboard2 = new Scanner(System.in);
        System.out.print("Type a Letter: ");

        Letter = (char) System.in.read();
        System.in.read();

        System.out.print("Your letter is "+ Letter);
    }


}

Upvotes: 0

Views: 3186

Answers (3)

Nishant Lakhara
Nishant Lakhara

Reputation: 2455

Try :

if(phrase.equals("hi") || phrase.equals("hello")) {
//rest of your code
}

Upvotes: 0

Daniel
Daniel

Reputation: 36720

You condition !phrase.equals("hi") || !phrase.equals("hello") is always true.

If the word is hi, it's false or true; if the word is hello, it's true or false. Otherwise its true or true. You did not describe the intended behaviour, thus I can't tell what is correct.

Upvotes: 3

Maroun
Maroun

Reputation: 96016

It's not doing what you wanted to do. Check De Morgan laws.

You probably want to do:

if(!(phrase.equals("hi") || phrase.equals("hello")))

Which is not like what you did because if(!a || !b) is not like if(!(a || b)).

Upvotes: 0

Related Questions