Niall Lonergan
Niall Lonergan

Reputation: 901

Calculating two variables in method

This is some really beginner stuff. And cannot for the life of me figure out why I cannot have a method calculate two variables for me.

public class Testing {
    int val1; 
    int val2;
    int res;

    public static void main(String[] args)
    {
        int calcResult();
    }

    public Testing()
    {
        val1 = 4;
        val2 = 8;
        res = 0;
    }

    public static int calcResult()
    {
        res = val1 + val2;
        return res;
    }
}

Upvotes: 0

Views: 517

Answers (3)

Waddah Ajaj
Waddah Ajaj

Reputation: 141

You have multiple errors in your code. First off, you can only assign a function result to a variable, so the current code won't compile:

public static void main(String[] args) { int calcResult(); }

Also, you cannot reference a field (non static) variable from a static function, so also the following won't compile:

public static int calcResult()
    {
        res = val1 + val2;
        return res;
    }

because all the variables will not be available from within the static function calcResult().

Not to mention that it's generally bad practice to use field variables in calculations. What I would recommend is something like the following:

public class Testing {

public static void main(String[] args)
{
   new Testing();
}

public Testing()
{
    int val1 = 4;
    int val2 = 8;
    int res = calcResult(val1, val2);
    System.out.println(res);

}

public static int calcResult(int val1, int val2)
{
    return val1 + val2;

}

}

Upvotes: 1

Gilian Joosen
Gilian Joosen

Reputation: 486

val1 and val2 aren't static and your method is static that's a problem. I would recommend you to do this:

public class Testing {
private int val1; 
private int val2;
private int res;

public static void main(String[] args)
{
    new Testing();
}

public Testing()
{
    this.val1 = 4;
    this.val2 = 8;
    this.res = 0;
    this.calcResult();
}

public int calcResult()
{
    res = this.val1 + this.val2;
    return res;
}
}

Upvotes: 2

ikettu
ikettu

Reputation: 1203

static method can not access instance variables.

Remove static keyword and try something like:

public class Testing {
int val1; 
int val2;
int res;

public static void main(String[] args)
{
    System.out.println( new Testing().calcResult() );
}

public Testing()
{
    val1 = 4;
    val2 = 8;
    res = 0;
}

public int calcResult()
{
    res = val1 + val2;
    return res;
}
}

Upvotes: 1

Related Questions