使用开关/外壳时无效的常量字符?

时间:2017-09-06 15:24:03

标签: java switch-statement case

我似乎无法使我的代码正常工作。我需要找到方形的区域,并根据用户使用的英寸,米为米,厘米为厘米,英尺为英尺,添加测量单位。

public static void main (String[] args)
{

// create scanner to read the input

        Scanner sc = new Scanner(System.in);

//prompt the user to enter one side of the length

       System.out.println("Enter one side of lenght of the square:");

        double side1 = sc.nextDouble();

        while (side1 < 0)

        {
//prompt the user to enter the input again in a positive value

            System.out.println("Error, No Negative Number. Enter again:");

            side1 = sc.nextDouble();
        }
char unitsMeasurement;
// prompt the user to enter the measurement unit
char units = Character.toUpperCase(status.charAt(0));
String unitsMeasurement = "";

    **{
        switch(units)
        {
        case "in":
            unitsMeasurement = "inch"; break;
        case "cm":
            unitsMeasurement = "centimeter"; break;
        case "ft":
            unitsMeasurement = "feet"; break;
        case "m":
             unitsMeasurement = "meter"; break;

        default:System.out.println("Invaild unit"); break;
                         }**


//Area of Square = side*side

          double area = side1*side1; 


        **System.out.println("Area of Square is: "+area, +unitsMeasurement+);**

      }

    }
}

1 个答案:

答案 0 :(得分:1)

您的主要问题是,您在char上使用了switch-case语句,而所有案例都基于String。这并不是一起工作的。 其他一些问题是status从未定义,因此units根本无法获得价值。

我不太确定你想要实现的目标,但我假设如下: 用户输入具有单位(缩写)的正方形的长度。程序计算方块的面积并将其与单位(未缩写)一起输出。

示例输入:

5cm

示例输出:

Area of square is: 25 centimeter^2

请记住,某个区域的长度为平方单位!

基于此,这里有一些工作代码:

public static void main (String[] args) {

    // create scanner to read the input
    Scanner sc = new Scanner(System.in);

    //prompt the user to enter one side of the length
    System.out.println("Enter one side of lenght of the square:");
    String input = sc.nextLine();

    //Remove anything but digits
    double side1 = Double.parseDouble(input.replaceAll("\\D+",""));
    //Remove all digits
    String unit = input.replaceAll("\\d","");
    System.out.println(side1);
    System.out.println(unit);

    while (side1 < 0) {
        //prompt the user to enter the input again in a positive value
        System.out.println("Error, No Negative Number. Enter again:");
        input = sc.nextLine();

        //Remove anything but digits
        side1 = Double.parseDouble(input.replaceAll("\\D+",""));
    }

    switch(unit) {
        case "in":
            unit = "inch";
            break;
        case "cm":
            unit = "centimeter";
            break;
        case "ft":
            unit = "feet";
            break;
        case "m":
            unit = "meter";
            break;

        default:
            System.out.println("Invaild unit");
            break;
    }

    double area = side1*side1;
    System.out.println("Area of Square is: " + area + " " + unit + "^2");
}