简体   繁体   中英

How to call a non-static method from main in Java?

I've been working on a lab for my Intro to Comp Sci course and I've run into this issue:

As per the instructions, I must have every method that answer the specific question (Ex: Problem 5.9, method is fivePointNine() and must be called within main by another class (Assignment6.main). My problem here is that main is static and the final method I need to call for the lab is non-static, so it will not allow me to compile and run. The three errors I have are related to multiSphere(x). The specific error is "Cannot make a static reference to the non-static method 'multiSphere(double)' from the type Assignment6."

public class Assignment6
{
public Sphere newSphere = new Sphere();
public Assignment6 A6 = new Assignment6();
public static int x;
public static void main(String[] args)
{
       x = 2 + (int)(Math.random() * ((10 - 2) + 1));
   multiSphere(x);

   x = 2 + (int)(Math.random() * ((10 - 2) + 1));
   multiSphere(x);

   x = 2 + (int)(Math.random() * ((10 - 2) + 1));
   multiSphere(x);
    }
    public void multiSphere(double diameter)
    {
    Sphere.inputDiameter(diameter);
    Sphere.volumeCalc(diameter);
    Sphere.surfaceAreaCalc(diameter);
    toString();
}
public String toString()
{
   return "The diameter of this sphere is " + Sphere.inputDiameter(x) + ", the volume      is " + Sphere.volumeCalc(x) + ", and the surface area is " + Sphere.surfaceAreaCalc(x) + ". ";
}

My second class is called Sphere and looks like this:

public class Sphere 
{
public Assignment6 newA6 = new Assignment6();
public static double volume;
public static double surfaceArea;
public static double inputDiameter(double diameter)
{
    return diameter;
}
public static double volumeCalc(double diameter)
{
    // Volume = (4.0/3.0)(pi)(r)^3
    volume = (4.0/3.0) * (Math.PI) * Math.pow((diameter/2.0), 3);
    return volume;
}
public static double surfaceAreaCalc(double diameter)
{
    // Surface area = (4)(pi)(r)^2
    surfaceArea = (4) * (Math.PI) * (Math.pow((diameter/2.0), 2));
    return surfaceArea;
}
}

I'm not exactly sure how to call the multiSphere(x) in the main method without running into the errors I've been getting. I feel like I'm missing something so simple.

Regarding

How to call a non-static method from main in Java?

Short answer: You don't, at least not directly. The canonical answer is to create an instance of the class with the method, and then call the method on that instance, but in your case, it would be worthless since the class has nothing but static fields and methods. This makes your toString method meaningless in a class that is filled with static everything. Either make the method static (and it will not be a true toString() override) or create a true class with non-static fields and methods.


The correct course is to get rid of all static everything from your Sphere class, the critical class here, and then give it a decent public String toString() method override. Of the two classes you've posted, it is the only class where a toString() method makes sense, but again, only if it is a true object oriented class with non-static methods and fields.


Next, you need to give Sphere getter and setter methods that make sense. This:

public static double inputDiameter(double diameter)
{
    return diameter;
}

is neither fish nor foul. Get rid of it and create true getter and setters, the getters taking no parameters but returning a value and the setters taking a parameter and declared to return void.


Next within the static main method, you will create a Sphere variable and assign it a new Sphere instance. Then you can call the appropriate methods of Sphere, including its toString() method.


So in short, scrap all your code and start over. Start with the most important bit -- creating a decent Sphere class. Then create your Assignment class, the one with the main method, and create your Sphere instance.

If you're still confused, post your actual assignment instructions , not your interpretation or paraphrasing of them, so we can see exactly what you're supposed to do.


For example, using a related example that is similar but not the same as yours:

CircleTest.java

public class CircleTest {
   public static void main(String[] args) {
      Circle circle = new Circle(10.0);
      System.out.println(circle); // calls toString()
   }
}

Circle.java

public class Circle {
   private double diameter;

   public Circle(double diameter) {
      this.diameter = diameter;
   }

   public double getDiameter() {
      return diameter;
   }

   public double calculateArea() {
      return Math.PI * diameter * diameter / 4.0;
   }

   public double calculateCircumference() {
      return Math.PI * diameter;
   }

   @Override
   public String toString() {
      String result = String.format("Circle with diameter %.2f, area %.2f, "
            + "circumference %.2f", 
            diameter, calculateArea(), calculateCircumference());
      return result;
   }
}

There is a lot going on here that needs to be rectified fast--especially with finals coming soon.

First, you need to understand how your Sphere class is supposed to work. Every instance of Sphere is its own thing and knows how to do things. All a Sphere needs to be given is its diameter (or radius), and with that, it can figure out everything it needs to about itself. It can calculate its volume and surface area, and it can print itself out in toString .

So you want Sphere to look like this:

public class Sphere {
    public double diameter;

    public Sphere(double diameter) {
        this.diameter = diameter;
    }

    public double volume() {
        return (4.0 / 3.0) * (Math.PI) * Math.pow((diameter / 2.0), 3);
    }

    public double surfaceArea() {
        return (4) * (Math.PI) * (Math.pow((diameter / 2.0), 2));
    }

    public String toString()
    {
       return "The diameter of this sphere is " + diameter + ", the volume is " + volume() + ", and the surface area is " + surfaceArea() + ". ";
    }
}

Notice how Sphere has a constructor, which is how we create new instances of Sphere . We do so with just the diameter. Once it has that, the instance of Sphere can do everything Sphere s do.

Notice also there is no static . I have no idea why you are so in love with static .

You should know that static anything means that every instance of the class shares it. That won't apply to Sphere s because each instance has its own diameter. It isn't like a bunch of Sphere s share a diameter. Some might have equal diameters, but they still are their own. It's like how you and I could drive Bentleys (wishful thinking) that are identical in every way, but they are still two different cars. Of course static things can't access non- static things because non- static things need to be part of an object instance that may not be available.

Finally, in your main class Assignment6 , you simply do something like this:

Sphere s = new Sphere(5);

to create a an instance of Sphere with diameter 5. Now s can tell us its volume, surface area, and its description via toString .

I'm not actually sure what your assignment is, but hopefully this will help you out.

you can use new instance to call the method like this:

public static void main(String[] args)
{
    Assignment6 assignment6 = new Assignment6();
    ....
    assignment6.multiSphere(x);

  ....
    assignment6.multiSphere(x);
     ....
    assignment6.multiSphere(x);
}

but there are some errors with program, please checks it.

First, make your variables (newSphere, A6, and x) private. Global variables should, almost always, be private.
In terms of your question- instead of having the main method call multiSphere, create an object, and call it on that.

public static void main(String[] args) {
    ...
    Assignment6 newAssig = new Assignment6();
    ...
    newAssig.multiSphere();
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM