猿问

在 main 中调用解决方案类

我试图模仿 Eclipse 中 FizzBuzz 问题的解决方案。已经给出了解决方案类,但我不完全确定如何在 main 中运行它来打印结果。在解决方案中,列表上升到 15 并打印出结果。如果我这样运行,是不是在 main 中为 s 创建了列表?如果是这样,我如何将其打印为列表而不是获取“Solution@7852e922”对象输出?


 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;

     }

 }


月关宝盒
浏览 110回答 2
2回答

萧十郎

在您的main方法中,您只需调用fizzBuzz()新创建的Solution对象的方法并循环遍历结果:&nbsp;public static void main(String[] args) {&nbsp; &nbsp; &nbsp;Solution s = new Solution();&nbsp; &nbsp; &nbsp;List<String> result = s.fizzBuzz(100);&nbsp; &nbsp; &nbsp;for (int n : result) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println(n);&nbsp; &nbsp; &nbsp;}&nbsp;}

慕仙森

你不能运行一个类,你只能运行一个方法。我假设您想运行该类的fizzBuzz(int n)方法Solution。你通过调用它来做到这一点,例如&nbsp;List<String>&nbsp;fizz&nbsp;=&nbsp;s.fizzBuzz(15);
随时随地看视频慕课网APP

相关分类

Java
我要回答