0

I have a comp sci project:

Prompt the user to enter a word.

  1. If the word is “Neil,” then ask the user to enter a letter. If the letter is a or b, display “Peart.” If it’s another letter, display “Xanadu.”
  2. If the word is “Geddy,” then ask the user to enter a number. If the number is odd and divisible by 9, display “Lee.” If the number is negative or equals 2012, display “YYZ.”

I typed the code for this and everything works except one thing. After I write Neil and it asks me to write a letter, if I type a or b it doesn't output Peart it outputs Xanadu.

 import java.util.Scanner;
 public class Rush
 {
     public static void main()
     {
       Scanner myReader = new Scanner (System.in);
       System.out.print("Enter a word:" );
       String word = myReader.nextLine();

       if (word.equals ("Neil"))
       {
           System.out.print("Enter a letter: ");
           String letter = myReader.nextLine();
           if  (letter == "A" || letter == "a" || letter == "B" || letter == "b")
           {
             System.out.println("Peart");            
           }
           else 
           {
             System.out.println("Xanadu");  
           }
       }
       if (word.equals ("Geddy"))
       {
           System.out.print("Enter a number: ");
           int number = myReader.nextInt();
           if (number % 2 != 0 && number % 9 == 0)
           {
              System.out.println("Lee"); 
           }
           if (number < 0 || number == 2012)
           {
               System.out.println("YYZ");
           }
       }

    }
 }
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Selinnxox
  • 45
  • 1
  • 7
  • 4
    `letter == "A"`? No. You're doing it right in part of your code, `if (word.equals ("Neil"))`, why are you doing it wrong here? – Hovercraft Full Of Eels Oct 19 '15 at 20:24
  • 1
    You're comparing strings using the equality operator `==`. That will check if they are the same object in memory (they are not). Use `"string".equals("string")` to check for equality between strings. – Luke Melaia Oct 19 '15 at 20:25
  • If you want a letter you can follow your `nextLine()` call by `.charAt(0)`. This will give you a character that you can compare with `==`. – Alexis C. Oct 19 '15 at 20:26
  • Oh Ok so if I do if (letter.equals ( "A" ) || letter.equals ("a") || letter.equals ("B") || letter.equals ("b")) it should work – Selinnxox Oct 19 '15 at 20:29
  • Myself, I'd either use a char as noted by @AlexisC or use `equalsIgnoreCase(...)` since then I'd need only two of these method calls rather than four. – Hovercraft Full Of Eels Oct 19 '15 at 20:34

0 Answers0