Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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

like image 678
chandrakanth B Avatar asked Sep 15 '16 15:09

chandrakanth B


People also ask

Does Scanner read spaces in Java?

It is a method of Scanner class in java. next() method can read input till the space (i.e. it will print words till the space and whenever it gets space it stops working and give the result till the space).


1 Answers

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

    }
}
like image 138
Rajesh Avatar answered Sep 20 '22 11:09

Rajesh