0

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]);
        }
    }
7
  • 1
    What happened when you tried it? Commented Feb 20, 2015 at 2:21
  • it didn't do anything, it added everything to the list even the spaces Commented Feb 20, 2015 at 2:21
  • I think you meant !array[a].equals(" ") and yes. Commented Feb 20, 2015 at 2:21
  • you are right. !array[a].equals(" ") should work. Commented Feb 20, 2015 at 2:21
  • Thank you, and can i get an explanation on the down-vote, please? Commented Feb 20, 2015 at 2:26

4 Answers 4

3

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 " ""

Sign up to request clarification or add additional context in comments.

Comments

1

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

0

Since array.equals produces a boolean, the ! modifier would invert the result.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.