Tech > JavaCodeSnippets

Java Code Snippets

Alternating Rows

Using exclusive OR operator ^

public class AlternatingRows {

   public static void main(String[] args) {
      int n = 1;
      for (int i=0; i < 10; i++) {
        System.out.println(((n ^= 1) == 1) ? "Odd" : "Even");
      }
   }
}

Using remainder (modulo) operator %

public class AlternatingRows2 {

   public static void main(String[] args) {
      for (int i=0; i < 10; i++) {
        System.out.println((i%2 == 0) ? "Odd" : "Even");
      }
   }
}

-- Frank Dean - 09 Aug 2007

Related Topics: DevelopmentSetup, JavaDateConversion