Hello,
After a relatively small C++ background, I decided to learn some Java. I want to be able to pass two variables from my main class, evaluate them in another class, and return that answer to the main class. I have all the code done for it pretty much, but I can't figure out how to use the returned variable in my main class. Any help would be appreciated!

//This is the main class file 
import java.util.Scanner;
public class Main {
    public static void main (String args[]) {
        System.out.println("Calculator v2");
        Scanner choice = new Scanner (System.in);
        System.out.println("Which operation do you want to do?");
        System.out.println("1-Addition");
        System.out.println("2-Subtraction");
        System.out.println("3-Multiplication");
        System.out.println("4-Divistion");
        int opt = choice.nextInt();
        switch (opt) {
        case 1: {
            Addition addobj = new Addition();
            System.out.println("Enter the first number!"); 
            Scanner numbers = new Scanner (System.in);
            double  fnum = numbers.nextDouble();
            System.out.println("Enter the first number!"); 
            double snum = numbers.nextDouble();
            addobj.add(fnum, snum);

        break;
        }



        default: {
            System.out.println("No such operation!");
        }
        }




    }
}






//This is the addition class file


public class Addition {
    public static double add (double num, double num2) {
        double answer = num+num2;
        return answer;
    }

}

I just tried adding a "System.out.println(answer)" in the case inside the switch statement (ln. 22) , but I got an error saying that "answer cannot be resolved to a variable." I'm sure this is a quick fix, but I couldn't find anything helpful by googling it, so any help would be awesome.
Thanks much!
~Carpetfizz

Recommended Answers

All 2 Replies

You can't really pass variables to methods or return variables. You can only pass and return the value of a variable. So answer isn't really returned, only the number it contains is returned. You need to use addobj.add(fnum, snum) as an expression to get the returned number, such as System.out.println(addobj.add(fnum, snum)). That will print out the number that is returned from add. If you really want a variable called answer in main then you can do double answer = addobj.add(fnum, snum). When you just do addobj.add(fnum, snum) the return value is lost.

Works great, thanks much for the explanation!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.