• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

while loop and try-catch

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Having a little trouble understanding the integration of a while loop and try-catch. I want to create my own exception class, then throw an exception from a method. I'd like to give the user several attempts to input valid data.

Basically:

conditions for while loop

attempts = 0
boolean done = false

while (tries < 10 && !done)
try
{
block of code
throw new Exception
}
catch (exception)
}

I cant seem to get the counter placed correctly.

Any suggestions appreciated.
 
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
could you add a little more code to see if you're getting any desired behavior? it's hard to tell with what you have.
 
Lawton Garvin
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here you are......please let me know if this is enough. Basically, a method to make a move in a game of tic tac toe:





Edit by mw: Added Code Tags.
[ April 12, 2008: Message edited by: marc weber ]
 
Marshal
Posts: 80763
488
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Where are you setting done to true? You can probably lose all references to moves if you get "done" updated correctly.
Please confirm that the starting state for each square is " ".
I would suggest you change your System.out.print . . . \n calls to System.out.printf . . . %n
Find out about formatted printing in the Java™ Tutorials.

All those errors are minor errors; just looking at your method and the try-catch it looks otherwise all right to me.

BUT . . .

You don't have a return value in that method; I presume you intended to return "done". That is a major error; it will prevent your method from compiling
[ April 12, 2008: Message edited by: Campbell Ritchie ]
 
Lawton Garvin
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
First, thanks for the reply.

And, yes, the " " should denote an empty square on the board.

I hope my counter is in the right place to increment every attempt to enter
a valid row/column selection.

Not sure where to put done.......that is the big stumbling block; but I know it has to be there to satisfy the second condition of the while loop.
 
f. nikita thomas
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Lawton Garvin:
Here you are......please let me know if this is enough. Basically, a method to make a move in a game of tic tac toe:


should this be void? if so then "done" has done its job...
[ April 12, 2008: Message edited by: f. nikita thomas ]
 
Lawton Garvin
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Nikita,

I am a rank novice. I know that void in the class statement means that a return value is not required (I think). But, I also think that the boolean done, as part of a while loop, sets up the conditions for a true value in the method code. If I start with the default boolean value (false), and then later in the block change done to (true) then I have a way out of the loop....which then allows the code for the remainder of the class to operate. Am I on the right path of thinking here?

Thanks.
 
f. nikita thomas
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
you have (2) ways out of the loop. you're correct about void not returning a value. also if you look at where your code will continue without problems that maybe a place to look to set the boolean ...
[ April 12, 2008: Message edited by: f. nikita thomas ]
 
Lawton Garvin
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
So, maybe......

 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Not to show any disrespect for the folks who have brought you this far in this discussion, but...

This is not what exceptions are for, and that's the first thing that people should have told you.

Here's what exceptions are for:

Imagine that there's some code in method A, which wants to query a database. So you call Database.sendQuery(), which calls connectToDatabase(), which calls new NetworkConnection(), which calls getDatabaseServerHostAddress(), which calls calls InternetAddress().lookupByHostName(), which determines that the server name is "TODO -- NEED TO FILL THIS IN LATER". What should lookupByHostName() do? It can't print an error message, because it has no idea if method "A" (remember method "A"?) is part of a GUI program, or Web program, or command-line program. But it can't return an address, since it doesn't have good data.

There are two choices for what it can do: first, it could return a special value, like 'null', to indicate failure. That means every one of the methods above has to check for special error values to indicate failure. That's a lot of checking!

The other choice is to throw an exception, which leaves the method and causes getDatabaseServerHostAddress() to exit, and new NetworkConnection() to exit, and connectToDatabase() to exit, and so on, until we get to method "A", which can catch the exception and learn that the host address is bad. Method "a" knows how to tell the user about the problem.

The important thing about this scenario is that one method throws an exception, and some other method -- often a method way up the call stack -- catches it.

You never throw an exception and catch it in the same method. It's slow, inefficient, and messy. Instead, just use the control structures that Java offers. The "continue" statement skips to the next iteration of a loop; that's exactly what you need here. So...



By the way, the method call "System.exit(0)" will end your program.
 
Campbell Ritchie
Marshal
Posts: 80763
488
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Ernest Friedman-Hill:
This is not what exceptions are for, and that's the first thing that people should have told you.

I shoul dhave seen that, shouldn't I?

 
Lawton Garvin
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes! I absolutely understand your point; my textbook, upon closer reading, makes the same point. I have been throwing and catching within the method; I need to throw from one method, catch in another (in this case the main method) to give the user an opportunity to correct the invalid input.

Many thanks.....
 
Ranch Hand
Posts: 3389
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That's a very beautiful explanation EFH . Of course, we can deal with the exception in the same class for a small ordinary program wherein it itself acts as a client to the specific method. Does that make sense?

Campbell, perhaps we may look at one perspective while leaving some traces for improvements and thats where our sheriffs/bartenders come in

Thank you EFH.
 
Campbell Ritchie
Marshal
Posts: 80763
488
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Actually, what EFH points out is that you can simply use an if block, and go round the loop again if there is invalid input. You just print an error message, set "done" to false, and go round again.
You can probably get rid of the counting of tries; when you set done = true then the loop can finish. You can dispense with throwing exceptions altogether.

----------------------------------------------------------------------------

There is an alternative; give the method a boolean return and return done at the end. The calling method can use the return value to confirm the number has been entered correctly, or it can ignore it. That is for the calling method to decide.
 
Campbell Ritchie
Marshal
Posts: 80763
488
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Oh, I didn't notice there was a rule about invalid moves. If you have that rule, then you can't get rid of the move counting.
 
Lawton Garvin
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Oh, I didn't notice there was a rule about invalid moves. If you have that rule, then you can't get rid of the move counting.



Our instructions for this assignment include the requirement that we give the user three tries for valid input.

So, we have to catch and throw an exception, using the try-catch, and we have to set up the program to give the user three tries.

If she had asked me to catch and throw, I might have been able to do that.

If she had asked me to give the user three tries (using a while loop), I might have been able to do that.

Combining the two taxed my still very young Java brain.

Thanks to all.
 
Campbell Ritchie
Marshal
Posts: 80763
488
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Were you instructed to use exceptions in the case of invalid input?

Suggest:
  • 1: Set up a method which asks the user to call a number.
  • In that method set up a for loop. If you have a specified number of tries, a for loop (counter-controlled repetition) is probably appopriate.
  • In that loop, set up a try-catch(BadMoveException)
  • In the try, call the method which asks the user to input a number.
  • In that method, set up a while(!done) loop containing a try-catch(NumberFormatException)
  • You now have all the parts of your original method, but with the try-catch blocks spread out.
  • If you use a java.util.Scanner to read the numbers input, it throws a different exception: look for InputMismatchException instead of NumberFormatException
  • I hope that helps you CR
     
    reply
      Bookmark Topic Watch Topic
    • New Topic