Question

long time searcher but first time I'm posting a question. I am an IT student going into [haven't started yet] my second programming class. The first was just an intro to Java (we're talking basics really). I have been having a hard time with calling methods within the same class. I have attempted search-foo with poor results. A few articles pop up but they don't cover exactly what I'm looking for. Included is an example (quickly and probably poorly written) to get across what I'm asking. The basic gist [remember to stay with me since I'm new to programming in general] is that I want to add two numbers, creating a third, and have the system display the result...

public class MethodCallExample{

public static void main(String[] args){

  int valueTwo = 3;
  MethodToCall();
  int valueOne;
  int TrueValue = valueOne + valueTwo;
  System.out.println("The total value is " + TrueValue + "!");
}

public static int MethodToCall(){

  int valueOne = 2;

  return valueOne;
}
}

When I go to compile I get one of two errors depending on which derp I try to underp. If I compile as its' written, I receive a "valueOne might not have been initialized" error, and if I either move or remove -int valueOne - I receive "cannot find symbol" referring to valueOne. Any help is greatly appreciated since I am still learning.

Sincerely, Hubert Farnsworth

Was it helpful?

Solution

When you call MethodToCall, you aren't doing anything with the returned value. You need to store the returned value in your variable i.e.

int valueOne = MethodToCall();

OTHER TIPS

It looks like you are confused with the variable scopes. Try doing

int valueOne = MethodToCall();

Inside your main.

When you return something then you need a variable to hold the returned value.. so

int valueone = methodtovalue();

would be correct..

Also note that the variable declared in a function would lose its scope when it is reaches the main program because the variable is declared in function. So valueone in function is different from the valueone declared in main() because valueone in function has its scope only within function and valueone in main has its scope till the end of mainprogram

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top