我正在尝试创建一个包含两个类和一个构造函数的程序。它必须返回一个矩形的面积和周长的答案。我写的程序,但我不知道如何让它返回。我在创建第二个类和使用构造函数时遇到了问题。
import java.util.Scanner
public class RectangleCalc{
public static void main(String[] args) {
Rectangle myRect = new Rectangle(1.5, 2.3);
double Area;
double Perimeter;
greetUser(); // method call
userInput(); // method call
userGoodbye(); // method call
myRect.setLength(0);
myRect.setWidth(0);
Area = myRect.area();
Perimeter = myRect.perim();}
public static void greetUser(){
System.out.println("Welcome to the Rectangle Calculator");}
public static void userInput(){
System.out.println("This program will accept the user input of length and width to calculate the perimeter and area of a rectangle.");
System.out.println("Would you like to continue Y/N?");
System.out.println("Enter the width ");
System.out.println("Enter the length ");
}
public static void Results(double area, double pr, double width, double length){
Scanner input=new Scanner;
System.out.println ("The width you entered is:" + width );
System.out.println ("The length you entered is:" + length);
System.out.println ("The area of your rectangle is:" + area );
System.out.println ("The perimeter of your rectangle is:" + pr);
System.out.println ("Would you like to calculate another rectangle Y/N?");}
public static void userGoodbye(){
System.out.println ("Thank you for using the Rectangle Calculator. Goodbye!");}
Rectangle newRect = new Rectangle(10, 20);
}
class Rectangle{
public double width, length;
public double len, wid;
public void setWidth(double w) {
width = w;
}
public void setLength(double ln) {
length = ln;
}
public double getWidth() {
return width;
}
public double getLength() {
return length;
}
public double area() {
double area;
area = length * width;
return area;
}
public double perim() {
double pr;
pr = (length * 2) + (width * 2);
return pr;
}
public Rectangle(double len, double wid) {
}
}发布于 2014-04-11 23:03:08
这里
public Rectangle(double len, double wid) {
}执行此操作
public Rectangle(double len, double wid) {
setLength(len);
setWidth(wid);
}就这样!
发布于 2014-04-11 23:12:57
首先,你的问题标题可以更具描述性。
您应该在Rectangle类中遵循Java约定,在定义其方法之前定义构造函数。我几乎以为你还没写好呢。
缩进。虽然Java不依赖于适当缩进的代码,但人类在某种程度上依赖。尽量让你的代码块和级别保持一致的缩进。可以使用制表符,也可以使用几乎成为标准的空格-4,每个缩进级别。不正确地缩进你的代码只会在尝试跟随你的程序流时导致困难,并可能由于错误地假设任何行实际上是什么代码块的一部分而导致错误。
Java变量和方法应该以小写字母开头(具体来说是pascalCase)。double area和double perimeter。类名是CamelCase,并且以大写字母开头。
编辑:您在这里也混淆了代码标记解析器。看看你的变量是如何在你的帖子的代码块中着色的。
但是关于你的代码...
您的构造函数接受两个参数,但从不将这些值赋给任何地方。他们只是迷路了。
您的userInput()方法会提出问题,但不会尝试获得任何答案。它只是打印一些文本。
您的Results(...)方法(参见上面的案例问题)声明了一个Scanner,但并没有使用它。您可能想让它进入当前毫无意义的userInput()方法。
所以:
在你的构造函数中使用你定义的setter方法,在你的userInput()方法中获取一些用户输入,如果事情还没有改善,回到这里,我们可以帮助你走得更远。
发布于 2014-04-11 23:13:13
仔细查看你的代码,我发现了一些问题:
import java.util.Scanner的末尾需要一个分号:import java.util.Scanner;public Rectangle(double len, double wid) { width = wid; length = len; }
https://stackoverflow.com/questions/23016104
复制相似问题