Reputation: 1
I'm trying to make a try/catch program calculator that removes the following errors but it isn't working. Please tell me what I'm doing wrong. I'm supposed to test for illegal operand operations and division by zero.
do // do while is for many operations
{
try
{
System.out.println("Enter num1 and num2 : ");
int num1 = new Scanner();
int num2 = new Scanner();
System.out.println("Enter sign : ");
char sign = new Scanner();
}
catch(IllegalArgumentException ex) // This will check for illegal inputs
{
System.out.println(ex.Message()); //Will print error message
}
if(sign == '+')
{ // part of code where you will write the plus operation
System.out.println(num1+num2);
}
if(sign == '-')
{
System.out.println(num1-num2);
}
if(sign == '*')
{
System.out.println(num1*num2);
}
if(sign == '/')
{
try
{
System.out.println(num1/num2);
}
catch(ArithmeticException ex)// Check for divide by zero exception
{
System.out.println("Divide by zero");
}
}
if(sign == 'x') // to exit
{
flag = false
}
else
{
System.out.println("Error : Unknown Operator\n");
}
}while(flag == true) // flag will be true until user enters 'x' as the choice to exit.
Upvotes: 0
Views: 7736
Reputation: 106528
First, and probably more pressing, your code has some glaring syntax issues. It was mentioned before that certain statements won't even compile - int num1 = new Scanner()
is inappropriate because an int
is not an object, and an empty constructor isn't one of the choices for a new Scanner
.
Second, and probably the most important, your program has a rigid, linear flow to it. Suppose I only want to add two numbers. Well, I'm out of luck, since I have to go through and add, subtract, multiply, and divide numbers every time.
In this instance, it is very important that you reasonably scope out your code. Use methods to accomplish this.
public Long add(Long value1, Long value2) {
return value1 + value2;
}
// and so forth
Whenever you want to do a specific operation, you can do so by capturing input - either from the word "add", a text-based menu (enter 1 for addition), or some other way.
As for division by zero, you do not use a try...catch
block. Typically you do this around code you don't want to break, so it'd be useful in a division method, or when you attempt to divide.
public Long divide(Long value1, Long value2) throws ArithmeticException {
return value1 / value2;
}
When you go to use that method, you would want:
Long a = new Long(300);
Long b = new Long(0);
try {
divide(a, b);
} except(ArithmeticException, ae) {
System.out.println("Can't divide by zero");
}
I leave the overall flow and building of the project to you, but this should give you a good start.
Upvotes: 0
Reputation: 51965
You're assigning a Scanner object to an int variable, not going to compile.
What you're looking for is:
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
I suggest you read the Scanner docs: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html
Upvotes: 4