Phil Nalivayko Phil Nalivayko - 7 days ago 6
Java Question

indexOf for space in string

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

}

Mat Mat
Answer

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

Comments