0

I am finding it so hard to just print my fizzBuzz method out without having to make it static.

In the code below when I first tried to print out my fizzBuzz method, System.out.println(fizzBuzz(6,10));, I got an error and it would not let me do this. I had to make it static and then add Arrays.toString to my System.out.println(); in order for me to review my answer in the console.

I want to be able to print a non-static method in my main but can not seem to do so.

import java.util.Arrays;

public class test {

    public static String[] fizzBuzz(int start, int end) {
        String[] numbers = new String[end - start];

        for (int i = start; i < end; i++) {
            if (i % 15 == 0) {
                numbers[i - start] = "FizzBuzz";
            } else if (i % 3 == 0) {
                numbers[i - start] = "Fizz";
            } else if (i % 5 == 0) {
                numbers[i - start] = "Buzz";
            } else {
                numbers[i - start] = String.valueOf(i);
            }
        }
        return numbers;
    }

    public static void main(String[] args) {
//    int start = 6;
//    int end = 10;
        fizzBuzz(6, 10);
        System.out.println(Arrays.toString(fizzBuzz(6, 10)));
    }
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
vob
  • 1
  • 1
  • remove the static keyword in fizzBuzz() method . System.out.println(new Test().fizzBuzz(6, 10) ); and Class Name Always Started Capital Letter – Ng Sharma Mar 23 '20 at 16:41

1 Answers1

0

You need to create an object of your class to use non-static methods.

import java.util.Arrays;

public class Test {

    public String[] fizzBuzz(int start, int end) {
        String[] numbers = new String[end - start];

        for (int i = start; i < end; i++) {
            if (i % 15 == 0) {
                numbers[i - start] = "FizzBuzz";
            } else if (i % 3 == 0) {
                numbers[i - start] = "Fizz";
            } else if (i % 5 == 0) {
                numbers[i - start] = "Buzz";
            } else {
                numbers[i - start] = String.valueOf(i);
            }
        }
        return numbers;
    }

    public static void main(String[] args) {
//    int start = 6;
//    int end = 10;
        Test testObj = new Test();
        System.out.println(Arrays.toString(testObj.fizzBuzz(6, 10)));
    }
}

You can read more about static objects here.

Moreover, your class' names are not as per java naming convention. Please read more about naming conventions here.

Rahul Goel
  • 842
  • 1
  • 8
  • 14