使用开关/情况时,无效的常数字符



我似乎无法使我的代码正常工作。我需要找到正方形的区域,并根据用户使用的数字,m for meter,cm,厘米和ft for fos for for for for for for for Mind,并添加测量单位。

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+);**
      }
    }
}

您的主要问题是,您在char上使用开关案例,而所有案例均基于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");
}

最新更新