我的 IF 语句中缺少 break 语句

问题描述

我目前正在完成一项课堂任务,涉及计算任意数量的具有不同尺寸的墙壁所需的油漆量,问题是我已经设置了所有内容,所有计算结果都正确。

>

我正在使用 IF 语句将 EU 转移到正确的代码块,但出于某种原因,当我使用英尺到英制加仑部分时,它仍然尝试将米运行到升部分。在我的第一个 IF 语句和 do while 循环(用于计算墙壁总面积和房间总面积的循环)结束时,我显然遗漏了一些东西,我只是想知道是否有人可以快速观察它并且指出我正确的方向。如果有人可以提供帮助,请在下面附上代码

(对于第一次在这里发帖的任何差异表示歉意,所以请善待lol)

public static void main(String[] args) throws IOException
{
        double widthOfWall = 0;
        double lengthOfWall = 0;
        double areaOfWall = 0; 
        double areaOfRoom = 0;
        double paintNeeded = 0;
        char   UnitsUsed = ' '; 
        char   extraCalc = 0;
        
        
        
    //Scanner class
    Scanner keyboard = new Scanner (system.in);
    
    {   
    System.out.println("Are using Feet or Metre? (F/M)");
    UnitsUsed = ValidateData.checkTwoChars('F','M');
    {
        {   
if (UnitsUsed == 'F')
    
    do{ 
        System.out.println("Please enter width of the wall");
        widthOfWall = keyboard.nextDouble();
        
        System.out.println("Please enter the Length of the wall");
        lengthOfWall = keyboard.nextDouble();
        
        areaOfWall = widthOfWall * lengthOfWall; 
        System.out.println("The area of this wall is " + areaOfWall);
        
        System.out.println("Do you require an additional calculation? ");
        extraCalc = ValidateData.checkTwoChars('Y','N'); 
        
        areaOfRoom += areaOfWall;
        areaOfWall ++; 
        
        
System.out.println("The area of the room " + areaOfRoom);
        
        
        paintNeeded = areaOfRoom / 6.229; 
        System.out.println("The amount of paint needed (in Imperial gallons) " + paintNeeded);
        }
        while (extraCalc == 'Y'); 
        

else if (UnitsUsed == 'M');
    
    //do while loop
    do{ 
    System.out.println("Please enter width of the wall");
    widthOfWall = keyboard.nextDouble();
    
    System.out.println("Please enter the Length of the wall");
    lengthOfWall = keyboard.nextDouble();
    
    areaOfWall = widthOfWall * lengthOfWall; 
    System.out.println("The area of this wall is " + areaOfWall);
    
    System.out.println("Do you require an additional calculation? ");
    extraCalc = ValidateData.checkTwoChars('Y','N'); 
    
    areaOfRoom += areaOfWall;
    areaOfWall ++; 
    }
    while (extraCalc == 'Y'); 
    
    System.out.println("The area of the room " + areaOfRoom);
    
    paintNeeded = areaOfRoom / 12; 
    System.out.println("The amount of paint needed (in litres) " + paintNeeded);
    }




}
}}

}

解决方法

这里用分号代替左大括号 {

else if (UnitsUsed == 'M');

此外,这是很多重复的代码,当两个分支之间的唯一区别是单元时。您可以使用三元运算符设置乘数和单位字符串变量,然后消除 if/else 以简化此操作。