使用一种方法的结果以另一种方法计算价格

时间:2019-03-09 04:55:58

标签: java methods

我是初学者。 我无法弄清楚我到底在做什么错。 我设法使第一种方法正常工作(calculateArea),但是我不明白为什么第二种方法不起作用(找不到区域的符号)

import java.util.Scanner;

public class PaintCalculator
{
   public static void main(String[] args)
   {
      double length;
      double width;

      Scanner keyboard = new Scanner(System.in);

      System.out.print("Enter the length >> ");
      length = keyboard.nextDouble();
      System.out.print("Enter the width >> ");
      width = keyboard.nextDouble();
      keyboard.nextLine();

      calculateArea(length, width);
      calculatePrice(area);
   }

   public static double calculateArea (double length, double width)
   {
     double area;
     area = length * width;
     System.out.println(area);
     return area;

   }

  public static void calculatePrice(double area)
   {
    double gallons = area * 350;
    double price = gallons * 32;
    System.out.println(price);
   }
}

抱歉,这是一个菜鸟问题

2 个答案:

答案 0 :(得分:1)

您必须将calculateArea(是区域)的返回值保存为double变量,并将其传递给calculatePrice

 public static void main(String[] args)
  {
  double length;
  double width;

  Scanner keyboard = new Scanner(System.in);

  System.out.print("Enter the length >> ");
  length = keyboard.nextDouble();
  System.out.print("Enter the width >> ");
  width = keyboard.nextDouble();
  keyboard.nextLine();

 double area = calculateArea(length, width);
 calculatePrice(area);
 }

答案 1 :(得分:0)

这是Java如何在方法中处理数据的经典示例。 area变量在您的calculateArea方法中,您正尝试通过main使用它,并将其输入计算价格。而是将区域分配给变量并将其传入

{
   public static void main(String[] args)
   {
      double length;
      double width;

      Scanner keyboard = new Scanner(System.in);

      System.out.print("Enter the length >> ");
      length = keyboard.nextDouble();
      System.out.print("Enter the width >> ");
      width = keyboard.nextDouble();
      keyboard.nextLine();

      //calculateArea(length, width);
      int area = calculateArea(length, width);
      calculatePrice(area);
      //or just directly place it in like this
      calculatePrice(calcuateArea(length, width));
   }

   public static double calculateArea (double length, double width)
   {
     double area;
     area = length * width;
     System.out.println(area);
     return area;

   }

  public static void calculatePrice(double area)
   {
    double gallons = area * 350;
    double price = gallons * 32;
    System.out.println(price);
   }
}