Java 计算矩形的周长和面积

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18497458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 08:35:47  来源:igfitidea点击:

Calculating perimeter and area of a rectangle

java

提问by Derek Pike

I need to be able to input length and width of a rectangle into a console and calculate its perimeter and area. I have it working other than accepting my inputs for the calculations. I know I'm close, but can't seem to figure it out. Thanks in advance for your help. Keep in mind I'm a novice to put it nicely, so your answers may not make sense to me at first. I cannot get it to calculate the values that I input into the console.

我需要能够将矩形的长度和宽度输入控制台并计算其周长和面积。除了接受我的计算输入之外,我还让它工作。我知道我很接近,但似乎无法弄清楚。在此先感谢您的帮助。请记住,我是一个新手,所以说得好,所以你的回答一开始可能对我没有意义。我无法让它计算我输入到控制台的值。

package edu.purdue.cnit325_lab1;

public class Rectangle {    
    private static double length;
    private static double width;

    public Rectangle() {
        length=0.0;
        width=0.0;
    }

    public Rectangle(double l, double w) {
        length = l;
        width = w;
    }

    public double FindArea() {
        return length*width;
    }

    public double FindPerim() {
        return length*2 + width*2;
    }   
}

package edu.purdue.cnit325_lab1;

import java.util.Scanner;

public class TestRectangle {
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
            Scanner scanL = new Scanner (System.in);
            System.out.print("Please enter the length of the rectangle: ");
            double L = scanL.nextDouble();
            Scanner scanW = new Scanner (System.in);
            System.out.print("Please enter the length of the rectangle: ");
            double W = scanW.nextDouble();
            //int W = scanW.nextInt();
            double RectangleArea;
            Rectangle unitRectangle = new Rectangle(); 
            RectangleArea = unitRectangle.FindArea();
            System.out.println("The area of a unit rectangle is " + RectangleArea);

            double RectanglePermiter;
            Rectangle perimRectangle = new Rectangle();
            RectanglePermiter = perimRectangle.FindPerim();
            System.out.println("The permimiter of the unit rectangle is " + RectanglePermiter);
    }
}

采纳答案by GerritCap

Note that you are calling the Rectangle constructore with no arguments thus setting its width and height to zero, you should use

请注意,您正在调用不带参数的 Rectangle 构造函数,从而将其宽度和高度设置为零,您应该使用

Rectangle unitRectangle = new Rectangle(L,W);

矩形 unitRectangle = new Rectangle(L,W);

and indeed like the other answer you should use one Scanner instance.

确实像另一个答案一样,您应该使用一个 Scanner 实例。

Plus regarding coding style: do not upercase your variable names. Its quite confusing for more "experienced" java developers. :-)

另外关于编码风格:不要大写你的变量名。对于更多“有经验的”Java 开发人员来说,这相当令人困惑。:-)

回答by Martijn Courteaux

Use one Scanner instance. Just reuse it.

使用一个 Scanner 实例。只需重复使用它。

Scanner scanner = new Scanner (System.in);
System.out.print("Please enter the length of the rectangle: ");
double L = scanner.nextDouble();
System.out.print("Please enter the length of the rectangle: ");
double W = scanner.nextDouble();

Update:You don't pass the Land Wto the constructor as the other answer points out. However, some mistakes you made:

更新:您没有像其他答案指出的那样将Land传递W给构造函数。但是,您犯了一些错误:

  • You declared lengthand widthas static. Don't do that. That makes no sense. The length and the width are properties of a rectangle and shouldn't be shared by all rectangle instances.
  • You don't use the correct naming conventions: variables start with a lowercase character, class names start with an uppercase character.
  • You are creating two instances of your Rectangle to calculate both perimeter and area of the same rectangle. Share that instance instead.
  • 您声明lengthwidth作为static. 不要那样做。这是没有意义的。长度和宽度是矩形的属性,不应由所有矩形实例共享。
  • 您没有使用正确的命名约定:变量以小写字符开头,类名以大写字符开头。
  • 您正在创建 Rectangle 的两个实例来计算同一矩形的周长和面积。改为共享该实例。

回答by Prabhaker A

you missed to call parameterized constructor.

你错过了电话parameterized constructor

public static void main(String[] args) {
    Scanner scanL = new Scanner (System.in);
    System.out.print("Please enter the length of the rectangle: ");
    double L = scanL.nextDouble();

    System.out.print("Please enter the length of the rectangle: ");
    double W = scanL.nextDouble();


    Rectangle rectangle = new Rectangle(l,w); 
    double rectangleArea = rectangle .FindArea();
    System.out.println("The area of a unit rectangle is " + rectangleArea);

    double rectanglePermiter = rectangle.FindPerim();
    System.out.println("The permimiter of the unit rectangle is " + rectanglePermiter);
}

Note: Unnecessarily you created two Scannerobjects and two Rectangleobjects in your code,which are removed from the above code.

注意:您不必要地在代码中创建了两个Scanner对象和两个Rectangle对象,这些对象已从上述代码中删除。

回答by progrenhard

So you need to set the values in some way... you can do either

所以你需要以某种方式设置值......你可以这样做

A)

一种)

Rectangle unitRectangle = new Rectangle(l,w); 

B)

乙)

or create getters and setters in the rectangle class..

或在矩形类中创建 getter 和 setter ..

setLength(double l) length = l;
setWidth(double w) width = w

double getLength() return length;
double getWidth() return height;

Since you are initializing with the default constructor

由于您使用默认构造函数进行初始化

aka

又名

 Rectangle unitRectangle = new Rectangle(); 

the values for length and width will also be zero.

长度和宽度的值也将为零。

回答by Sid

Your code consists of the Default constructor, which will initialize the respective values length and width to 0.0as set by you and also consist of parametrized constructor which requires input values to be provided and will set the value accordingly.

您的代码由默认构造函数组成,它将初始化相应的值长度和宽度0.0为您设置的值,还包括参数化构造函数,它需要提供输入值并相应地设置值。

When you are creating the object of your class, you are calling the Default Constructor instead of parametrized constructor in this line

当您创建类的对象时,您将在此行中调用默认构造函数而不是参数化构造函数

Rectangle unitRectangle = new Rectangle();

Rectangle unitRectangle = new Rectangle();

Thus setting them to 0.0

因此将它们设置为 0.0

If you do Something like this

如果你做这样的事情

Rectangle unitRectangle2 = new Rectangle(2.3,4.3);

Rectangle unitRectangle2 = new Rectangle(2.3,4.3);

This will create the object having values for length and breadth as 2.3 and 4.3 respectively.

这将创建长度和宽度值分别为 2.3 和 4.3 的对象。

回答by Sravan

//write a java program which will calculate area and perimeter of rectangle by accepting radius from cmd prompt
//area = width x height,perimeter = (2 x width) + (2 x height)

class AreaAndPerOfRect
{
    int h,w;
    void set(int x,int y)
    {
        h=x;
        w=y;
    }
    int AreaOfRect()
    {
        int area=w*h;
        return area;
    }
    int PerOfRect()
    {
        int per=(2*w)+(2*h);
        return per;
    }
    void disp()
    {
        int area=AreaOfRect();
        System.out.println("area of rectangle"+area);
        int per=PerOfRect();
        System.out.println("area of rectangle"+per);
    }
}
class AreaAndPerOfRectDemo
{
    public static void main(String args[])
    {
        if(args.length!=2)
        {
            System.out.println("please enter two values");
        }
        else
        {
            int x=Integer.parseInt(args[0]);
            int y=Integer.parseInt(args[1]);
            AreaAndPerOfRect ap=new AreaAndPerOfRect();
            ap.set(x,y);
            ap.disp();
        }
    }
}

回答by Ravikiran

//This is the Java code for finding the area and perimeter of a rectangle
package demo;

import java.util.Scanner;

public class DemoTranslation {
public static int area(int length, int width) {
    int areaOfRectangle;
    areaOfRectangle = length * width;
    System.out.println("Area of Rectangle is : " + areaOfRectangle);
    return 0;
}

public static int perimeter(int length, int width) {
    int perimeterOfRectangle;
    perimeterOfRectangle = (length + width) * 2;
    System.out.println("Perimeter of Rectangle is : " + perimeterOfRectangle);
    return 0;
}

public static void main(String[] args) {
    int length, width, choice;
    System.out.println("Enter the length of the triangle ");
    length = STDIN_SCANNER.nextInt();
    System.out.println("Enter the width of the triangle ");
    width = STDIN_SCANNER.nextInt();
    System.out.println("Enter 1 : View the area ");
    System.out.println("Enter 2 : View the perimeter ");
    System.out.println("Enter 3 : view both ");
    choice = STDIN_SCANNER.nextInt();
    switch(choice) {
    case 1:
        area(length, width);
        break;
    case 2:
        perimeter(length, width);
        break;
    case 3:
        area(length, width);
        perimeter(length, width);
        break;
    default:
        System.out.println("Invalid option ");
        break;
    }
    }

    public final static Scanner STDIN_SCANNER = new Scanner(System.in);
    }