简体   繁体   中英

How to skip whitespaces and take input in Single line using Scanner

I need to take input in a single line of String which is a combination of String and integers.

I have tried to take the input like this

Scanner in = new Scanner(System.in);
String stringWithoutSpaces=in.nextLine();

But, scanner reads only the first character.

Input String:A 10,B 10,C 10,D 10
Required String:A10,B10,C10,D10 

I need this input in a one single line using scanner class.

From what I understand, you are trying to receive the string from the user without storing all the white spaces. If your goal is to remove all the white spaces from the user input string, you can use replaceAll .

Code:

Scanner in = new Scanner(System.in);
System.out.print("Enter input: ");
String input = in.nextLine();
String noWhiteSpaces = input.replaceAll(" ", "");
System.out.println(noWhiteSpaces);

Console:

Enter input: A 10,B 10,C 10,D 10
A10,B10,C10,D10
    import java.util.*;

public class Solution {

    public static void main(String args[]) {
        System.out.println("Hello world");
        Scanner scanner=new Scanner(System.in);
        String aItems = scanner.nextLine();
        System.out.println(aItems);

    }
}

This is working fine. I have Provided same input as mentioned by you and it is taking it as one string.Share your complete code or match from this one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM