vendredi 25 mars 2016

Java, nested if, if/else statements to add words

I'm doing an assignment where I need to do a multitude of things that require nested if/else. Print the first 50 Fibonacci numbers, but:

  • if the number is a multiple of 3 - print "Cheese"
  • if the number is a multiple of 5 - print "Cake"
  • if the number is a multiple of 7 - print "Factory"
  • if the number is a multiple of 3 & 5 - print "CheeseCake"
  • if the number is a multiple of 3 & 7 - print "CheeseFactory"
  • if the number is a multiple of 5 & 7 - print "CakeFactory"
  • if the number is a multiple of 3 & 5 & 7 - print "CheeseCakeFactory"
  • if the number is a multiple of 2 - print "Blah"

At this point I'm repeating the conditions, and I'm sure there's a cleaner way to do it:

package Assignment1;

public class CheeseCakeFactory_163003984 {

    public static void main(String[] args) {
        long numberOne = 0;
        long numberTwo = 1;
        long sum = 0;
        int counter = 0;

        String word1 = "Cheese";
        String word2 = "Cake";
        String word3 = "Factory";

        while (counter <= 50) {
            sum = numberOne + numberTwo;
            numberOne = numberTwo;
            numberTwo = sum;
            counter++;

            if (sum % 3 == 0) {
                System.out.print(word1 + ", ");
            } else if (sum % 5 == 0) {
                if (sum % 3 == 0) {
                    System.out.print(word1 + word2 + ", ");
                } else if (sum % 3 == 0) {
                    if (sum % 5 == 0) {
                        if (sum % 7 == 0) {
                            System.out.print(word1 + word2 + word3 + ", ");
                        }
                    }
                    if (sum % 7 == 0) {
                        System.out.print(word1 + word2 + word3 + ", ");
                    } else if (sum % 2 == 0) {
                        System.out.print("Blah, ");
                    } else {
                        System.out.print(sum);

                        if (counter % 10 == 0) {
                            System.out.print("\n");
                        } else {
                            System.out.print(", ");
                        }
                    }
                }
            }
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire