-2

I need the code to print "Invalid Response" if the user does not enter "yes" or "no", and wish to know the simplest way you can do this. Thank you!

import java.util.Scanner;
public class Closet
{
   public static void main(String[] args)
   {
      Scanner scan = new Scanner(System.in); 
      System.out.println("Welcome to your closet! Let's see what you can wear!");
      System.out.println("Is it cold outside?");
      String cold = scan.nextLine().toUpperCase();
      if (cold.charAt(0) == ('Y'))
      {
         System.out.println("You should wear long sleeves."); 
      }   
      if (cold.charAt(0) == ('N'))
      { 
         System.out.println("You should wear short sleeves.");
      }  
   }
}
Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • 5
    That is some funny looking JavaScript – epascarello Oct 16 '19 at 21:19
  • 1
    so what goes hand in hand with an if statement? – epascarello Oct 16 '19 at 21:20
  • Why are you testing only first character? What if user typed `You will never know!!!`? Compare entire response to what you expect to get. See [How do I compare strings in Java?](https://stackoverflow.com/q/513832) or if you don't want to manually change its case you can use something like `if("yes".equalsIgnoreCase(response)){...}`. – Pshemo Oct 16 '19 at 21:29
  • Take a look at https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html especially part about `else`. – Pshemo Oct 16 '19 at 21:31

1 Answers1

0

You need to change your main method like this:

public static void main(String[] args)
{
    Scanner scan = new Scanner(System.in);
    System.out.println("Welcome to your closet! Let's see what you can wear!");
    System.out.println("Is it cold outside?");
    String cold = scan.nextLine().toUpperCase();
    if (cold.equalsIgnoreCase("yes")) {
        System.out.println("You should wear long sleeves.");
    } else if (cold.equalsIgnoreCase("no")) {
        System.out.println("You should wear short sleeves.");
    } else {
        System.out.println("Invalid response");
    }
}

So, the valid entries are "yes" and "no" and isn't case sensitive (You could send "YES", "Yes", etc)

Villat
  • 1,455
  • 1
  • 16
  • 33