Skip to content
Advertisement

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

I need to read spaces (present before string and after String) given as input using Scanner Note : if there is no spaces given in input it should not add space in output

Please find the below code:

package practise;

import java.util.Scanner;

public class scanccls {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner scan = new Scanner(System.in);
         String name= scan.nextLine();
        name+=scan.nextLine();
         scan.close();

        System.out.println("Enter your name"+name); 

    }

}

I am expecting output like:

  1. Input :Enter Your name:Chandu Aakash
    Output:chandu Aakash

  2. Input: Enter Your name: (Space..)Chandu Aakash(Space..)
    Output: (space.. )chandu Aakash(Space..)

Advertisement

Answer

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); 

    }

}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement