Java油漆计算器程序报cannot find symbol错误 求排查解决
问题原因
你遇到的cannot find symbol报错是变量作用域和返回值接收的问题:
- 在
computeArea方法内部定义的area变量只属于该方法的局部变量,main方法无权直接访问 - 同理
computeGallons里的gallons也是方法局部变量,main方法无法直接调用 - 你调用三个计算方法时,都没有接收它们的返回值,计算结果生成后直接被丢弃,后续找不到对应变量自然触发编译报错
修正方案
只需要在main方法里定义对应变量接收三个方法的返回值即可,另外别忘了导入Scanner类,否则还会触发额外编译错误。
修正后的完整代码如下:
import java.util.Scanner; public class PaintCalculator { public static void main (String args[]) { System.out.println("Please enter the length, width, and height of your rectangular room."); Scanner input = new Scanner(System.in); System.out.println("Enter length >>"); double length = input.nextDouble(); System.out.println("Enter width >>"); double width = input.nextDouble(); System.out.println("Enter height >>"); double height = input.nextDouble(); // 接收返回的墙面面积 double area = computeArea(length, width, height); // 接收返回的油漆加仑数 double gallons = computeGallons(area); // 接收返回的总费用 double totalCost = computeTotalCost(gallons); // 若需要main方法单独打印最终费用可以放开下方注释 // System.out.println("The price to paint the room is $" + totalCost); } public static double computeArea(double length, double width, double height) { double area = (length * height * 2 + height * width * 2); return area; } public static double computeGallons(double area) { double gallons = (area/350); System.out.println("You will need " + gallons + " gallons"); return gallons; } public static double computeTotalCost(double gallons) { double totalCost = gallons * 32; System.out.println("The price to paint the room is $" + totalCost); return totalCost; } }
效果验证
输入长10英尺、宽7.5英尺、高8英尺的测试参数,计算得出墙面面积280平方英尺,油漆用量0.8加仑,总费用25.6美元,运行输出完全符合需求要求。
内容的提问来源于stack exchange,提问作者daiger427
相关产品推荐
相关产品推荐

