-2

I have a array of chars called votacoes. And when I do:

for (int i = 0; i < nDeputados; i++) {
    System.out.println(votacoes[i]);
}

the output is:

S
A

S
S
S
N
A

As you can see you there is a blank char in index 2.

To print everything except the blank char what is the condition in the following if?

for (int i = 0; i < nDeputados; i++) {
    if(???????????){
        System.out.println(votacoes[i]);
    }
}

5 Answers5

0
for (int i = 0; i < nDeputados; i++) {
    if(!String.valueOf(votacoes[i]).matches("\\s")){
        System.out.println(votacoes[i]);
    }
}

This will skip up any type of space characters and print out a continuous output.

Jaskaranbir Singh
  • 2,034
  • 3
  • 17
  • 33
  • 1
    If you are downvoting you should also provide a reason for that. – Jaskaranbir Singh Nov 28 '15 at 18:33
  • Now that you have edited your answer to use char[] instead of only strings, this line doesn't make sense: `if(!String.valueOf(votacoes[i]).equals(""))` Since votacoes[i] is a char, it will always have length of 1 and so will never be "". By the way, you should call String.isEmpty() rather than equals(""). – Klitos Kyriacou Nov 28 '15 at 19:58
  • Yup, you are right. Code "Trimmed". And I use `""` because you dont have to check for `null` in that. So it does work fine for me in a lot of situations... but yeah, `.equals()` is cleaner and actually does a good `null` check too. – Jaskaranbir Singh Nov 28 '15 at 20:09
0

You can use String isBlank method:

for (int i = 0; i < nDeputados; i++) {
    if(!StringUtils.isBlank(votacoes[i])){
    System.out.println(votacoes[i]);
    }
}

Look here: http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#isBlank%28java.lang.String%29

m.aibin
  • 3,528
  • 4
  • 28
  • 47
-1
for (int i = 0; i < nDeputados; i++)
{
 if(Character.isAlphabetic(votacoes[i]))

      System.out.println(votacoes[i]);
}

The Character.isAlphabetic() method returns true if the value passed is an alphabet. Hope this helps :)

-1

use this code

      for (int k = 0; k < votacoes.length; k++) {
        if (votacoes[k]==' ') {
            k++;
        }
        System.out.println(votacoes[k]);

hope it would work for you..

  • 1
    Which gives a nice `ArrayIndexOutOfBoundsException` if the last character is a space. – Tunaki Nov 28 '15 at 18:46
  • @Tunaki Ohh that's right, it was just slipped from my mind, thanks `Character.isAlphabetic(array[k])` would be perfect here as I know – Shivam Jaiswal Nov 29 '15 at 10:42
-1
char[] votacoes = {'S','A',' ','S','S','S','N','A'};
for (char b : votacoes) {
    if(!Character.isWhitespace(b)) {
        System.out.println(b);
    }
}
Sruit A.Suk
  • 7,073
  • 7
  • 61
  • 71
Madushan Perera
  • 2,568
  • 2
  • 17
  • 36