1

Below is the code, when i divide 5/6,it shows 0.0 output rather 0.8333.

package sunday;

import java.util.Scanner;

public class exception {
    public static void main(String[] args) {
        int donut,milk;
        double donutperglass;
        Scanner in=new Scanner(System.in);
        try{
            System.out.println("enter donut");
            donut=in.nextInt();
            System.out.println("enter milk");
            milk=in.nextInt();

            if(milk<1)
                throw new Exception("no milk");

            donutperglass=donut/milk;
            System.out.println(donutperglass);
        }catch(Exception e){
            System.out.println(e.getMessage());
            System.out.println("go buy some milk");
        }
        System.out.println("end");
        // TODO Auto-generated method stub    
    }    
}

4 Answers4

3

Change the data types of donut and milk to double.

So that it will return the double value instead of int.

See this question for more details

Integer division: How do you produce a double?

Community
  • 1
  • 1
smali
  • 4,687
  • 7
  • 38
  • 60
0

Declare donut and milk as double type too if you want double type dounutperglass after division.

CodeNewbie
  • 2,003
  • 16
  • 29
0

Data type should be changed to double.

Reason : int cannot hold the floating values.

int/int gives int only. Change the data types of donut and milk to double.

double/double gives you the exact result

Vinay Veluri
  • 6,671
  • 5
  • 32
  • 56
0

You must cast one of the terms to a floating point value, instead of int.

By example:

donutperglass=((double) donut)/milk;