Hello,
I was trying to write a program that checks if any of the numbers that the user inputs are divisible by 3 5 or both. If the number is divisible by 3 it prints out "Fizz", if divisible by 5 then "Buzz" and lastly "FizzBuzz" for both. The program should also print out the other numbers anyway, which are not divisible by either 3 or 5.
E.g. input : 15
Output:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
My code is below and I have attached a picture of the current output. Why is it like this? How do I make it work the way I want?
P.S. The first bit of code which I have enclosed between /* */ is another solution of the problem by another person. I do not understand it, however, hence I tried doing it on my own! If somebody would also like to explain how it works to me I would be more than grateful!
public class ArrayExample { public static void main(String args[]) { /*String words[] = new String[Integer.parseInt(args[0])]; for(int i = 0;i < words.length;++i) { words[i] = ""+(i+1); } for(int i = 2;i < words.length;i += 3) { words[i] = "Fizz"; } for(int i = 4;i < words.length;i += 5) { words[i] = "Buzz"; } for(int i = 14;i < words.length;i += 15) { words[i] = "FizzBuzz"; } for(int i = 0;i < words.length;++i) { System.out.println(words[i]); }*/ for (int i=0; i<args.length; i++) //MY OWN SOLUTION BEGINS { for (int j=0; j<Integer.parseInt(args[i]); j++) { if (Integer.parseInt(args[i])%3==0) { System.out.println("Fizz"); } if (Integer.parseInt(args[i])%5==0) { System.out.println("Buzz"); } if (Integer.parseInt(args[i])%15==0) { System.out.println("FizzBuzz"); } } System.out.println(args[i]); } } }
Currently the program prints out this:
ArrayExample.jpg