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!

tried throwing the exception if newb = 0?

In the Java Language Specification I read the following:

"The result of a floating-point division is determined by the specification of IEEE arithmetic:"
...
"Division of a nonzero finite value by a zero results in a signed infinity."

(Source: JLS - 15.17.2 Division Operator)

Ok, now I've got it! I perform the division with both numbers been integers and I get the ArithmeticException as I want it! Thank you very much!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.