我真正坚持的问题是:
编写一个程序,要求用户输入矩形的宽度和长度,然后显示矩形的面积。该程序应调用以下方法:
• getLength – 此方法应要求用户输入矩形的长度,然后以 double 返回该值。
• getWidth – 此方法应要求用户输入矩形的宽度,然后将该值作为 double 值返回。
• getArea – 此方法应接受矩形的长度和宽度作为参数,并返回矩形的面积。面积的计算方法是将长度乘以宽度。
• displayArea – 此方法应接受矩形的长度、宽度和面积作为参数,并将它们显示在屏幕上的适当消息中。
我不知道如何完成这段代码,因为现在我所拥有的是:
import java.util.Scanner;
public class WidthLengthAreaMethods
{
public static void main(String[]args)
{
Scanner keyboard = new Scanner(System.in);
double length;
double width;
double area;
length = getLength();
width = getWidth();
area = getArea(double length, double width);
displayData(length, width, area);
}
public static double getLength()
{
System.out.println("Enter length. ");
length = keyboard.nextDouble();
System.out.println("The length is " + length);
}
public static double getWidth()
{
double width;
System.out.println("Enter width. ");
width = keyboard.nextDouble();
System.out.println("The width is " + width);
}
public static double getArea()
{
double length;
double width;
double area = length * width;
System.out.println("The area is: " + area);
}
public static void displayData(double length, double width, double area)
{
System.out.println(" The length is: \t" + length);
System.out.println(" The width is: \t" + width);
System.out.println(" The area is: \t" + area);
}
}
我搞砸了什么,我该如何解决?我是编程的初学者,所以请多多包涵 :D。
谢谢大家!!
最佳答案
由于您的程序被分解为多个方法,因此每个方法中的数据都是本地的,除非您将其存储在类本身中。
例如,您的 getLength() 和 getWidth() 辅助函数将无法访问您的键盘扫描仪,除非您在 main 方法之外声明它,例如:
import java.util.Scanner;
public class WidthLengthAreaMethods {
Scanner keyboard = new Scanner( System.in );
// Initialized within the class, but outside of any methods
public static void main( String[] args ) {
double length = getLength();
double width = getWidth();
double area = getArea( length, width );
displayData( length, width, area );
}
}
另一种选择是将您的 Scanner 传递给函数调用中的每个辅助方法,例如
public static double getLength( Scanner keyboard ){}
虽然将 Scanner 分别传递给每个函数可以让您的方法按预期工作,但第一个选项的可读性稍高一些。
要考虑的另一件事是,当方法有返回值时,例如 getLength()、getWidth() 和 getArea() 中的 double 值,调用该函数的代码片段需要一些变量要返回的那种类型。在 void 函数的情况下,例如 main() 或 displayData(),该方法声明它不会返回任何特定类型的变量。
因此,当您将长度设置为等于 getLength() 时,您要做的是将本地长度变量的值设置为等于从辅助函数返回的值。如果永远不会发送该值,则程序很可能无法编译 - 当您尝试调用该函数时,将抛出一个错误,指出类似于“预期类型 double ”的内容。要修复编译器错误,需要在辅助函数中添加 return 语句,例如:
Scanner keyboard = new Scanner( System.in );
public static double getWidth() {
System.out.println("Enter width.");
double width = keyboard.nextDouble(); // Sets the value to return to your main function
System.out.println("The width is " + width);
return width; // Returns the value to your main function
// Causes any code underneath the return statement to be ignored
}
结合所有这些应该可以让编译器错误停止,并使您的程序正常工作。
关于java - 确定矩形面积的多种方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29567656/