-1

i have a function java where i need print multiples of 2 numbers 3 and 5 i do this function. but it dont very clean

for(int i = 1; i <= 100; i++){
    if (i % 3 == 0 && i % 5 == 0) {
        System.out.println("im multiple of 3 and 5");
    }
    else if (i % 3 == 0) {
        System.out.println("im multiple of 3");
    }
    else if (i % 5 == 0) {
        System.out.println("im multiple of 5");
    }
    else{
        System.out.println(" i dont multiple");
    }
}

how should i to do for a code more clear

  • 2
    Really? You're asking SO for advice on an obvious fizzbuzz? That said, it's also unclear what exactly you're asking us for help with? – neminem Jul 21 '15 at 17:51
  • well i just doing any exercises and i read about very if and else nested dont is a code clean, just remenber now and wanted see how is the better form for make a code more clean, i know there is say in book refatoring code – Ricardo Patrick Jul 21 '15 at 17:54
  • 1
    This is also offtopic given the code works. This should be cleaned up, and moved to Code Review. – Carcigenicate Jul 21 '15 at 18:05
  • possible duplicate of [How to reduce if statements](http://stackoverflow.com/questions/16669753/how-to-reduce-if-statements) – Codermonk Jul 21 '15 at 19:06

3 Answers3

0

This one is classical FizzBuzz problem. Below is one way to write neat code for the same. You can modify the same to fit your problem statement.

public class Fizzbuzz {
    public static void main(String[] args) {
         for (int i = 1; i <= 100; i++) {
            String output = "";
            output += (i % 3) == 0 ? "Fizz" : "";
            output += (i % 5) == 0 ? "Buzz" : "";
            System.out.println(output.isEmpty() ? i : output);
        }
    }
}

Hope that helps.

digidude
  • 289
  • 1
  • 8
0

You could refactor your code (extract methods).Or you may take advantage of of object-oriented programming .your code is simple you may not take advantage of using a design design pattern.

0
String mul2="",mul3="",mulof3and5="";
for(int i = 1; i <= 100; i++){
mul2+=i*2;
mul3+=i*3;
mulof3and5+=i*6;
}
System.out.println(mul2);
System.out.println(mul3);
System.out.println(mulof3and5);
Jishnu Prathap
  • 1,955
  • 2
  • 21
  • 37