I'm not sure if I understand correctly how to call a new method in Java

1827 views java
-4

I have the following exercise that I'm trying to solve:

Write a class Summing with a method public static void sumit(). The method computes the sum of all numbers between 1 an 200 which are divisble by 7 and prints the result in the form

"The sum is NUMBER"

where "NUMBER" is the sum.

Here is what I've written so far:

public class Summing {
    public static void main(String[] args) {
        public static void sumit() {
            for(int i = 0; i <= 200; i += 7) {
                System.out.print("The sum is " + i);
            }
        }
    }
}

I'm not sure how I correctly call on the sumit() method here. Can anybody point out to me how I properly create the method sumit()?

answered question

Put your method outside of the main, and then just you can just call it like: sumit()

2 Answers

13

execution of program always starts from main method, so you need to call sumit method inside main method

 public static void main(String[] args) {
    sumit();
}
 public static void sumit() {
        for(int i = 0; i <= 200; i += 7) {
            System.out.print("The sum is " + i);
        }
    }

posted this
9

You cannot put a method inside another method so rather do this:

  • Write your method outside the main method

    public class Summing {

    public static void main(String[] args)

    { sumit(); }

    public static void sumit() { for(int i = 0; i <= 200; i += 7) { System.out.print("The sum is " + i); } } }

posted this

Have an answer?

JD

Please login first before posting an answer.