How to call method from same class? - java

i am using this code to call the method which is present in same class. when i am trying to call the method, i am getting this error..
How to resolve this error
please help me
error:
: cannot find symbol
symbol : method getRowCount()
code:
int modelvalue =(int) getRowCount();
System.out.println("This is model"+modelvalue);
method:
public int getRowCount()
{
return dataz.size();
}

You're probably calling the method from a static method (main?).
When you have non-static method, you have to access it through an object.
You should do:
MyClass myObj = new MyClass(); //Actually it's your class
int modelvalue = myObj.getRowCount();
Another note, it's redundant to cast the result to int. It's already an int.

If you are calling getRowCount() in static method then you will get this error.You need to create object of the class containg method and call the method on that object.
eg :
public class Abc
{
public int getRowCount()
{
return dataz.size();
}
public static void main(String args[])
{
Abc ob=new Abc();
int modelvalue =ob.getRowCount();
System.out.println("This is model"+modelvalue);
}
}

This is Because you called the method with a missing definition where it is defined ,since you have not shown your class structure on how you define your method and how your going to access it ...but this is similar issue caused when you have'n instantiated the class it belongs like
MyTestClass test = new MyTestClass();
int result = test.getRowCount();
System.out.println("Result is Integer {0},is:",result);

Related

How to jump to another method?

Is there any function in java that lets you jump to another method?
This is an example how it should work:
if (boolean expression(){
jump to public void something;
if (boolean expression) {
jump to public void something2;
} else{
jump to public void 3;
}
This is needed for a program that checks 3 numbers, and they have different methods linked to them.
If by jump, you mean calling a method:
if (boolean expression(){
something();
if (boolean expression(){
something2();
}
else{
something3();
}
Simply invoke it, in your example
if (boolean expression(){
something();
} else if (boolean expression(){
something2();
} else{
something3();
}
instead of jump to public void something just call something()
There is no syntax called "jump to" although you can easily call a method by firstly making a method.
public void myMethod(){
// do something
}
now when you have done this, you call it from another method by invoking it's name myMethod();. You might know that a method can either return a variable or return nothing (void) if you give it a return-type you MUST return a variable with the same type as your method.
For example:
public int oneplusone(){
int integer = 1 + 1;
return integer;
}
and a void would be like this:
public void oneplusone(){
int integer = 1 + 1;
System.out.println(integer);
}
When you've specified your method you need to call it by invoking its name from another place in your program. Final example:
public class Snippet(){
public static void main(String args[]){ // THIS IS THE MAIN METHOD OF YOUR PROGRAM!
Snippet snippet = new Snippet();
System.out.println(snippet.oneplusone());
}
public int oneplusone(){
int integer = 1 + 1;
return integer;
}
}
I suggest you should check out thenewboston java tutorials explaning java for beginners. Good luck!
if you have the mothod call in the class just call the method like
something(int i);
if your method is in another class make sure you have an object of that class if the method isn't static and call your method
Foo foo = new Foo();
foo.something(10);

StackOverflowError when trying to call a method which calls another method from another class

I think the method is calling itself or something.
Here's my code:
public boolean isRaak(int rij, int kolom)
{
boolean raak = isRaak(rij, kolom); //this "isRaak" should refer to a method in another class, not sure how to do this...
return raak;
}
Two ways
If that is a instance method, You need to create instance of that and call it.
public boolean isRaak(int rij, int kolom)
{
AnotherClass an =new AnotherClass();
boolean raak = an.isRaak(rij, kolom);
return raak;
}
If that is a static method
public boolean isRaak(int rij, int kolom)
{
boolean raak = AnotherClass.isRaak(rij, kolom);
return raak;
}
But your method seems like an Utility method to me,So go for static method,if so.
Before proceeding further, Prefer to read:
Understanding Instance and Class Members
The error is pretty evident. Call the method by prefixing the classname if the method is static, else call the method with the object of the class.
I can think of 3 ways to accomplish this:
Create a new instance of your AnotherClass and call the isRaak method:
public boolean isRaak(int rij, int kolom) {
return new Anotherclass().isRaak(rij, kolom);
}
Reuse a current instance of your AnotherClass and call the isRaak method:
//field in the class initialized somewhere along your current class...
AnotherClass anotherClass = ...
public boolean isRaak(int rij, int kolom) {
return anotherClass.isRaak(rij, kolom);
}
If the method is declared as static in AnotherClass, call the method directly from the class without using an instance.
public boolean isRaak(int rij, int kolom) {
return AnotherClass.isRaak(rij, kolom);
}
Note that the first two methods assume the constructor of AnotherClass doesn't need to receive parameters, but this should be adaptable to your specific case.

How to call a function with array parameters in main application?

I've been doing some tutorial on inheritance abstract class, and I pass an array to a function for a calculation of total price. But then, when I tried to call the function in the main, it didn't work and I've got some error according the method call.
Here is my calculation code in subclasses :
public double calcPrice(String[] a, int[] qty, int num){
int i =0;
for(i=0;i<=num;i++) {
if (a[i]=="a")
price=24.90;
}
double tot=price+qty[i];
return tot;
}
This is my method call in the for loop. I don't know how to call the method as the error says "non-static method calcPrice() cannot be referenced from a static context"
for(int i=0;i<=num;i++) {
System.out.println("\t"+a[i]+"\t\t\t"+qty[i]+" "+calcPrice());
}
The main method is static, and can't call non-static code. You have 2 solutions.
Create an instance of the class performing the calculation, and call calcPrice on that instance.
make calcPrice static.
I suggest option one as you've been doing research on classes. This would be good practice for you.
Also do not compare variable a to "a" with ==. Use .equals instead. Check this link for why.
Edit:
I'm not sure how an abstract class plays into this as you have no abstract methods needing implementation.
public class CalcClass{
public double calcPrice(String[] a, int[] qty, int num){
int i =0;
for(i=0;i<=num;i++) {
if ("a".equals(a[i]))
price=24.90;
}
double tot=price+qty[i];
return tot;
}
}
public class MainClass{
public static void main(String[] args){
//create instance of calc class
CalcClass c = new CalcClass();
//call calc price method on calcclass
c.calcPrice(a, new int[]{1}, 1};
}
}
Changed to-
public static double calcPrice(String[] a, int[] qty, int num){
...
}
You should create an object before you do a call from main. Say you have a class-
public class Test {
public void someMethod(){
}
public static void main(String... args){
// Create an object first
Test t = new Test();
// Now you can use that non-static method someMethod
t.someMethod();
}
}
For static method, they exist on load.
You will need to create instance in order to call you method since your method is not static.
making you methos static will enable you to use it without creating instance of the class.
you may want to read about Static Methods here

getting the current class object

I have three classes.. A,B,C.
In both classes B and C i have a static string variable "name" which contains the name of B and C, as-
class B
{
static name;
public static void main(String args[])
{
name="Class B";
A.getName();
}
I am calling class A's getName method from class B and C.. Class A is as follows:
class A
{
getName()
{
System.out.println(this class called me);
}
}
class C is:
class C
{
static name;
public static void main(String args[])
{
name="Class C";
A.getName();
}
Now my question is, what code should i use in place of "this class called me" in class A so that i get the name of whichever class calls A! I hope i am clear!!
Your A.getName method cannot know what class's code called it. You have to pass that information into it.
Okay, so that's not strictly true, you could figure it out by generating a stack trace and inspecting that. But it would be a very bad idea. In general, if a method needs to know something, you either A) Make it part of an instance that has that information as instance data, or B) Pass the information into it as an argument.
class A {
getName()
{
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
int lastStackElement = stackTraceElements.length-1;
String callingObjectsName = stackTraceElements[lastStackElement].getClassName();
System.out.println(callingObjectsName + " called me.");
}
}
Modify your code to something like this:
class A
{
getName(String className)
{
System.out.println(className);
}
}
and use it like :
class B
{
static name;
public static void main(String args[])
{
name="Class B";
A.getName(name);
}
}
It sounds like what you're really trying to do is to pass information from one stack frame to another one -- and specifically, from a frame A to a frame B, where A invoked B. This is an easy thing to do, and I think you're over-engineering it.
public class B {
static String name = ...
public static void main(String[] args) {
A.getName(name);
}
}
public class C {
static String name = ...
public static void main(String[] args) {
A.getName(name);
}
}
public class A {
public static void getName(String name) {
System.out.println(name);
}
}
Your approach would require:
Getting the stack trace
Using that to get the calling stack frame, which is element 1 in the stack trace array
Using that to get the class name for the calling method
Using Class.forName to get the Class<?> object
Calling getField("name") on that Class<?> object to get a Field object
(optional but recommended) Confirming that the Field represents static field of type String
calling get(null) on the Field to get its value (the null represents the object for which you want the field -- since the field is static and thus not tied to any object, this argument is ignored), and casting this value down to String
Or, instead you could:
Just pass the name to the function that needs it.
Your approach also requires that the name field be static, since there's no way to get the calling instance (even though you can get the calling instance's class). The simpler approach works even if name is an instance field.

Non-static method cannot be referenced from static content

I cannot compile the following code:
public class Test {
public static void main (String [] args ){
int a = calcArea(7, 12);
System.out.println(a);
}
int calcArea(int height, int width) {
return height * width;
}
}
The following error appears:
Non-static method calcArea(int, int) cannot be referenced from static content
What does it mean? How can I resolve that issue..?
EDIT:
Based from your advice, I made an instance which is new test() as follows:
public class Test {
int num;
public static void main (String [] args ){
Test a = new Test();
a.num = a.calcArea(7, 12);
System.out.println(a.num);
}
int calcArea(int height, int width) {
return height * width;
}
}
Is this correct? What is the difference if I do this...
public class Test {
public static void main (String [] args ){
int a = calcArea(7, 12);
System.out.println(a);
}
static int calcArea(int height, int width) {
return height * width;
}
}
Your main is a static, so you can call it without an instance of class test (new test()). But it calls calcArea which is NOT a static: it needs an instance of the class
You could rewrite it like this I guess:
public class Test {
public static void main (String [] args ){
int a = calcArea(7, 12);
System.out.println(a);
}
static int calcArea(int height, int width) {
return height * width;
}
}
As comments suggests, and other answers also show, you might not want to go this route for evertyhing: you will get only static functions. Figure out what the static actually should be in your code, and maybe make yourself an object and call the function from there :D
What Nanne suggested is definitely a fix for your problem. However, I think it would be prudent if you got in to the habit right now, while you are early in your progression of learning java, of trying to use static methods as little as possible, except where applicable (utility methods, for instance). Here is your code modified to create an instance of Test and call the calcArea method on your Test object:
public class Test {
public static void main (String [] args ){
Test test = new Test();
int a = test.calcArea(7, 12);
System.out.println(a);
}
int calcArea(int height, int width) {
return height * width;
}
}
As you get further in to coding with java and, presumably given the code you've just written start dealing with objects such as polygon objects of some sort, a method like calcArea belongs at the instance context and not the static context so it can operate on the internal state of your objects. This will make your code more Object Oriented and less procedural.
calcArea mustn't be static. For using another methods in main class, you must create an instance of its.
public class Test {
public static void main (String [] args ){
Test obj = new Test();
int a = obj.calcArea(7, 12);
System.out.println(a);
}
int calcArea(int height, int width) {
return height * width;
}
}
Do you know what a static method is?
If not, look it up, but the short answer is that a static method does not (can not) access "this" because it is not assigned to any particular instance of the class. Therefore you can't call an instance method (one that isn't static) from within a static one, because how will the computer know which instance should the method be run on?
If a method is defined as static that means you can call that method over the class name such as:
int a = Test.calcArea(7, 12);
without creating an object,
here; Test is the name of the class, but to do this calcArea() method must be static or you can call a non-static method over an object; you create an object by instantiating a class such as:
Test a = new Test();
here "a" is an object of type Test and
a.calcArea(7,12);
can be called if the method is not defined as static.
your class calcArea should be declared static and if you want to use that class, you have to first create an instance of the class. In the class the parameters of the class should be returned, as someone suggested.

Categories

Resources