我是编程的新手,我有一些错误。我在Java中构建代码时出现此错误,它与int和double有关。 这是我的代码:
import java.util.Scanner;
import java.text.DecimalFormat;
public class Overloader
{
public static void main(String[] args)
{
Scanner k1 = new Scanner(System.in);
double selection = 0, radius, height;
do
{
System.out.println("Select the options from [1-3]");
System.out.println("1- Volume of the Cylinder");
System.out.println("2- Volume of the Sphere");
System.out.println("3- Exit");
selection = k1.nextDouble();
switch (selection)
{
case 1:
System.out.print("Enter radius: ");
radius = k1.nextDouble();
System.out.print("Enter height: ");
height = k1.nextDouble();
System.out.printf("Volume = %10.3f%n", getVolume(radius, height));
break;
case 2:
System.out.print("Enter radius: ");
radius = k1.nextDouble();
System.out.printf("Volume = %10.3f%n", getVolume(radius));
break;
case 3:
System.exit(0);
default:
System.out.println("Incorr... choice!");
} // end switch
} while (selection != 3);
}
public static double getVolume(double radius, double height)
{
return Math.PI * radius * radius * height;
}
public static double getVolume(double radius)
{
return (4.0 / 3.0) * Math.PI * Math.pow(radius, 3);
}
}
调试器说:
switch (selection) {
^
required: int
found: double
1 error
Process completed.
请帮忙,我很感激。 非常感谢你。
答案 0 :(得分:3)
开关不能基于double或float。 根据数据范围,您可能需要替换
selection = k1.nextDouble();
与
selection = k1.nextInt;
(选择被宣布为int,由Ingo提出)
答案 1 :(得分:1)
你无法打开双倍。您可以参考the language specification #14.11:
Expression的类型必须是char,byte,short,int,Character,Byte,Short,Integer,String或枚举类型(第8.9节),否则会发生编译时错误。
在你的情况下,你期望一个int,所以只需使用:
int selection = k1.nextInt();