IndexOf for space in line

There is a space in the line, but when I run the program, it returns -1, which means that there are no spaces in the line. Here is 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(' ')); } } 
+6
source share
5 answers

Scanner.next() returns the next token in the input file, and by default, tokens are separated by spaces. those. s guaranteed to be blank.

Perhaps you meant String s = scan.nextLine(); ?

+7
source

This works great for me.

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

This is because of the following Scanner method. check this

+4
source

The scanner reads text separated by spaces, which can be a line break, as well as a space character. This is why scan.next () will return a string without spaces. If you need line breaks, use scan.nextLine ()

+3
source

Try

 String s = scan.nextLine(); 

how scan.next () gets the next "word" that cannot contain spaces.

+3
source

Use scan.nextLine() because scan.next() will read until it encounters a space (tab, space, input) so that it finishes receiving when it sees a space. You yourself could have guessed it by printing too! to be successful!

+1
source

Source: https://habr.com/ru/post/912121/


All Articles