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(' ')); } } 

5 Answers

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();?

this perfectly works fine for me.

System.out.println("one word".indexOf(' ')); 

This is because of Scanner next method. check this

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()

Try

String s = scan.nextLine(); 

as scan.next() gets the next "word" which can't contain spaces.

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!

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy