Frank Drebin Frank Drebin - 3 months ago 8
Java Question

Java or Eclipse 'fails' on Whitespaces(?)

After many questions asked by other users this is my first one for which I was not able to find a fitting answer.

However, the problem sounds weird and actually is:
I have had more than one situation in which whitespaces were part of the problem and common solutions to be find on stackoverflow or elsewhere did not help me.

First I wanted to split a String on whitespaces. Should be something like

String[] str = input.split(" ")


But neither
(" ")
nor any regex like
("\\s+")
worked for me. Not really a problem at all. I just chose a different character to split on. :)

Now I'm trying to clean up a string by removing all whitespaces. Common solution to find is

String str = input.replaceAll(" ", "")


I tried to use the regex again and also
(" *", "")
to prevent exception if the string inludes no whitespaces. Again, none of these worked for me.

Now I'm asking myself whether this is a kinda weird problem on my Java/Eclipse plattform or if I'm doing something basically wrong. Technically I do not think so, because all code above works fine with any other character to split/clean on.

Hope to have made myself understood.

Regards Drebin

edit to make it clearer:

I'm caring just about the "replacing" right now.

My code does accept a combination of values and names separated by comma and series of these separated by semicolon, e.g.:


1,abc;2,def;3,ghi


this gets two time splitted, first on comma, then on semicolon. Works fine.

Now I want to clear such an input by removing all whitespaces to proceed as explained above. Therefore I use, as already explained,
String.replaceAll(" ", "")
, but it does NOT work. Instead, everything in the string after the FIRST whitespace, no matter where it is, gets removed and is lost. E.g. the String from above would change to


1,abc;


if there is whitespace after the first semicolon.

Hope this part of code works for you:

import java.util.*;

public class Main {

public static void main(String[] args) {

// some info output

Scanner scan = new Scanner(System.in);
String input;

System.out.println("\n wait for input ...");
input = scan.next();

if(input.equals("info"))
{
// special case for information
}
else if(input.equals("end"))
{
scan.close();
System.exit(0);
}
else
{
// here is the problem:
String input2 = input.replaceAll(" ", "");

System.out.println("DEBUG: "+input2);

// further code for cleared Strings
}
}
}


I really do not know how to make it even clearer now ...

Answer

The next method of Scanner returns the next token - with the default delimiters that will be a single word, not the complete line.

Use the nextLine method if you want to get the complete line.