javaarraysstringstoring-data

Java program to take string as user input and store it in array, then print it


I'm sorry if I'm not able to explain the question. When I take user input it prints only the first word of the string. Help me understand what I'm missing, or why is it not working when I take user input.

When I pass the input, "This is Mango", it prints only This.

Instead I want to print it as This is Mango

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.println("Enter the String: ");
    String str= in.next();

    String[] words = str.split("[[ ]*|[//.]]");
    for(int i=0;i<words.length;i++)
        System.out.println(words[i]+" ");

If I give a hard-coded string, it is able to save it in array.

String str = "This is a sample sentence.";
String[] words = str.split("[[ ]*|[//.]]");
for(int i=0;i<words.length;i++)
    System.out.println(words[i]+" ");

When I run the above code, it prints as

This is a sample sentence


Solution

  • Change this line:

    String str = in.next();
    

    to this:

    String str = in.nextLine();
    

    This way, your Scanner object will read the whole line of input.

    If you only use next() it only reads the input until it encounters a space. Meanwhile, nextLine() reads the whole line (so until you escape to the next line when providing input). Also note that if you would like to read other data types you would need to use the corresponding function. For example, to read an integer you should use nextInt().

    Hope this helps!