我对编码还很陌生。我不确定如何跨方法移动输入值。我尝试了不同的方法,但它总是给我一个错误。我也很好奇您将如何返回多个值。就像让我们说,而不是有 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);
}
}
最佳答案
您的问题来自于非 void 方法将返回值这一事实。如果您不将这些值分配给任何变量,Java 将不会对它们执行任何操作。
float length = 0;
float width = 0;
float area = 0;
// Values are retrieved, but must be assigned to variables
length = getLength();
width = getWidth();
area = calcArea(length, width);
我强烈建议您尝试一些更直观的方法。我知道您是编码新手,但请尝试解决这个问题,看看它能给您带来什么。 OOP 是 Java 的核心组件,通常最好尽可能使用它。
矩形.java:
public class Rectangle
{
private float length;
private float width;
public Rectangle(float length, float width)
{
this.length = length;
this.width = width;
}
public float getArea()
{
return length * width;
}
public float getLength()
{
return length;
}
public float getWidth()
{
return width;
}
}
主类:
public static void main(String[] args)
{
// Only open one stream at a time
// Opening multiple without closing the previous may cause some problems in the future
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter Length: ");
float length = keyboard.nextFloat();
System.out.print("Enter Width: ");
float width = keyboard.nextFloat();
// Remember to close the stream when you are finished using it
keyboard.close();
// Create a new rectangle with the length and width that was given by the user
Rectangle rect = new Rectangle(length, width);
// Round the area to the nearest tenth of a decimal place and display results
System.out.printf("The area of the rectangle is %.1f", rect.getArea());
}
关于java - 代码运行但没有给我正确的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58254099/