Search code examples
javaclassfizzbuzz

Calling solution class in main


I'm trying to mimic a solution to the FizzBuzz problem in Eclipse. The solution class has been given, but I'm not entirely sure on how to run it in main to print the result. In the solution, the list goes up to 15 and prints out the results. If I run it like this, is the list created for s in main? and if so, how do I print it as a list instead of getting "Solution@7852e922" object output?

 public class FizzBuzzMain {

     public static void main(String[] args) {
     Solution s = new Solution();
     System.out.println(s);

     }
 }


  import java.util.ArrayList;
  import java.util.List;

 public class Solution {
     public List<String> fizzBuzz(int n) {
         List<String> list = new ArrayList<>();
         for(int i = 1;i<=n;i++){
             if(i%3==0&&i%5==0){
                 list.add("FizzBuzz");
             }
             else if (i%3==0) list.add("Fizz");
             else if(i%5==0) list.add("Buzz");
             else{
                 list.add(Integer.toString(i));
             }
         }
         return list;
     }
 }

Solution

  • In your main method you need to just call the fizzBuzz() method of the newly created Solution object and loop through the results:

     public static void main(String[] args) {
         Solution s = new Solution();
         List<String> result = s.fizzBuzz(100);
         for (int n : result) {
             System.out.println(n);
         }
     }