java - “类型不匹配:无法从 double 转换为 int 错误”
问题描述
import java.util.Scanner;
public class PaintCostCalculator {
public static void main( String args[] )
{
try (Scanner input = new Scanner(System.in)) {
//variable declarations
int NoOfRooms;
int RoomCounter;
int choice;
int Area = 0;
int AreaSum = 0;
int TotalLSCost;
int TotalSGCost;
int TotalMatCost;
//constants declarations
final int PaintCoverage = 16;
final int LowSheenCost = 17.6;
final int SemiGlossCost = 20;
final int MatteCost = 14.3;
//code
System.out.print("Please enter the number of rooms to be painted: ");
NoOfRooms = input.nextInt();
for(RoomCounter = 0; RoomCounter < NoOfRooms; RoomCounter ++) {
System.out.printf("\nEnter the area of room %d in m^2.: ", RoomCounter + 1);
Area = input.nextInt();
AreaSum = AreaSum + Area;
}
System.out.println("\nPlease choose one of the following paint options: \n1. Low Sheen($17.60/L)\n2. Semi Gloss($20/L)\n3. Matte($14.30/L)");
choice = input.nextInt();
switch (choice)
{
case 1:
System.out.print("You have chosen Low Sheen\n");
TotalLSCost = (AreaSum / PaintCoverage) * LowSheenCost;
System.out.printf("To paint a total area of %dm^2 with Low Sheen paint it would cost a total of %d", AreaSum, TotalLSCost);
break;
case 2:
System.out.print("You have chosen Semi Gloss\n");
TotalSGCost = (AreaSum / PaintCoverage) * SemiGlossCost;
System.out.printf("To paint a total area of %dm^2 with Semi Gloss paint it would cost a total of %d", AreaSum, TotalSGCost);
break;
case 3:
System.out.print("You have chosen Matte\n");
TotalMatCost = (AreaSum / PaintCoverage) * MatteCost;
System.out.printf("To paint a total area of %dm^2 with Matte paint it would cost a total of %d", AreaSum, TotalMatCost);
break;
}
}
}
}
我仍处于 Java 的早期学习阶段,它是我的第一语言,尝试执行程序任务。简单的程序询问用户房间的数量,每个房间的面积比提供 3 种油漆选项的选择,它将计算要油漆的总面积和所需的油漆价格。我收到错误:
类型不匹配:无法从 double 转换为 int
解决方案
final int LowSheenCost = 17.6;
17.6
是一个双重文字:它有一个整数部分和一个小数部分。您不能将其放入期望整数的变量中。
反而:
final double LowSheenCost = 17.6;
(对其他人也是如此)。
一个小问题是:
final int PaintCoverage = 16;
有效;但它可能会在以后给你意想不到的结果,因为这样:
(AreaSum / PaintCoverage)
在
TotalLSCost = (AreaSum / PaintCoverage) * LowSheenCost;
是整数除法,即除法只能得到整数结果:如果是|AreaSum| < 16
,则其值为零;如果16 <= AreaSum < 32
,它的值将是一个等。
因此,如果您打算进行分数除法,也请使用PaintCoverage
adouble
而不是 an 。int
推荐阅读
- terraform - Terraform For 循环从地图生成 JSON
- android - Android Picasso 将之前加载的图片设置为占位符
- elasticsearch - Elasticsearch 服务器超时
- angular - 在两个日期之间查询在 MongoDB 中返回不正确的结果?
- python - 如何从 python 代码写入 .env 文件
- django - 表格(前缀=)和比赛条件
- c# - 如何处理多个对象共享的数据
- spring-boot - 如何使用 mockito 模拟方法?
- reactjs - 替换 React 组件 onClick
- python - 致命错误 LNK1181:安装 matplotlib==3.0.3 时无法打开输入文件“png.lib”