How to take input as String with spaces in java using scanner

Your code work fine. I just add little modification:

package practise;

import java.util.Scanner;

public class scanccls {

    public static void main(String[] args) {

        System.out.println("Enter your name:"); 
        Scanner scan = new Scanner(System.in);
        String name="";

        name+=scan.nextLine();
        scan.close();

        System.out.println("Your name is :"+name); 

    }

}

/@esprittn solution didn't work./

my solution:

while(scan.hasNext()){
name+=scan.nextLine();
}

import java.util.*;
public class Str{
    public static void main(String[] args) throws IOException
    {
        Scanner scan = new Scanner(System.in);
        int i = scan.nextInt();
        double d = scan.nextDouble();
        String s=" ";
        s= scan.nextLine();
        s+=scan.nextLine();
        scan.close();

        System.out.println("String: "+s);
        System.out.println("Double: "+d);
        System.out.println("Int: "+i);
    }
}

One can use the delimiter function to segregate your input as shown below.

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in).useDelimiter("\n");
        String input = scanner.next();
        System.out.println(input);
        scanner.close();

    }
}

Tags:

Java