Results 1 to 6 of 6

Thread: JAVA - try/catch in do-while

  1. #1
    Banned
    Join Date
    Aug 2001
    Location
    Yes
    Posts
    4,424

    JAVA - try/catch in do-while

    I have a JAVA question...

    I can't figure out how to combine a try/catch block with a do-while loop... I have a user input prompt (where the user is supposed to enter a number); if the user doesn't enter a number (but a letter, for example, instead), the catch block catches it, but I need it to repeat the request for that number input - I can't get it figured out, and ... I tried doing it in C# because I thought how to do it there, but I can't figure that out either anymore Now I'm not even sure anymore if a do-while is the right way to go...

    Here's the code I'm talking about

    Code:
    String inputString1; // The number entered
    int number1 = 0; // The input will be parsed as int
    	
    	
    BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in)); 
    	
    	
    		try
    		{
    		System.out.print("Please enter the first number: "); // User prompt for the first number
    		inputString1 = br1.readLine(); // User input first number
    		number1 = Integer.parseInt(inputString1); // User's input parsed as an integer
    		}
    		catch(NumberFormatException n)
    		{
    			
    			System.out.print("You must enter a number!");
    		}
    In addition to displaying that "You must enter a number!" message, it should ask the user again to input that first number... I've tried the following (and a bunch of other possibilities), but it doesn't work...

    Code:
    do
    		{
    		try
    		{
    		System.out.print("Please enter the first number: "); // User prompt for the first number
    		inputString1 = br1.readLine(); // User input first number
    		number1 = Integer.parseInt(inputString1); // User's input parsed as an integer
    		}
    		catch(NumberFormatException n)
    		{
    			
    			System.out.print("You must enter a number!  Value initialized to zero!\n ");
    		}
    		}
    		while(false);
    Any suggestions?

  2. #2
    Senior Member
    Join Date
    Mar 2004
    Posts
    557
    Hi

    Havent' done Java since years, so I write down something in C#, which should do what
    you want (and can be compiled)
    Code:
            bool done = false;
            while (!done){
       	             try
    		    {
                         done = true;
    	             System.Console.WriteLine("Please enter the first number: "); // User prompt for the first number
                         inputString1=System.Console.ReadLine(); // User input first number
    		     number1 = Int32.Parse(inputString1);
    		    }
    		     catch(FormatException e)
    		    {
        			
    			  System.Console.WriteLine("You must enter a number!");
                              done = false;
                }
            }

    So the corresponding java code might be (not sure whether this can be compiled)
    Code:
    boolean done = false;
             do
    	 {
    		try
    		{
                      done=true;
    		  System.out.print("Please enter the first number: "); // User prompt for the first number
    		  inputString1 = br1.readLine(); // User input first number
    		  number1 = Integer.parseInt(inputString1); // User's input parsed as an integer
    		}
    		  catch(NumberFormatException n)
    		{
    			
    			System.out.print("You must enter a number!  Value initialized to zero!\n ");
                            done=false;
    		}
    	}
    	while(not done);

    Cheers
    If the only tool you have is a hammer, you tend to see every problem as a nail.
    (Abraham Maslow, Psychologist, 1908-70)

  3. #3
    Senior Member mungyun's Avatar
    Join Date
    Apr 2004
    Location
    Illinois
    Posts
    172
    Well, I'm not sure if these will come to any help but here are some code snippits I have used for school projects. They are along the lines of what you are looking for so I hope they help. But they are for for validating numerical input in a JTextField.

    The first one is just a keylistner input verification.

    Code:
     
    
     keyText.addKeyListener(new KeyAdapter() {
        public void keyTyped(KeyEvent e) {
          char c = e.getKeyChar();      
          if (!((Character.isDigit(c) ||
             (c == KeyEvent.VK_BACK_SPACE) ||
             (c == KeyEvent.VK_DELETE))) {
            getToolkit().beep();
            e.consume();
          }
        }
      });
    Here is a quote from the sun java developer site that talks about this key listner method.

    There's a special consideration in using a key listener if you are working in an environment where you need to install an input method listener. In this case, the input method listener will disable the ability to capture keystrokes with a key listener. This usually happens when there are not enough keyboard keys to map to input characters. An example of this is accepting Chinese or Japanese characters as input.
    And, If you have swing you can do input validation this way which beeps on invalid input.

    Code:
    inputText.setInputVerifier(new InputVerifier() {
        public boolean verify(JComponent comp) {
          boolean returnValue = true;
          JTextField textField = (JTextField)comp;
          String content = textField.getText();
          if (content.length() != 0) {
            try {
              Integer.parseInt(textField.getText());
            } catch (NumberFormatException e) {
              returnValue = false;
            }
          }
          return returnValue;
        }
        public boolean shouldYieldFocus(JComponent input) {
          boolean valid = super.shouldYieldFocus(input);
          if (!valid) {
            getToolkit().beep();
          }
          return valid;
        }
      });
    Once again, these are for the jtextfield. I am not sure on how to do the above with system in and out. Maybe you can create a popup that has an input field?

    Hopefully this at least helps some.
    I believe in making the world safe for our children, but not our children’s children, because I don’t think children should be having sex. -- Jack Handey

  4. #4
    Banned
    Join Date
    Aug 2001
    Location
    Yes
    Posts
    4,424
    sec_ware > Thanks! That's the (C#) code I was thinking of!

    It seems like the problem in Java, though (from what I found after I posted), is that "[t]he code that caused the exception is never resumed." (http://java.sun.com/docs/books/jls/s...tions.doc.html).

    That's what I've been suspecting for a while... the way I have it set up, every time the code throws an exception, the program just ends (because it doesn't return control to the code that threw that exception)...

    The Java code you have compiles just fine, but doesn't do what I need because as soon as the exception is thrown, the whole thing just aborts... I was hoping a "return" statement would fix that, but it doesn't.

    I keep reading that exception handling should be a last resort (since all those exceptions can be prevented with code validation), so I'm going to have to read into that...

  5. #5
    Banned
    Join Date
    Aug 2001
    Location
    Yes
    Posts
    4,424
    mungyun > Thanks! I see some code in your post that I'm going to have to experiment with!

  6. #6
    Senior Member mungyun's Avatar
    Join Date
    Apr 2004
    Location
    Illinois
    Posts
    172
    Cool. If you have any luck, let me know. I'd be interested in what you end up doing.
    I believe in making the world safe for our children, but not our children’s children, because I don’t think children should be having sex. -- Jack Handey

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •