I have this code that takes the user input, the breaks it down into an array using.split() and then adds the only the values that are not" " to a list, normally when comparing lets say integers i would write == or != but how can i write does not equal to using.equals()? Do i write(!array.equals(" ");?
Scanner in = new Scanner(System.in);
String input = in.next();
String[] array = input.split("");
List<String> list = new ArrayList<String>();
for (int a = 0; a < array.length; a++) {
if (array[a].equals(" ")) {
list.add(array[a]);
}
}
4 Answers 4
array[a].equals(" ") returns true or false, if you want to reverse the condition then you need to use ! (not)
For example
if (!array[a].equals(" ")) {
Which reads "if the element in array at position a is NOT equal to " ""
Comments
Yes, you'll use the ! not operator to invert any boolean expression but here you should use trim() as well.
if (!array[a].trim().equals("")) {
This makes sure that if input has one or more spaces it doesn't get added to the List. Another way is to make use of isEmpty() like
if (!array[a].trim().isEmpty()) { // Java 6 and above
Comments
Since array.equals produces a boolean, the ! modifier would invert the result.
Comments
When comparing a string to a literal value, always use the literal value to call .equals() as the literal value is null-safe:
" ".equals(array[a]);
If you're using Java8 you can do what you want really nicely and succinctly using streams:
List<String> notSpaces = Pattern.compile("").splitAsStream(input)
.filter(s->!" ".equals(s))
.collect(Collectors.toList());
You could also be really sneaky and split twice, the first time splitting on space characters:
Pattern splitAll = Pattern.compile("");
List<String> notSpaces = Pattern.compile(" +").splitAsStream(input)
.flatMap(s->splitAll.splitAsStream(s))
.collect(Collectors.toList());
The first split will remove all the spaces from the resulting strings, and the second split will split each remaining string into its component character strings. Not sure which is actually more efficient. The second one might be better if there are a lot of spaces together.
!array[a].equals(" ")and yes.!array[a].equals(" ")should work.