How do I make Java register a string input with spaces?

user1687772 picture user1687772 · Sep 21, 2012 · Viewed 110.7k times · Source

Here is my code:

public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
  String question;
  question = in.next();

  if (question.equalsIgnoreCase("howdoyoulikeschool?") )
    /* it seems strings do not allow for spaces */
    System.out.println("CLOSED!!");
  else
    System.out.println("Que?");

When I try to write "how do you like school?" the answer is always "Que?" but it works fine as "howdoyoulikeschool?"

Should I define the input as something other than String?

Answer

Osiris picture Osiris · Sep 21, 2012

in.next() will return space-delimited strings. Use in.nextLine() if you want to read the whole line. After reading the string, use question = question.replaceAll("\\s","") to remove spaces.