Well you can use java.util.Scanner.next()
method.
see the documentation
next()
Finds and returns the next complete token from this scanner.
Scanner sc = new Scanner(System.in);
String str = sc.next();
System.out.println(str);
There are also plenty of other options available if you’re willing to switch from Scanner
class. One possible option is using java.io.BufferedReader
class.
BufferedReader bi = new BufferedReader(new InputStreamReader(System.in));
String str = bi.readLine();
System.out.println(str);
solved Java String Containing Spaces