English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I have to create a Java-based application (using the BlueJ interface and compiler) that caluclates body mass index. I have a code developed, but for some reason I keep getting an error saying that "non-static method cannot be referenced from a static context". Could somebody please help me fix this?:

public class Java016A {

public int index (int weight, int height) {

int bmi = 10000 * (weight / (height^2));

return bmi;
}

public static void main () {

int weight, height, bmass;
weight = 50;
height = 120;

bmass = index(weight, height);

System.out.println("Body Mass Index: " + bmass);
}
}

2006-10-19 18:35:07 · 2 answers · asked by NiceShyGuy 1 in Computers & Internet Programming & Design

2 answers

you cannot access a non-static method inside main(since it is static-Refer the textuals for the explanation of a static member).

So if you want to access the method just try one of the 2 tecniques.

1)create an object and access the method.
Java016A obj = new Java016A();
obj.index(weight, height);
or
2) declare the index method(function) as static.

public static int index (int weight, int height) {
int bmi = 10000 * (weight / (height^2));
return bmi;
}

good luck.

2006-10-19 21:50:21 · answer #1 · answered by Anand 3 · 2 0

It is an easy fix. You need to create an object of the class Java016A and then call the index() method.

In your main() method, instead of trying to call the index() method directly, you could do this:

Java016A indexer = new Java016A();
bmass = indexer.index(weight, height);

I hope that this helps!

2006-10-19 18:56:42 · answer #2 · answered by codewriterdavid 3 · 0 0

fedest.com, questions and answers