• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to return a value from a function/method/class?  RSS feed

 
Daniel Dagenhart
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am learning to call functions, but I hit a snag.

The program will compile, and it will let you input 4 numbers..

What I want it to do next is to sum up all of those values that are input.

What I have tried so far is : Making a double temp and trying to return the value , I have tried to make a global double above the public main static void.. I have tried putting double " name" down in the other public static sideA, B, C, D etc..  I have tried other things I already forgot, but nothing is working.

Can someone explain how to retrieve the values of what ever the user input is, and then sum it up back up in the main method.

I watched a few videos on you tube about call functions, but none of them were about retrieving a value.

Thank you.
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Refer to the Java Tutorials: https://docs.oracle.com/javase/tutorial/java/javaOO/returnvalue.html

Why don't you simplify your program so you only have a few problems? Right now, you have lots of problems with the code you wrote: it's not indented properly, you have lots of repetitive code, and it's not very logical. Why would you ask the user to enter the length of each of the four sides of a square? You know that all four sides of a square have the same length, right?
 
Daniel Dagenhart
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Junilu Lacar wrote:Refer to the Java Tutorials: https://docs.oracle.com/javase/tutorial/java/javaOO/returnvalue.html

Why don't you simplify your program so you only have a few problems? Right now, you have lots of problems with the code you wrote: it's not indented properly, you have lots of repetitive code, and it's not very logical. Why would you ask the user to enter the length of each of the four sides of a square? You know that all four sides of a square have the same length, right?


Its not meant to  be that logical..  the point is to just add 4 sides together..  and the other point is just to understand how to return values that are created on other methods and get them into the main.

As for the program being simpler, yes I could make it add 4 numbers together from user input and make a sum of them all, but I just need to find out how to retrieve a value that is made in a method and then get that value back to the main so I can add them together..  I can clean the rest of the code up, I just need to learn what I was asking. 
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Daniel Dagenhart wrote:
Its not meant to  be that logical.. 

Programming is all about logic. IMO, it's not very useful, especially when you're learning, to separate logic from the mechanics of the language that you're trying to learn. Sure, you can learn to use a screwdriver or hammer and just drive random screws or nails into a piece of wood but you don't learn a whole lot from doing that and you don't get anything very useful out of it. It would be better to try to make a simple box using a few nails or screws, pieces of wood, and a screwdriver or hammer. Then it all comes together in something that's actually useful.

Did you look at the tutorial page that I cited? That tells you how to write methods that return values.
 
Fred Kleinschmidt
Bartender
Posts: 572
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you should be using OOP- create an instance of Square in main(), using a comnstructor that takes the side length as an argument and saves that in an instance variable. Then create a method named getSideLength() that returns the length of a side, and another called getArea() that gets the area, and getPerimeter() that gets the perimeter, etc. None of those methods should be static
 
fred rosenberger
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So a couple of things have to happen to return a value from a method.

1) the method has to be declare to return <whatever>.  A method must return a specific kind of thing.  If you declare it to return an Integer, it can't return a Database connection.

2) the method must have lines like "return <whatever>" in it in such that whatever execution path is taken, one is hit.  This is invalid:


if myValue is not 7, then the method doesn't know what to return. This will be flagged by the compiler as an error.

3) You more than likely want to SAVE what is returned.  Assuming I have a valid method that returns an int, this doesn't do me much good:

because the value returned by myMethod is lost. It's like if you ask someone a question, then walk away without hearing their answer. They may still say the answer, but it's lost. You'd need to do something like this:

then the value returned by myOtherMehod is saved in the variable saveThis.

Note: these examples were typed out way too early in the morning before I've had even CLOSE to enough coffee, so please forgive any minor typos.  I'll fix them later if they are pointed out to me.
 
Daniel Dagenhart
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Junilu Lacar wrote:
Daniel Dagenhart wrote:
Its not meant to  be that logical.. 

Programming is all about logic. IMO, it's not very useful, especially when you're learning, to separate logic from the mechanics of the language that you're trying to learn. Sure, you can learn to use a screwdriver or hammer and just drive random screws or nails into a piece of wood but you don't learn a whole lot from doing that and you don't get anything very useful out of it. It would be better to try to make a simple box using a few nails or screws, pieces of wood, and a screwdriver or hammer. Then it all comes together in something that's actually useful.

Did you look at the tutorial page that I cited? That tells you how to write methods that return values.


Yes, if we are talking about a square.. I know I used it in my program above, but that is not the object of my question if something is square or not. 
LEts forget I ever called it a square, and just say its an object that has 4 sides of X length.. I want to find the perimeter of all 4 sides.. the shape is irrelevant, its needing to figure out how to retrieve information that was generated in another method. In this case a numerical value that needs to be stored, and then passed back to the main method.
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I sense you're getting a little defensive; don't take the square comment the wrong way. That's something you're going to have to learn if you're going to write programs: you'll make mistakes and sometimes they make you look a little silly. No big deal, everybody does it. The best way to deal with mistakes and critiques/criticism is by adopting the mindset of the egoless programmer.

You've already been given a link to the tutorial page that teaches how to write methods that return values and Fred also gave you some guidelines.

Here's an example you can use directly:

You only need to declare a Scanner one time, not multiple times as you have done. You also only need the one method. If you want the prompt to be different, then define a parameter, don't define essentially the same method N number of times just because you want the prompt to be different.

EDIT: If you look at the example I gave, it has a mistake. One might even say it's a dumb mistake. Again, no biggie. Happens to everybody, even to the best programmers, not that I'm claiming to be one them.

The example should be this:

My mistake was in declaring the method to return an int value when the code actually returned a double value.
 
Daniel Dagenhart
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Junilu Lacar wrote:I sense you're getting a little defensive; don't take the square comment the wrong way. That's something you're going to have to learn if you're going to write programs: you'll make mistakes and sometimes they make you look a little silly. No big deal, everybody does it. The best way to deal with mistakes and critiques/criticism is by adopting the mindset of the egoless programmer.

You've already been given a link to the tutorial page that teaches how to write methods that return values and Fred also gave you some guidelines.

Here's an example you can use directly:

You only need to declare a Scanner one time, not multiple times as you have done. You also only need the one method. If you want the prompt to be different, then define a parameter, don't define essentially the same method N number of times just because you want the prompt to be different.

EDIT: If you look at the example I gave, it has a mistake. One might even say it's a dumb mistake. Again, no biggie. Happens to everybody, even to the best programmers, not that I'm claiming to be one them.

The example should be this:

My mistake was in declaring the method to return an int value when the code actually returned a double value.


Thanks for you help. I got better clarification today when talking one on one with a person who knows java in and out.  I now realize that to get that value from the the methods, first  it was suggested to just use int , second was to name the method/ class I am calling an int so public int whatevername()  put the int value in the class into an int variable , then return it.. then call that class back up to my main.

So I am already rewriting the program to clean it up, and make it function.  Thanks for the help.
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Daniel Dagenhart wrote:
Thanks for you help. I got better clarification today when talking one on one with a person who knows java in and out.

No problem. There are a lot of folks around here who know a few things about Java, too. In fact, we have quite a number of authors of Java books on staff at CodeRanch. But like I said, gotta be egoless, so practice what you preach and all that... 

I now realize that to get that value from the the methods, first  it was suggested to just use int , second was to name the method/ class I am calling an int so public int whatevername()  put the int value in the class into an int variable , then return it.. then call that class back up to my main.

Well, I hope those are your words and not those of your knows java in and out guy because the terminology is all jumbled and wrong.  Translated to use the correct terms, that would be better stated as something like this:

... to get a value from a method, first you need to declare the method's return type (something other than void) in front of the method name, like int myMethod(). The method needs to have a return statement that includes the value to be returned by the method, like return 5; or return anIntVariable;. When you call the method, you can use the returned value in an expression that is compatible with the method's return type, like double perimeter = perimeter + inputSideLength(). If you want to save the returned value, you have to assign it to a variable that is compatible with the method's return type, like double sideLength = inputSideLength();
 
Daniel Dagenhart
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, I reworked it to where I got it to work, and chopped off all the other methods.

This still is not the optimal way to do this, but it did allow me to get more of a basic understanding to call functions from other classes.
I greyed out the old stuff just to see what I got rid of.

 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Variables should start with a lowercase letter, so your SideA, SideB, etc. variables should be sideA, sideB, etc, instead.

Your code formatting needs a lot of work. Properly formatting/indenting your code so that it follows any of the common indentation styles for Java programs makes your program easier to read and it helps reveal the program logic and any possible errors in it.

You should also take care to choose good variable/method/class names.  Good names are very important, good names can make your program very readable and understandable. Bad names, such as what you currently have, mislead the reader and make the program unclear and/or confusing to follow.

Compare what you wrote with this:

This incorporates all the advice you've been given in this thread: Use objects and methods, don't duplicate code, use only one Scanner object for console input, etc.
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Programs like the example I gave are often confusing for beginners because of the presence of both static and non-static methods in the same class. Here's an equivalent program, this time with two classes, the "driver" class that dictates the flow of the program and the other class that represents an object, in this case a Square.

Notice how the MethodsDemo class has all static methods. In those methods, it does display, user input, and object instantiation. It creates a Square object which takes care of all the calculations that need to be made to get the area and the perimeter of a square whose sides are a given length.
 
Daniel Dagenhart
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Junilu Lacar wrote:Variables should start with a lowercase letter, so your SideA, SideB, etc. variables should be sideA, sideB, etc, instead.

Your code formatting needs a lot of work.


Yes I know , I have been told before how bad it was.  I was told to get a book . I think its called Clean Code , I am not sure. I did find it on Amazon and downloaded to my Kindle, but I havent had time to really get into it yet.

This is my 3rd class I have taken in Java , 104, 211, 314 ..  104 was mainly learning how to draw lines, rectangles, understanding for loops.  211 was even more on forloops , do while etc.. and Arrays, doing coding Bat exercises.. this is my 3rd one , 314, and now we are learning classes methods functions..

Honestly I am disgusted with the professor. He is brilliant, hes pretty old , been programming for 45 years , but he is not a good teacher if you know what I mean. He knows how to write code in his sleep, but has poor skills in transferring, translating his knowledge into a way for us to understand. So i spend most of my time watching videos like The New Boston  which goes over the basics of everything, coding bat.

Professor says programming is done better by people who are more left brained.  I dont know how much truth there is to that, but I took 5 tests online to see what I am, and I am in the middle on all the test. I have equal balance.

I dont want to be a programmer, I dont think its my calling. However, my Major is CIS concentration in networking and cyber security.  I like the networking side of it, and I havent really got my feet wet with the cyber security part yet.
Anyway , I will see what becomes of it all. I still have 2 years and this semester left. 
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Daniel Dagenhart wrote:Professor says programming is done better by people who are more left brained.  I dont know how much truth there is to that, but I took 5 tests online to see what I am, and I am in the middle on all the test. I have equal balance.

In my experience, programming usually takes the whole brain. You need to be logical and organized. You also need to be creative, have a knack for thinking in abstract terms, looking at things from different perspectives. I don't know which side controls which but they both need to work together. Clean Code is a great book. Chapter 2 is all about names and choosing good ones to use in your programs. If there's one chapter in that book that you will find useful, it's that chapter.

Another good book I've been recommending is Think Like a Programmer by V. Anton Spraul.  It's all about problem solving strategies and organizing your solutions. That's what a lot of teachers unfortunately gloss over. They seem to like jumping right into nitty gritty details like how to draw lines and circles and do for-loops.

Cybersecurity is not an easy field. People who are successful in this field are also good programmers. If you're going to be a soldier in that war, you're going to need to know how to use the weapons and code is the weapon of choice in cyber warfare. You have to know how your opponents think and the kind of techniques they use. If you don't know how to program, you're going to be at a huge disadvantage.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!