我需要能够将矩形的长度和宽度输入控制台并计算其周长和面积.除了接受我的计算输入之外,我还有其他工作.我知道我很亲密,但似乎无法弄明白.在此先感谢您的帮助.请记住,我是一个很好的新手,所以你的答案起初可能对我没有意义.我无法计算我输入控制台的值.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,您正在调用不带参数的Rectangle构造函数,因此将其宽度和高度设置为零,您应该使用
Rectangle unitRectangle = new Rectangle(L,W);
确实像其他答案一样,你应该使用一个Scanner实例.
另外关于编码风格:不要使用变量名称.它对于更"经验丰富"的Java开发人员来说相当混乱.:-)
你错过了电话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);
}
Run Code Online (Sandbox Code Playgroud)
注意:您必须在代码中创建两个Scanner对象和两个Rectangle对象,这些对象将从上面的代码中删除.