Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

string

space

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?

like image 969
user1687772 Avatar asked Sep 21 '12 04:09

user1687772


2 Answers

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.

like image 32
Osiris Avatar answered Sep 28 '22 01:09

Osiris


I found a very weird thing in Java today, so it goes like -

If you are inputting more than 1 thing from the user, say

Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
String s = sc.nextLine();

System.out.println(i);
System.out.println(d);
System.out.println(s);

So, it might look like if we run this program, it will ask for these 3 inputs and say our input values are 10, 2.5, "Welcome to java" The program should print these 3 values as it is, as we have used nextLine() so it shouldn't ignore the text after spaces that we have entered in our variable s

But, the output that you will get is -

10
2.5

And that's it, it doesn't even prompt for the String input. Now I was reading about it and to be very honest there are still some gaps in my understanding, all I could figure out was after taking the int input and then the double input when we press enter, it considers that as the prompt and ignores the nextLine().

So changing my code to something like this -

Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
sc.nextLine();
String s = sc.nextLine();

System.out.println(i);
System.out.println(d);
System.out.println(s);

does the job perfectly, so it is related to something like "\n" being stored in the keyboard buffer in the previous example which we can bypass using this.

Please if anybody knows help me with an explanation for this.

like image 189
Shubham Arya Avatar answered Sep 28 '22 00:09

Shubham Arya