Reputation: 117
There is a space in the string, but when I run program, it returns -1, that means there aren't spaces in the string Here's the code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.next();
System.out.println(s.indexOf(' '));
}
}
Upvotes: 10
Views: 56458
Reputation: 35
Use scan.nextLine()
because scan.next()
will read until it encounters a white space (tab, space, enter) so it finish getting when it see space. You yourself could guess this by printing s, too!
be successful!
Upvotes: 1
Reputation: 8530
this perfectly works fine for me.
System.out.println("one word".indexOf(' '));
This is because of Scanner next method. check this
Upvotes: 6
Reputation: 533492
Try
String s = scan.nextLine();
as scan.next() gets the next "word" which can't contain spaces.
Upvotes: 3
Reputation: 1148
Scanner reads text seperated by whitespace, which can be a line break but also a space character. This is why scan.next() will return a String with no spaces. If you need line breaks instead, use scan.nextLine()
Upvotes: 3
Reputation: 206689
Scanner.next()
returns the next token in the input, and by default, tokens are whitespace separated. i.e. s
is guaranteed not to contain spaces.
Maybe you meant String s = scan.nextLine();
?
Upvotes: 12