我是编码新手。我不确定如何在方法之间移动输入值。我尝试了不同的方法,但这总是给我一个错误。我也很好奇您将如何返回多个值。就像让我们说的那样,不使用getLength()和getWidth()而是使用一个名为getInput()的方法,它将同时返回长度和宽度。

    import java.util.Scanner;  // Needed for the Scanner class
/**
   This program calculates the area of a rectangle.
*/
public class Rectangle
{
   //main method
   public static void main(String[] args)
   {
      float length = 0;
      float width = 0;
      float area = 0;


      getLength();
      getWidth();
      calcArea(length, width);
      displayData(area);
   }

   //method 2
   public static float getLength()
   {
      // Create a Scanner object to read from the keyboard.
      Scanner keyboard = new Scanner(System.in);

      System.out.print("Enter Length: ");
      float length = keyboard.nextFloat();

      return length;

   }

   public static float getWidth()
   {
      // Create a Scanner object to read from the keyboard.
      Scanner keyboard = new Scanner(System.in);

      System.out.print("Enter Width: ");
      float width = keyboard.nextFloat();

      return width;

   }


   public static float calcArea(float length, float width)
   {
     float area = length*width;

     System.out.print("\nxxxx "+area);

     return area;

   }

   public static void displayData(float area)
   {
      System.out.print("\nThe area of the rectangle is "+area);
   }

}

最佳答案

这应该有助于:

      length = getLength();
      width = getWidth();
      area = calcArea(length, width);
      displayData(area);

关于java - 代码运行但没有给我正确的输出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58254099/

10-11 07:25