aspose file tools*
The moose likes Beginning Java and the fly likes beginning methods help Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "beginning methods help" Watch "beginning methods help" New topic
Author

beginning methods help

Heather Hamrick
Greenhorn

Joined: Feb 21, 2012
Posts: 13
Alright, I'm new here and need some help with methods, which we just started in my Java 1 class. I have to make a method with EvenOdd program that inputs an integer using JOptionPane and returns true or false whether its even or odd and uses JOptionPane for output stating whether the number is even and odd. We also have to use a sentinel while loop. I'm having some trouble calling the method correctly in the main program part, so I'm kinda lost. SOme help would be greatly appreciated!

Zeeshan Sheikh
Ranch Hand

Joined: Nov 20, 2011
Posts: 144

ans = isEven //???;

Well isEven is not a variable its a method so



//method returns boolean so it should always return a value

Hope this helps.


MySQL Blog
http://mysqlearner.blogspot.com/
Heather Hamrick
Greenhorn

Joined: Feb 21, 2012
Posts: 13
so what is the purpose of the "2"? I just want to read in a number from the user in JOption Pane and return a message in JOptionPane whether it is even or odd
Zeeshan Sheikh
Ranch Hand

Joined: Nov 20, 2011
Posts: 144

Here is the complete solution.



Hope this helps
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11422
    
  16

Zeeshan Sheikh wrote:Here is the complete solution.

Hope this helps

It does not. Our goal here is to teach people how to write their own code, therefore we do not provide complete solutions.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Zeeshan Sheikh
Ranch Hand

Joined: Nov 20, 2011
Posts: 144

Sorry I tried to point her in right direction but somehow was not making sense to user so I corrected those error messages. Next time I will keep this in mind.
Heather Hamrick
Greenhorn

Joined: Feb 21, 2012
Posts: 13
Sorry, I didn't want to be given the answer...I have revised my program...now I just have two issues, first of all before the last bracket, I have the error that "missing return statement". Also I can't really figure out the correct way to call the method in order to get a JOptionPane output that either says its even or odd.

Zeeshan Sheikh
Ranch Hand

Joined: Nov 20, 2011
Posts: 144

1. Look at the signature of your method. It returns boolean which is why compiler is complaining about return statement.

2.JOptionPane returns a String. You need to convert String to integer so It can be passed to method.

3. Use showMessageDialog() method within if statement and it will display output i.e. value is even or odd.

Hope this helps.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11422
    
  16

You have to remember that the compiler is dumb. You and I can both see that the while loop will always run since you set integer to 0 just before the while statement...but the compiler can't see that. It is saying "Well...what happens if we never enter the while loop? What should I return then?"

as a bigger picture, I would question why you have a while loop at all. In fact, the whole isEven method looks...strange.

You pass in an integer on line 22, then you immediately set that variable to 0 - this causes you to loose whatever you passed in.

The while loop is totally unnecessary. You can do the test of 'integer % 2' without the loop, you only have to do the test once...personally, I'd take the loop out entirely.

but you then again set integer to 0 oi line 32. Do you expect it to have changed somewhere? What is the purpose of this?
Ryan Sykes
Ranch Hand

Joined: Jan 18, 2012
Posts: 58
You will need to look up the Integer.parseInt() method to convert number which is a String into an int. Additionally, I hope that your declaration of int n = 0 is just there for troubleshooting, because as it stands, you are not doing anything with your String variable number, after you get the user input.

I think you need to take a step back and work through the logic before diving head first into the code. For example, what is the purpose of messaget and messagef? You do not seem to do anything with those Strings.

PS - if you have learnt about ternary operators, then this would be a more succinct way of expressing this part of your code:

Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Ryan Sykes wrote:
PS - if you have learnt about ternary operators, then this would be a more succinct way of expressing this part of your code:



More succinct still is


Any time you have condition ? true : false, you can just use condition. And of course for the opposite, condition ? false : true, simply !condition.
Ryan Sykes
Ranch Hand

Joined: Jan 18, 2012
Posts: 58
Haha, thanks for making me feel like an idiot Jeff :-). You are absolutely correct.
Heather Hamrick
Greenhorn

Joined: Feb 21, 2012
Posts: 13
Thanks everyone for the help but I'm still stuck because many of the things you posted I am not allowed to use because we haven't learned them.
These are the requirement for my homework that have to be done in this program:
1) method isEven that uses the remainder operator to determine whether an integer is even
2) method should take in an integer arguement and return true if it is even and false if odd.
3) use JOptionPane for input and output
4) program will run an indeterminate number of times, so you use a sentinel while loop, use -1 as sentinel

that is why I have used a sentinel while loop and the boolean type since it requires me to return true & false.

Here is how far I have gotten in the code and I have questions within the code that I would appreciate help with.

Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Heather Hamrick wrote:ne.showInputDialog("Enter integer, enter -1 to quit");
// >>>how do I call the boolean method so that it runs?


You need a loop something like this:




public static boolean isEven(int integer)
{
String message1 = "";
String message2 = "";


while (integer != -1)


The isEven() method should not loop. It should just tell you whether its input is even, once. The caller of isEven() will do the looping.

} //<<< error says it is "missing a return statement", I'm not sure what to do here.


Not an issue once you fix above looping, but the problem is this:

If the while loop is never entered (that is, if the condition is never true), then we're not returning anything.

Zeeshan Sheikh
Ranch Hand

Joined: Nov 20, 2011
Posts: 144

As per your method signature it should always return a value, in your case use return true after while block.

Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Zeeshan Sheikh wrote:As per your method signature it should always return a value, in your case use return true after while block.



Bad idea.

We don't just return some arbitrary value to make the compiler stop complaining. Instead, we understand the logic error we made that led us to that compiler error and we fix it.
Heather Hamrick
Greenhorn

Joined: Feb 21, 2012
Posts: 13
so instead of doing "return true;" what kind of return should I use?
Zeeshan Sheikh
Ranch Hand

Joined: Nov 20, 2011
Posts: 144

As Jeff said in the above post "The isEven() method should not loop. It should just tell you whether its input is even, once. The caller of isEven() will do the looping".
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Heather Hamrick wrote:so instead of doing "return true;" what kind of return should I use?


None.

As I pointed out, in this case having the while loop was wrong in the first place. The correct solution is to examine the logic, realize that, and fix it so this becomes a non issue, and you don't end up having to return anything.

But let's say the while loop was valid, and we had something like this:



Then it would depend on the real-world semantics of a method.

For instance, if it were an equals() method comparing array contents, such as how String's equals() method, then we'd take the return true out of the loop, since we could only return true after we'd iterated over all the array elements. Any mismatch inside the loop would cause us to immediately return false, but if we made it all the way through the loop, then we'd return true, after it. So, in this case, your solution would have been partially correct. We'd put in the return true you added, but only after examining the logic, finding our error, and eliminating the return true inside the loop.

On the other hand, if we were searching a List or array for the existence of an element, it would be the opposite. If we found it at any point in the loop, we're done and we return true, but if we make is out of the loop without finding it, the answer is false. So we'd get rid of the return false inside the loop, and put it after the end of the loop.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11422
    
  16

If you want the brutal truth...You should throw all this code away, and start over from the beginning.

And by "beginning", i REALLY mean the beginning. That means you don't think about java, or while loops, or booleans. You think in English, and say "what should my program do?". You actually write it down. you then revise it several times, refining each step. something like this:

revision 1:
1) ask the user for a number, tell them if it is odd or even, and repeat until they enter "-1".

The above cannot be easily converted directly into java. let's revise it again
revision 2:
1) ask the user for a number
2) test it for odd/even, and print result
3) repeat if they didn't enter "-1"

again, none of the above can easily be converted directly to java. But notice something...#1 and #2 above are INDEPENDENT of each other. I can ask the user for a number, regardless of what I want to do with it. Further, I can test a number for even/odd, regardless of where it comes from. This suggests that perhaps these two things could/should be in different methods. If they were, I could then write another program that needed to (say) test for odd/even for numbers read from a file. All I'd have to do is write the 'read from file' part - the number test method could be used as-is, saving me development time. That is called 'code re-usability;.

So now let's revise #2 above. I need to test for even-ness. a common convention for methods that return a boolean is to name them something like "isWhateverImTesting"...so something like "isEven" would be a good, descriptive name. What should it do?

2a) since it is a method, I will need to pass in the value I'm testing
2b) I know that if the number mod 2 is 0, it is even
2c) if the number mod 2 is NOT 0, it is odd
2d) I need to return true or false

AHA!!! this looks almost like actual java code!!! I can now write this method...



Now, I can write some dummy code in my main() method that tests this. It may need some refining, but once I'm sure it works, I don't have to worry about it anymore. I know this is rock solid (again, once I test it). I can now use it all I want, and work on building the other parts.

a few notes...I ALWAYS use curly braces, even when my block is only one line. It saves me headaches later in live when I am revising code. without them, if i forget and put in a System.out.println(), things can start acting VERY weird.

next...there will probably be some discussion about me using a returnVal variable. There is a lot of debate over whether a method should ever have more than one return statement. Many people feel there should only ever be one, and this is the idiom for doing that. I could have just as easily written the method without it, and done this:

Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4422
    
    8

fred rosenberger wrote:next...there will probably be some discussion about me using a returnVal variable. There is a lot of debate over whether a method should ever have more than one return statement. Many people feel there should only ever be one, and this is the idiom for doing that. I could have just as easily written the method without it, and done this:

Or even, in this particular case:
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

fred rosenberger wrote:


I'm gonna have to go ahead and disagree with you there. In this particular case you don't need to set it to something by default, and in general, you should not. Only assign a default value if it is a meaningful value to have based on the semantics of the method. Never do it just to shut the compiler up.

In this case, it wasn't necessary anyway, because you covered all the code paths, but let's take a trip through a hypothetical evolution of that method:

First, we try this:


The compiler complains that "returnVal might not have been initialized." The wrong way to deal with that is to just blindly give it a value at declaration, to make the compiler stop complaining. A just-as-wrong approach would have been to have done that in the first place, never have gotten the error, and possibly ended up with incorrectly behaving code.

The right approach to that compiler error is to question our own assumptions and think, "Oh, what code path did I miss?" If we do that, we'll see that we didn't handle the case where integer %2 != 0. Now, sometimes we'll find that our logic is sound, and the valid approach actually is to assign an initial value. But it's better to get in the habit of not doing so, in order to give the compiler a chance to help us find our logic errors. In this case, though, we see our missing branch, and we fix it properly.




As a general rule, don't initialize local variables at declaration, unless that value is meaningful and could legitimately be used during the method's execution as per that method's semantics. Leaving them uninitialized gives the compiler a chance to detect logic errors a syntax errors, and you can fix them at compile time. It's much easier to find the cause of an error at compile time than at runtime.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11422
    
  16

Jeff Verdegan wrote:
I'm gonna have to go ahead and disagree with you there. In this particular case you don't need to set it to something by default, and in general, you should not.

yeah, you're right and I know it...i was rushing through that, trying to finish it before a meeting...

I stand by my larger points, though (I think...haven't had time to look at it in depth yet)
Heather Hamrick
Greenhorn

Joined: Feb 21, 2012
Posts: 13
thanks for all the help guys, sorry it is taking me forever to understand. Here it is where I am at...my program compiles but its messed up...help

Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Heather Hamrick wrote:its messed up...help


Please remember that ItDoesntWorkIsUseless.(⇐click) You need to TellTheDetails.(⇐click) What exactly is going wrong?

Also, you ignored my previous advice, so I'm not sure what else I can tell you.

EDIT: And you also ignored Fred's excellent and crucial advice to break it down into pieces, completely outside of Java, and then work on one piece at a time. So I really, really, really don't know what else to tell you.
Ryan Sykes
Ranch Hand

Joined: Jan 18, 2012
Posts: 58
I think between all the great replies on this thread, people have provided enough help for you to at least make some easy and obvious changes. It looks like you haven't taken any of the advice and are just looking for someone to solve this for you (in which case you will not learn anything).

Take some time to read every bit of advice in this thread, understand it, then look at your code and try to implement the suggested changes. If you are unwilling to do this after all the advice posted here, then people will also be unwilling to help you any further.

As Fred said...break everything down into small, logical pieces, figure out the algorithm/pseudocode and then begin the implementation in Java.

And to reiterate for the nth time - get rid of the while loop in isEven() after understanding why it has no place there. Also, get rid of the JOptionPane message dialogs in isEven(). That method should not be handling GUI events for displaying the result. Keep it short and simple and let it return a boolean based on whether the number is even or odd. Use that result from the isEven() call to then display the appropriate GUI dialog from your main method.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11422
    
  16

a method named "isEven" should do NOTHING other than test to see if the value is even. The entire method should probably contain one line. It shouldn't print anything, it shouldn't save anything...all it should to is test for 'even-ness' and return a boolean.

You need to learn how to separate the various pieces of what your code needs to do. that is CRITICAL in writing a good program.
Heather Hamrick
Greenhorn

Joined: Feb 21, 2012
Posts: 13
Alrighttt, I have rewritten my entire program, and just have a compiler issue, I have written my issue in the code. Finally understanding the logic though. Thanks everyone!


EDIT/JD -- horizontal scroll
Zeeshan Sheikh
Ranch Hand

Joined: Nov 20, 2011
Posts: 144

Hint Hint ... Please read above post by Fred posted Yesterday 2:20:04 PM 0 & its mentioned in several above posts.
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Heather Hamrick wrote:Alrighttt, I have rewritten my entire program


And you're still ignoring one of the most important pieces of advice given so far. At least. I haven't bothered wasting my time looking closely, but I expect you've ignore the rest of it too.
Ryan Sykes
Ranch Hand

Joined: Jan 18, 2012
Posts: 58
Please explain why you have a while loop in your isEven() method. There has been plenty of advice on this thread and you seem to be either a) ignoring it or b) not understanding it. Just posting code and making arbitrary changes to appease the compiler without trying to understand the inherent issues within the program is not going to help you in any way.

My piece of advice...as has been posted by Fred before. Stop posting code. Stop thinking about code. Please post a concise pseudocode/algorithm in words as to how you think the logic of the program should flow. Break it into tiny chunks. One chunk can be the isEven(int number) method. Another can be number entry within your main method. Once you figure those two pieces, how can you use a loop to continue getting numbers and checking each entry for whether it is even? I don't think anyone can help you unless you post the logic that you are following and why you are doing what you are doing. Blindly flinging code at this problem without understanding the basic logic is not going to make the program work.
Heather Hamrick
Greenhorn

Joined: Feb 21, 2012
Posts: 13
I have a while loop because thats what my professor has told us to do within our program, so I guess that should be in my main?
Ryan Sykes
Ranch Hand

Joined: Jan 18, 2012
Posts: 58
Heather Hamrick wrote:I have a while loop because thats what my professor has told us to do within our program, so I guess that should be in my main?

But you're not trying to understand why...you seem to be making guesses. So why do you think your professor asked you to use a while loop in the program? He/she obviously had a reason to ask you to use one. Just inserting one for the sake of it, and then moving it around is obviously not going to be of any use till you understand why your program needs a loop.

So - Why do you think a loop is needed in this program? What purpose should it serve?
Heather Hamrick
Greenhorn

Joined: Feb 21, 2012
Posts: 13
the purpose of the loop is to have the program keep running until -1 is entered.
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Heather Hamrick wrote:the purpose of the loop is to have the program keep running until -1 is entered.


Correct. The program. Not the isEven method. Did you even see the comments, from several of us, repeatedly, that the isEven method should not loop, and should just do one thing, and just do it one time?

If you didn't see them, then please pay closer attention to the advice that you're being given, and that you asked for.

If you did see them, but chose not to follow that advice or didn't understand it, please explain why you didn't, or ask about the parts you didn't understand.

There's a lot of good help to be had here, but to make effective use of it, you have to be an active participant in the discussion and the process.
Ryan Sykes
Ranch Hand

Joined: Jan 18, 2012
Posts: 58
Okay, so that part is clear. So from your answer above, and the code you had previously posted, the criteria for the while loop should be something like while(integer != -1). So that is a start. Now, what should go within the while loop? Also, since the loop is checking the value of the int integer, how is this variable being initialized? What do you think should precede the while loop?
Heather Hamrick
Greenhorn

Joined: Feb 21, 2012
Posts: 13
Within the while loop should be an if/else statement that test something like..
..
if(myAnswer ==true)
JOptionPane(print even)
else
JOptionPane(print odd)

...im not sure what should precede the while loop?...I guess I would say you would have to call the isEven method because that determines if the integer is true or false...but thats where I go blank

would I have to initialize the variable by putting "int integer;" in main?
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Heather Hamrick wrote:Within the while loop should be an if/else statement that test something like..
..
if(myAnswer ==true)
JOptionPane(print even)
else
JOptionPane(print odd)


Okay, and where would myAnswer come from?

And where would you put the code for that?

...im not sure what should precede the while loop?


He's hinting at initialization. Remember, a while loop always tests its condition before entering the loop body. So to ever even get into the loop body the first time, the condition has to be true before we first hit the "while" line.

So, if you have while (integer != -1), and you're using that to say, "keep going until integer is -1", what should you do before the loop to make sure that you get into the body at least once?

Or, more correctly, what should we do before we hit the while to tell us whether we should enter the loop at all?

...I guess I would say you would have to call the isEven


So, what you're saying is that we would check if some number is even, exactly once, and then we would go into a loop?

Heather Hamrick
Greenhorn

Joined: Feb 21, 2012
Posts: 13
myAnswer would come from calling the method as "boolean myAnswer;" , and then you would have to call the method in by doing "myAnswer = ???" to determine if true or false is returned

is that how you get into the loop?..well as well as having a JOptionPane to enter the integer
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Heather Hamrick wrote:myAnswer would come from calling the method as "boolean myAnswer;" , and then you would have to call the method in by doing "myAnswer = ???" to determine if true or false is returned


Right, but why the question marks? You know which method, right? And you know how to call a method, right?

is that how you get into the loop?


You get into the loop by making sure the condition is true when you first encounter the while.


And at this point I'll give you a little freebie push, because this part can be tricky for beginners, and I know you've been struggling so far.

There usual pattern for this kind of while loop is something like:



We have to get the input before we ever enter the loop, so that we know if we are going to enter it at all. And we have to get it once on every pass through the loop, so that we know whether to continue next time around.

People usually tend to think of it as


But the two problems with that are 1) input needs a value before you get into the loop. That's easily solved by giving it a dummy, non-negative-1 value to start with, and 2) by the time we've gotten our input we're already executing the body of the loop. We can get around that too, but we won't go into that now.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: beginning methods help