Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to return values from a different class file to main?

 
Ajay Cooper
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!

I just tried adding a "System.out.println(answer)" in the case inside the switch statement, 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
 
Aj Prieto
Ranch Hand
Posts: 75
Android Chrome Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's because you don't have the variable "answer" declared anywhere.

Also because you declared the add method static, you don't have to create an Addition object.

So instead of having to do:
 
Ajay Cooper
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much for the answer!
I learned that I could also just do:
, and it will print out returned value of that method.
 
Campbell Ritchie
Sheriff
Posts: 48363
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

You have fallen into a trap which lots of people fall into. You are writing too much code all in the same place. You are going to write enter 1st number enter 2nd number four times. That is not at all good style. That ought to be moved somewhere else. A separate method. Maybe even in a separate class. Create an Arithmetic class with two fields for the two numbers, and sum() difference() product() quotient() (=divide) and remainder() methods.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic