0

Whenever I use java.util.Scanner, after a certain length, it no longer receives text from the user. For example:

Scanner input = new Scanner(System.in);
String saySomething = input.next();

After I type a while, the words get cut off. For example, if the user types "Hello, my name is John", and I print the input, it only gives me something like "Hello," but I want it to print the entire sentence, i.e. "Hello, my name is John".

How do I fix this?

ublec
  • 165
  • 1
  • 14
SEJU
  • 1
  • 3
  • This is not a good idea to take multiple inputs during object generation one by one using a scanner. It is better you take a comma-separated string as an input, and parse it to get your values. – Md. Kawser Habib Mar 07 '21 at 03:34
  • Next time please include your question in the post too, not just the title. – ublec Mar 07 '21 at 04:26
  • you have to press ENTER. like `2233 Myboodk 3 33 MrAuthor` press Enter. – onkar ruikar Mar 07 '21 at 04:26
  • Scanner#next() only reads until the next delimited, which is, by default, a space. – NomadMaker Mar 07 '21 at 07:16
  • I don't know why OP accepted that bad edit. The input is delimited by a comma. That edit removed that vital information and pretends the input should be read line-by-line. – Tom Mar 07 '21 at 13:06

3 Answers3

0

Use input.nextLine() while taking a string as an input. input.next() will stop reading while a white space is encountered.

0

You can use useDelimiter() for this. Take the following example:

Scanner input = new Scanner(System.in).useDelimiter("\\n"); // This keeps the scanner listening until a new line (\n).

Now the input should not get cut off whenever you use input until the user presses enter.

ublec
  • 165
  • 1
  • 14
0

You can try this code :

import java.util.Scanner;
public class StringTest
{
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter any string : ");
        String str = scanner.nextLine();
        System.out.println("Entered string is : " + str);
    }
}