0
Scanner sc = new Scanner(System.in);
String str = sc.next();

System.out.println(str);
Provided input : this is a good school
Obtained Output : this 

Why is the complete string is not printing?

Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
keerthi
  • 11
  • 1

2 Answers2

6

Because next() returns the next token, not complete line.

You can use

String str = sc.nextLine();
Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
2

From the documentation of Scanner.next():

The java.util.Scanner.next() method finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.

https://www.tutorialspoint.com/java/util/scanner_next.htm

If you want to read the entire line it is probably better to use this code:

BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in));
String line=buffer.readLine();

Taken from this answer: https://stackoverflow.com/a/8560432/481528

selalerer
  • 3,766
  • 2
  • 23
  • 33