Hi! I'm having a project where I must give 2 integers and divide them. I must use the NumberFormatException to make sure that those two numbers are only integers( and display a message when they aren't) and the ArithmeticException to make sure that the can be divided (and display amessage when the denominator is equal to zero.Here's the code that I've written:
import java.util.Scanner;
import java.lang.*;
public class Division{
public static void main(String[] args){
Scanner input=new Scanner(System.in);
System.out.println("Enter first number:");
String number1=input.nextLine();
try{
int a=Integer.parseInt(number1);}
catch(NumberFormatException nfe){
System.out.println("Must enter an integer!");
return;}
System.out.println("Enter second number:");
String number2=input.nextLine();
try{
int b=Integer.parseInt(number2);}
catch(NumberFormatException nfe){
System.out.println("Must enter an integer!");
return;}
try{
int a=Integer.parseInt(number1);
int b=Integer.parseInt(number2);
double newa=(double)a;
double newb=(double)b;
double division=newa/newb;
System.out.println("Division outcome:"+division);}
catch(ArithmeticException DivZero){
System.out.println("Cannot divide by zero!");}
}
}
My programm works fine when the two numbers are integers, as well as when one of them isn't. But when a give a value of zero for b-the denominator, instead of getting the 'Cannot divide by zero", I get the Division outcome:infinity...
Can anyone please help me? I can't figure out what I'm doing wrong!