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:
Input :Enter Your name:Chandu Aakash
Output:chandu Aakash
Input: Enter Your name: (Space..)Chandu Aakash(Space..)
Output: (space.. )chandu Aakash(Space..)
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).
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With