Reputation: 85
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
Reputation: 2455
Try :
if(phrase.equals("hi") || phrase.equals("hello")) {
//rest of your code
}
Upvotes: 0
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