This week's book giveaway is in the Jython/Python forum.
We're giving away four copies of Murach's Python Programming and have Michael Urban and Joel Murach on-line!
See this thread for details.
Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

try catch using JOptionPane  RSS feed

 
Jenn Tran
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all, I'm new in programming, so please help . my program is running but I am trying to add the 'try catch' to catch the invalid input for direction from user. how do I do this ? I am not familar with try-catch at all, so I dont know what to do. thanks


 
Campbell Ritchie
Sheriff
Posts: 53773
127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

I have added code tags to your post, removed some of the unnecessary empty lines and broken the last line because it was too long. Doesn't it look better You can see how to break the long line, too.

Why are you using option pane in the first place? It is very old‑fashioned programming style. I would suggest you don't use try‑catch otherwise the method, which is already too long, will become even longer. You should have methods which gets input from the keyboard, e.g. getNextInt. I would suggest you should use a Scanner. This is how you could write a getNextInt method, assuming inScan is a Scanner pointing to System.in.
Sanner inScan = new Scanner(System.in); ...Rob Spoor taught me that technique years ago. There is no risk of an Exception.
You can swap lines 6 and 7 if you wish.

You can read all about Exceptions in the Java™ Tutorials.
 
Jenn Tran
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
it is 1 of the requirement that I have to use JOptionPane. so how would I do that and where would I put the try catch in? thanks
 
Simon Roberts
Author
Ranch Hand
Posts: 176
9
Java Linux Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
try catch is for exception handling. It's not really for handling errant user input (which I rather assume is what you're trying to do)

i believe that all you should be doing is having a final "else" (not else if) on the end of your input tests (where you're testing for North, South, etc.

But I might be missing the point of your program.

Regardless, until an exception is thrown, try/catch isn't going to do anything for you.
 
Campbell Ritchie
Sheriff
Posts: 53773
127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You won't get any Exceptions from option pane itself. The only Exceptions likely are:-
  • If the user clicks the cancel button the input is liable to be null, so you may suffer an NPE.
  • If you want numeric input and the text is not in the correct format you suffer a number format exception.
  • Neither of those is really associated with the option pane. Both are avoidable. You can avoid nulls by wrapping the call in a loop: example:-You can avoid number format exceptions with a Scanner:-The additional {} are there to limit the scope of the Scanner local variable.
     
    Campbell Ritchie
    Sheriff
    Posts: 53773
    127
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Jenn Tran wrote:. . . I have to use JOptionPane. . . .
    Option Pane went out of common use for keyboard input when Scanner was introduced in 2004. I am surprised that such old‑fashioned style should be a requirement.
     
    Simon Roberts
    Author
    Ranch Hand
    Posts: 176
    9
    Java Linux Netbeans IDE
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Option Pane went out of common use for keyboard input when Scanner was introduced in 2004. I am surprised that such old‑fashioned style should be a requirement.


    I think I'm missing your point Campbell, but JOptionPane is a GUI component, and Scanner works with character streams. Those are completely different problems, so while one might use both in the same program, and it's by no means unreasonable to suggest processing input from a GUI using a Scanner, I don't think that Scanner replaces any Swing GUI component, nor obsoletes JOptionPane; you still have to get the text from the user for the Scanner to parse it, and it's still going to be possible--given free form input--for the user to type "Banana" when you prompt them for a number, no?

    Perhaps I'm still suffering from tl;dr

     
    Campbell Ritchie
    Sheriff
    Posts: 53773
    127
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I said that Scanner superseded option pane for keyboard input. Not for anything else. If you use an input dialogue, you get a String which needs parsing. If you use a Scanner to get keyboard input, you can get the Scanner object to do the parsing for you.

    You can even write Apple when prompted for a number but a technique similar to what I showed earlier prompts you for new input if something which is not a number is written.
     
    Brett Spell
    Ranch Hand
    Posts: 118
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Campbell Ritchie wrote:I said that Scanner superseded option pane for keyboard input.


    That's not correct either. As Simon pointed out, one prompts the user for input through a UI (Swing) and the other doesn't. It's feasible that JOptionPane might be used to retrieve the raw input and then Scanner to parse it, but one wouldn't use Scanner in a GUI application as a substitute for JOptionPane.
     
    Brett Spell
    Ranch Hand
    Posts: 118
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Jenn Tran wrote:it is 1 of the requirement that I have to use JOptionPane. so how would I do that and where would I put the try catch in? thanks


    As Simon already pointed out, it's not really necessary to use an exception in this code to handle invalid input. In fact, doing so would arguably make that code a bit less readable than it is now, but I'm guessing that using an exception is also part of your assignment. Assuming that's the case, consider splitting the prompting, retrieval, and validation of the direction text out into its own method and call that method from your existing main() method. In other words, instead of putting everything in the main() method you'd create something like this:



    In other words, your method would be designed to either return a valid direction or throw an exception, and the code that calls the method could be wrapped in a try / catch, with the catch block handling the exception thrown when an invalid direction is entered. This would also facilitate expanding your code to display an error message and prompt the user repeatedly until they've entered a valid direction if that's also part of the assignment. Again, the extra method approach isn't strictly necessary to accomplish any of this, but it would make the code marginally easier to understand.

    P.S. You should also consider starting your variable names ("Mile", "Trip", etc.) with lower case letters. It'll work fine the way it is, but for some of us who've been working with Java for a while it's a little disconcerting to see variable names that start with an upper case letter because we normally expect only type (class) names to start with upper case.
     
    Liutauras Vilda
    Marshal
    Posts: 3820
    200
    BSD
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Brett Spell wrote:one wouldn't use Scanner in a GUI application as a substitute for JOptionPane
    OP not creating a GUI application, he is taking the keyboard input with GUI component (I wouldn't call it a GUI for application), what Campbell said it is a old fashioned way to do so, and I think he is right. Try imagine you have an application window, and for the input pops out another window for input, once you provide the input, you get another window (showMessageDialog) with "thanks for input" message, and then another cycle, maybe third and fourth.. And in this way you keep closing the pop up windows till you forget what have you been asked to do initially.

    [edit] but OP identified JOptionPane as one of his assignment requirement, so probably he has to follow it
     
    Brett Spell
    Ranch Hand
    Posts: 118
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Liutauras Vilda wrote:OP not creating a GUI application, he is taking the keyboard input with GUI component (I wouldn't call it a GUI for application)


    The application posted contains code to display an option pane, so by definition it is a GUI application.

    Liutauras Vilda wrote:Try imagine you have an application window, and for the input pops out another window for input...


    I'm not sure how your scenario is relevant since this isn't what the OP described or plans. But since we're speaking hypothetically, try imagining a Swing (or any other GUI) application that suddenly stops responding to the user because it's expecting them to enter text in a shell / DOS widow. Is that really something you'd advocate? If so, I'm guessing you don't do much desktop GUI development.

    JOptionPane hasn't been superseded by anything, certainly not Scanner, and in any case the OP said that using JOptionPane is a requirement. Writing a command line-based application would be a reasonable alternative to a GUI application for someone learning to write code, but that's not what's being discussed here.
     
    Campbell Ritchie
    Sheriff
    Posts: 53773
    127
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Brett Spell wrote:. . . That's not correct either. . . .
    I think we are actually saying the same thing but in such a way that we are confusing each other into thinking we disagree. When I said keyboard input I meant for a console application rather than a GUI.If that isn't crappy code my name isn't Campbell Ritchie.

    You have a 50/50 chance of getting the input from the text field or the option pane. You can use a Scanner to inspect whether the text has an int at its beginning and then parse it; “1234567890 Campbell” will evaluate as a valid int. You then have about 1μs to get the text into the text field before you get another error message because ***** isn't a number. You would often use something like this to get text into a number (or the parseInt method):-
    i = Integer.valueOf(myTextField.getText()).intValue();
    The method with a Scanner has the advantage that there is hardly any risk of Exceptions.
     
    Campbell Ritchie
    Sheriff
    Posts: 53773
    127
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Brett Spell wrote:. . . using JOptionPane is a requirement. . . .
    We know that, and have provided suggestions for code style which does use option pane. But you should regard option pane as obsolete for a command‑line application. The OP has been told something a bit like what I have never been told:-
    Fortunately, nobody ever wrote:Campbell, you need to go to London. You need to take the steam train to King's Cross.
    For any application which does not have a guaranteed console to provide input/output option pane remains in frequent use. If you have a non‑GUI app running from an executable .jar, option pane will probably be your favoured method for input and output.
     
    Liutauras Vilda
    Marshal
    Posts: 3820
    200
    BSD
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Back to OP's problem, Jenn, beside all what was mentioned, try to decompose your program to a smaller methods. At the moment you have 1 single method, which is "main" and it is meant to execute your program only. Beside that, it is quite difficult to follow the program flow.
    Try to move all program logic to other methods, even if methods would be very short, so your program could look similar to:

    In this way would be easier for yourself to debug program if needed and for your reader to understand your program flow.

    [edit] fixed typo
     
    Brett Spell
    Ranch Hand
    Posts: 118
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Campbell Ritchie wrote:you should regard option pane as obsolete for a command line application.
    ...
    If you have a non‑GUI app running from an executable .jar, option pane will probably be your favoured method for input and output.


    Using option pane isn't "obsolete" for a command line application because it never represented a command-line solution in the first place. Again, if you're advocating mixing command-line and GUI elements in a single application, I'm guessing that you haven't done much desktop development.
     
    Campbell Ritchie
    Sheriff
    Posts: 53773
    127
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    No, I haven't

    We seem to be in agreement that OP has unfortunately been required to use a less than optimal implementation.
     
    Brett Spell
    Ranch Hand
    Posts: 118
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Campbell Ritchie wrote:We seem to be in agreement that OP has unfortunately been required to use a less than optimal implementation.


    Yes, I agree that this isn't the way I'd want to start someone out who's trying to learn to code in Java. Having said that, though, it is arguably more satisfying to see "Hello, world!" pop up in a GUI (which is what most people think of as a software application) as opposed to the text appearing in a DOS window.
     
    Liutauras Vilda
    Marshal
    Posts: 3820
    200
    BSD
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Brett Spell wrote:which is what most people think of as a software application
    I have to admit agree with this point fully.
     
    Campbell Ritchie
    Sheriff
    Posts: 53773
    127
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Now, having "Hello, Brett" appear in an option pane would entail real OO programming
     
    Brett Spell
    Ranch Hand
    Posts: 118
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Campbell Ritchie wrote:Now, having "Hello, Brett" appear in an option pane would entail real OO programming


    A "Hello, Campbell!" would be at least as good.
     
    Jenn Tran
    Greenhorn
    Posts: 3
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    thank you all for your help. this assignment is already graded so I'm not cheating or anything , I just want to understand the concept so I can do better in the future. my TA doesnt have enough time to go over problem that already graded , so that is why I am here. once again, thank you for all your help.
     
    Campbell Ritchie
    Sheriff
    Posts: 53773
    127
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Brett Spell wrote:. . . A "Hello, Campbell!" would be at least as good.


    JN: you're welcome

    The way I would do it is to have a utility class. They have only static members and therefore never need instances. So you have a private constructor, and a field which is a Scanner. Never close a Scanner, Reader, etc pointing to System.in. Then you have methods with loops in; if you get wrong input you get an error message and “try again”:-Rob Spoor taught me how to write such loops.
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!