JAVA错误: Utilizing Switch Statements

标签 java

我是编程新手,有一些错误。当我用 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.

请帮忙,我将不胜感激。 非常感谢。

最佳答案

开关不能基于 double 型或浮点型。 根据数据范围,你可能需要替换

selection = k1.nextDouble();

selection = k1.nextInt;

(并且选择被声明为 int,由 Ingo 指定)

关于JAVA错误: Utilizing Switch Statements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23472311/

相关文章:

java - TestNG 中每个测试有多个数据提供者

java - 在第一次测试失败时中断测试类

Javax.persistence 与 @Entity bean 将 int[] 保存为 bytea (postgres)

java - 为什么 "Run as jUnit Test"没有出现在 Eclipse 中的现有类中?

java - 将数字字符串格式化为十进制

java - 使用运行时 Java 在 linux 中执行命令不工作返回代码不是 0

javascript - Struts 2 表单在不使用索引的情况下将参数绑定(bind)到集合

java - 如何设置java库路径进行处理

java - 如何在不删除配置单元表的情况下基于 DataFrame 从 SparkSQL 更改表,如删除/添加列?

java - 计算项目的出现次数