简体   繁体   中英

Looping through variables in JAVA

It is possible to loop through variables of primitive type char (using say a foreach loop)?

I have three characters

char char1 = 'A';
char charTest = 'P';
char character = 'R';

Currently I have a long list of "if" statements applied to char1:

if (char1 == 'A')
doSomething;
else if (char1 == 'K')
doSomethingElse;
else if (charPrev == 'G')
    doSomethingAgain;
else
    doSomethingYetAgain;

However, I will be applying the same set of "if" statements to other character variables (in this example charTest and character).

What is a simply way to accomplish this? Thanks for any input!

The easiest way to do this is to put your variables into an array and loop through them. Something like

char[] charArray = {char1, charTest, character};

// Essentially this says, for each char in charArray
for (char character : charArray) {
    if (character == 'A')
        // Do Something
    else if (character == 'K')
        // Do Something
    else
        // Do Something
}

You could pass your characters off to a method that run a switch.

  public static void main(String[] args) {
    char char1 = 'A';
    char char2 = 'B';
    doStuff(char1);
    doStuff(char2);
  }

  public static void doStuff (char a)
  {
      switch (a) {
        case 'A':
          doSomething();
          break;
        case 'B':
          doSomethingElse();
          break;
        default:
          dontDoAnything();
          break;
      }
      return;
  } 

To create array of characters in Java:

char[] characters = {'a', 'b', 'c'};

To loop over arrays of char using ' for each ' terms and because you have ' long list of if ', I suggest you to use switch:

for(char character : characters){
    switch(character){
          case 'a' : 
             //do something 
             break;
          case 'b' :
             //do something 
             break;
           ..
           ..
    }
}

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