11 Replies - 1484 Views - Last Post: 14 July 2011 - 09:53 AM Rate Topic: -----

#1 petardfoozer  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 12-July 11

How can I loop out of my try/catch?

Posted 12 July 2011 - 05:05 PM

Hello everyone!

I'm new to Java, and I'm trying my luck at throwing exceptions!

What I've done is written a simple calculator with operators '+' '-' '*' '/', and integers as the operands.

What I'd like to do is catch exceptions from user input such as:

user entering anything but an integer for the operands,
user entering anything but operators for the operators.

I've used the InputMismatchException to catch the operands so far, but I'm not sure how to catch the operators.
Also, I'm not sure where my loop is supposed to go in order to get the program to restart once the exception is caught.

Here's my code.


import java.util.*;
import java.lang.*;

public class exception 
{
    //Main Method
    public static void main (String[] args) 
    throws InputMismatchException
    
    {
        int result = 0;
        int operand1 = 0;
        int operand2 = 0;
        String operator = " ";
        char op = ' ';
        
    
    {
            
        
        try{
                
            
        System.out.println("Usage: operand1 operator operand");
        System.out.println("    (operands are integers)");
        System.out.println("    (operators: + - * /)");
        Scanner in = new Scanner(System.in);
    
        
        operand1 = in.nextInt();
        operator = in.next();
        op = operator.charAt(0);
        operand2 = in.nextInt();
        
        switch (op)
        {
            case '+': result = operand1 + operand2;
                    break;
            
            case '-': result = operand1 - operand2;
                break;
            
            case '*': result = operand1 * operand2;
                break;
            
            case '/': result = operand1 / operand2;
                break;
            default : 
        }
        
        
        //Display result
        System.out.println("Answer: " + operand1 + ' ' + op + ' ' + operand2 + " = " + result);
        }
    
    
        catch(InputMismatchException e)
            {
                            System.err.println("Input error.  Must enter an integer.  Try Again.");
                            return;
                               
            }
    
        
        
        
        
    }

}
}





thanks for any help!!

Is This A Good Question/Topic? 0
  • +

Replies To: How can I loop out of my try/catch?

#2 smohd  Icon User is offline

  • Critical Section
  • member icon


Reputation: 1820
  • View blog
  • Posts: 4,627
  • Joined: 14-March 10

Re: How can I loop out of my try/catch?

Posted 12 July 2011 - 05:22 PM

Use the default block to catch the operator wrong input. That is when user enter other than what is in case throw exception in default.
You can put a while(true) out of try block and at the end of try block put break; means you exit the loop if all inputs are correct
Was This Post Helpful? 1
  • +
  • -

#3 code_m  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 24
  • View blog
  • Posts: 202
  • Joined: 21-April 09

Re: How can I loop out of my try/catch?

Posted 12 July 2011 - 05:22 PM

First you'll want to read some more on Exceptions... Java is pretty picky.

As far as your loop itself is concerned, you should make a boolean "continue" variable like this:
public static void main(String[] args) {
    boolean validInput = false;

    do {
        // Prompt the user for input
        try {
            // grab and convert the input here

            // put this line after lines that throw exceptions
            // so that it will only occur if nothing was thrown
            validInput = true;
        } catch (InputMismatchException ime) {
            // tell the user what went wrong
            // and give suggestions as how to correct it

            // be safe and set this to make sure the loop runs again
            validInput = false;
        }
    } while (validInput == false);

    // do calculations with the input you received and output results
}


Remember to declare all your variables on the lowest block level that you want to access it !

This post has been edited by code_m: 12 July 2011 - 05:24 PM

Was This Post Helpful? 1
  • +
  • -

#4 immeraufdemhund  Icon User is offline

  • D.I.C Regular

Reputation: 79
  • View blog
  • Posts: 495
  • Joined: 29-March 10

Re: How can I loop out of my try/catch?

Posted 12 July 2011 - 05:23 PM

well a few things that might help you out. You should make a few methods in your class. and it is also good practice to NOT put a bunch of code in your try/catch area. The reason being is that you don't want to guess as to what is the possible thing throwing the exception.

and also never make your main method throw an exception. Have it call other functions.


this code will not work by just copying it in, but gives you an idea of what do start with
public static void main(String[] args)
{
  Calculator myCalc = new Calculator();
  while (myCalc.KeepCalculating)
  {
     myCalc.PrintUsageText();
     int a = In.nextInt();  //use scanner to verify correct input
     char b = In.???nextChar()???;
     int c = In.netxtInt();
     myCalc.Calculate(a,b,c);
     boolean keepItUp = myCalc.AskToContinue();
     myCalc.setContinue(keepItUp);
  }
}
public class Calculator()
{
  public Calculator()
  {
    CONTINUE  = true;
    //set up your different variables and input and so forth
  }
  public String PrintUsageText()
  {
    System.out.println("Usage: operand1 operator operand");
    System.out.println("    (operands are integers)");
    System.out.println("    (operators: + - * /)");
  }
  public int calculate(int operand1, char operator, int operand2)
  {
  //do your math checking and return the result
  }
  public boolean KeepCalculating
  {
    return CONTINUE;
  }
  public void setContinue(boolean continue)
  {
     CONTINUE = continue;
  }
}


Was This Post Helpful? 1
  • +
  • -

#5 petardfoozer  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 12-July 11

Re: How can I loop out of my try/catch?

Posted 12 July 2011 - 05:59 PM

Thank you very much everyone!

I'll get to it and see what I come up with!
Was This Post Helpful? 0
  • +
  • -

#6 petardfoozer  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 12-July 11

Re: How can I loop out of my try/catch?

Posted 12 July 2011 - 06:08 PM

View Postsmohd, on 12 July 2011 - 05:22 PM, said:

Use the default block to catch the operator wrong input. That is when user enter other than what is in case throw exception in default.
You can put a while(true) out of try block and at the end of try block put break; means you exit the loop if all inputs are correct



ahhh should have thought about the default

so that would go

switch (op)
{
case
case
...
...

default:
}

but what do I put in for the default statements? Sorry, I'm just unsure of how to use it :(
Was This Post Helpful? 0
  • +
  • -

#7 smohd  Icon User is offline

  • Critical Section
  • member icon


Reputation: 1820
  • View blog
  • Posts: 4,627
  • Joined: 14-March 10

Re: How can I loop out of my try/catch?

Posted 12 July 2011 - 06:15 PM

Just throw a new exception like
 
while(true){
// you have your try here
try{
//codes
//..... follow switch
switch(op){ //at default
default:
 throw new InputMismatchException();
} //end switch

//at the end which means all accepted, no
break;
}//end try block
//catch....
}//end while 

This post has been edited by smohd: 12 July 2011 - 06:23 PM

Was This Post Helpful? 2
  • +
  • -

#8 petardfoozer  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 12-July 11

Re: How can I loop out of my try/catch?

Posted 12 July 2011 - 06:21 PM

View Postsmohd, on 12 July 2011 - 06:15 PM, said:

Just throw a new exception like
 
while(true){
// you have your try here
try{
//codes
//..... follow switch
switch(op){ //at default
default:
 throw new InputMismatchException;
} //end swithc

//at the end which means all accepted, no
break;
}//end try block
//catch....
}//end while 


awesome, thanks so much, really appreciated!
Was This Post Helpful? 0
  • +
  • -

#9 petardfoozer  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 12-July 11

Re: How can I loop out of my try/catch?

Posted 13 July 2011 - 05:22 AM

Hey guys!

Here's the working code with divide by zero handling, integer handling, and operator handling.

Again, thank you so much!

I had no idea that the exception handling was built in and I thought that all exceptions had to be specifically declared. So much easier to use the built ins!


import java.util.*;
import java.lang.*;



public class exception 
{
    //Main Method
    public static void main (String[] args) 
    throws InputMismatchException, ArithmeticException
    
    {
        int result = 0;
        int operand1 = 0;
        int operand2 = 0;
        String operator = " ";
        char op = ' ';
        
        boolean validInput = false;
    
    {
            
    	do {

        try{
                
            
        System.out.println("Usage: operand1 operator operand");
        System.out.println("    (operands are integers)");
        System.out.println("    (operators: + - * /)");
        Scanner in = new Scanner(System.in);
    
        
        operand1 = in.nextInt();
        operator = in.next();
        op = operator.charAt(0);
        operand2 = in.nextInt();
        
        switch (op)
        {
            case '+': result = operand1 + operand2;
                    break;
            
            case '-': result = operand1 - operand2;
                break;
            
            case '*': result = operand1 * operand2;
                break;
            
            case '/': result = operand1 / operand2;
                break;
            
            default : 
            	System.out.println("Invalid operator!.");
            	throw new InputMismatchException();
            	

            
        }
        
        
        //Display result
        System.out.println("Answer: " + operand1 + ' ' + op + ' ' + operand2 + " = " + result);
        
        validInput = true;

        }
    
    
        catch(InputMismatchException e)
            {
                            System.err.println("Input error. Try Again.");
                            
                               
                            validInput = false;

            }
        catch(ArithmeticException e)
        {
                        System.err.println("Are you trying to destroy the universe? Cannot divide by zero! ");
                        
                           
                        validInput = false;

        }
        
        
        	
    	}
    	while (validInput == false);
    }
    }
}



Was This Post Helpful? 0
  • +
  • -

#10 smohd  Icon User is offline

  • Critical Section
  • member icon


Reputation: 1820
  • View blog
  • Posts: 4,627
  • Joined: 14-March 10

Re: How can I loop out of my try/catch?

Posted 13 July 2011 - 05:29 AM

Glad you get it working ;) Except you dont need some of the variable any more: Look at this updated version where some variables removed(means save memory space):
import java.util.*;
// also no need to import java.lang, it is auto imported!
public class ExceptionTest {

    public static void main(String[] args) { // no need to throw exception in main, just catch  them
        int result = 0;
        int operand1 = 0;
        int operand2 = 0;
        String operator = " ";
        char op = ' ';
        Scanner in = new Scanner(System.in); //I declare it here, removed from loop

// I removed the boolean variable
        while (true) {
            try {

                System.out.println("Usage: operand1 operator operand");
                System.out.println("    (operands are integers)");
                System.out.println("    (operators: + - * /)");
                //Scanner in = new Scanner(System.in);


                operand1 = in.nextInt();
                operator = in.next();
                op = operator.charAt(0);
                operand2 = in.nextInt();

                switch (op) {
                    case '+':
                        result = operand1 + operand2;
                        break;

                    case '-':
                        result = operand1 - operand2;
                        break;

                    case '*':
                        result = operand1 * operand2;
                        break;

                    case '/':
                        result = operand1 / operand2;
                        break;

                    default:
                        System.out.println("Invalid operator!.");
                        throw new InputMismatchException();
                }

                //Display result
                System.out.println("Answer: " + operand1 + ' ' + op + ' ' + operand2 + " = " + result);

                break; // break means exit loop

            } catch (InputMismatchException e) {
                System.err.println("Input error. Try Again.");

            } catch (ArithmeticException e) {
                System.err.println("Are you trying to destroy the universe? Cannot divide by zero! ");

            }

        }
    }
}



You may look at my comments in the code for the changes

This post has been edited by smohd: 13 July 2011 - 06:00 AM

Was This Post Helpful? 0
  • +
  • -

#11 petardfoozer  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 12-July 11

Re: How can I loop out of my try/catch?

Posted 14 July 2011 - 05:05 AM

View Postsmohd, on 13 July 2011 - 05:29 AM, said:

Glad you get it working ;) Except you dont need some of the variable any more: Look at this updated version where some variables removed(means save memory space):
import java.util.*;
// also no need to import java.lang, it is auto imported!
public class ExceptionTest {

    public static void main(String[] args) { // no need to throw exception in main, just catch  them
        int result = 0;
        int operand1 = 0;
        int operand2 = 0;
        String operator = " ";
        char op = ' ';
        Scanner in = new Scanner(System.in); //I declare it here, removed from loop

// I removed the boolean variable
        while (true) {
            try {

                System.out.println("Usage: operand1 operator operand");
                System.out.println("    (operands are integers)");
                System.out.println("    (operators: + - * /)");
                //Scanner in = new Scanner(System.in);


                operand1 = in.nextInt();
                operator = in.next();
                op = operator.charAt(0);
                operand2 = in.nextInt();

                switch (op) {
                    case '+':
                        result = operand1 + operand2;
                        break;

                    case '-':
                        result = operand1 - operand2;
                        break;

                    case '*':
                        result = operand1 * operand2;
                        break;

                    case '/':
                        result = operand1 / operand2;
                        break;

                    default:
                        System.out.println("Invalid operator!.");
                        throw new InputMismatchException();
                }

                //Display result
                System.out.println("Answer: " + operand1 + ' ' + op + ' ' + operand2 + " = " + result);

                break; // break means exit loop

            } catch (InputMismatchException e) {
                System.err.println("Input error. Try Again.");

            } catch (ArithmeticException e) {
                System.err.println("Are you trying to destroy the universe? Cannot divide by zero! ");

            }

        }
    }
}



You may look at my comments in the code for the changes



So the boolean is just adding more too it where as the whileloop can do the same job with less memory usage?

thanks!

EDIT: Oh also, why don't I HAVE to use the throws for the exceptions? I thought in order to catch exceptions you had to have a THROWS and a TRY

This post has been edited by petardfoozer: 14 July 2011 - 05:07 AM

Was This Post Helpful? 0
  • +
  • -

#12 smohd  Icon User is offline

  • Critical Section
  • member icon


Reputation: 1820
  • View blog
  • Posts: 4,627
  • Joined: 14-March 10

Re: How can I loop out of my try/catch?

Posted 14 July 2011 - 09:53 AM

Quote

Oh also, why don't I HAVE to use the throws for the exceptions? I thought in order to catch exceptions you had to have a THROWS and a TRY

When you throw exception in a method, means you want them to be caught by the method which called it or to be thrown by it to another caller method. But the main() is the super-caller so no need to throw exception in it, just catch them> Glad this will help for the least which I understand about catching and throwing of exception...For more you may look at sun`s doc or some java experts will explain more
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1