I was taking a shot at the FizzBuzz problem and decided to use an array to store the first 15 results in array and then iterate through it. But the variable stored in array is not updating its value if updated later in the loop
import java.util.Scanner; public class FizzBuzz { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc= new Scanner(System.in); System.out.println("Enter the number"); int Num= sc.nextInt(); String F= "Fizz"; String B= "Buzz"; String FB= "FizzBuzz"; String I=""; String arr[]= {FB, I, I, F, I, B, I, I, I, F, B, I, F, I, I}; for (int j = 1; j <= Num; j++) { I = Integer.toString(j); System.out.println(arr[j%15]); } } }
The variable I does not change its value in the for-loop. It just prints empty spaces in the result for the I variable. HeLp !
P.S: Is this a good implementation with respect to naive soln?
Advertisement
Answer
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the number"); int num = sc.nextInt(); String f = "Fizz"; String b = "Buzz"; String fb = "FizzBuzz"; String i = ""; String[] arr = {fb, i, i, f, i, b, i, i, i, f, b, i, f, i, i}; String indexValue; for (int j = 1; j <= num; j++) { indexValue = arr[j % 15]; System.out.println(indexValue.equals(i) ? j : indexValue); } } }