简体   繁体   中英

How do I change the type of number? Double to int

When I run this program, I need the part where it says example " cans needed 3.0" I need it to only say the integer.

public class PaintEstimator {
    public static void main(String[] args) {

        // Create the Scanner object scnr
        Scanner scnr = new Scanner(System.in);

        // Declare the identifiers
        double wallHeight;
        double wallWidth;
        double wallAera;
        double gallonPaint = 350;
        int paintNeeded;

        // Prompt user for and input wall's height and width; and then display them
        System.out.println("Enter wall height (feet) :");
        wallHeight = scnr.nextInt();
        System.out.println("Enter wall width (feet) :");
        wallWidth = scnr.nextInt();
        System.out.println("Wall height is: " + wallHeight + " and Wall width is: " + wallWidth);

        // Calculate and output wall area
        wallAera = wallHeight * wallWidth;
        System.out.println("Wall area: " + wallAera + "square feet");

        // Calculate and output the amount of paint in gallons needed to paint the wall
        System.out.println("Paint needed: " + (wallAera / gallonPaint) + " gallons");


        // Calculate and output the number of 1 gallon cans needed to paint the wall, rounded up to nearest integer


        System.out.println("Cans needed: " + Math.ceil(wallAera / gallonPaint) + " can ( s )");

        // Calculate and output the cost of painting the wall.
        double costPaint = Math.ceil(wallAera / gallonPaint) * 45.0;
        System.out.println("Cost to paint the wall: $" + costPaint);
    }
}

您可以像已经在做的那样舍入/限制它,然后将其转换为 int:

System.out.println("Cans needed: " + (int) Math.ceil(wallAera / gallonPaint) + " can ( s )");

There are 3 basic methods for change a double to an integer.

Where var-name is an integer and var-name1 is a double.

Method 1: Type-casting

Example:

int var-name = (int) var-name1;

Method 2: Rounding

Example:

int var-name = Math.round(var-name1);

Method 3: Double.intValue

Example:

int var-name = Double.intValue(var-name1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM