gpt4 book ai didi

java - 有什么方法可以更好地重写我的方法吗?

转载 作者:行者123 更新时间:2023-12-02 08:47:55 24 4
gpt4 key购买 nike

我不完全确定这个问题是否有一个更简单的答案,我正在努力思考它或什么,但我目前正在编写一个矩形 block 程序来练习Java。它的结构有 4 个方法:getInputvolBlocksaBlockdisplay,我只想使用这些方法的局部变量。有没有一种方法可以利用 getInput 接受并返回来自用户的单个 double 值,如果是这样,我如何在其他方法中使用该输入?

我构建了这段代码,它在 getInput() 中使用局部变量,然后将这些值传递给其他方法,但我无法找出显示方法,因此我将其硬编码到计算方法本身中。

这是代码:

import java.util.*;
public class Block {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String choice = "Y";
while (choice.equals("Y")){
getInput();
System.out.println("Would you like to do another calculation?(Y/N): ");
choice = in.next().toUpperCase();
}
System.out.println("Program now ending...");
}

public static void getInput() {
double l, w, h;
Scanner fin = new Scanner(System.in);
System.out.println("Please enter the length, width, and height in that order: ");
l = fin.nextDouble();
w = fin.nextDouble();
h = fin.nextDouble();

volBlock(l, w, h);
surfaceAreaBlock(l,w,h);
}

public static void volBlock(double length, double width, double height) {
double volume;

volume = length * width * height;

System.out.println("The volume is: " + volume);
}

public static void surfaceAreaBlock (double l, double w, double h) {
double surfaceArea;

surfaceArea = 2 * (l*h+l*w+h*w);

System.out.println("The surface area is: " + surfaceArea);
}
}

如果这个问题有点困惑,我很抱歉,我很难弄清楚所有这些。我对 Java 还很陌生。

感谢任何帮助,谢谢!

最佳答案

如果您正在练习 java,那么在继续之前,您可能应该更熟悉面向对象编程,因为您的代码让我相信您更习惯过程语言(例如 C、C++ 等)。 Java 不依赖于其 main 中的多个静态辅助方法;首选方法是构造一些类来为您执行这些计算,然后将这些函数创建的结果用于基本输入/输出,这通常是 main 的用途。

我实现了一个 block 类来演示我的意思:

public class Block {
private double length;
private double width;
private double height;

public Block(double l, double w, double h) {
length = l;
width = w;
height = h;
}

public double getVolume() {
return length * width * height;
}

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

/* This is the "display" method that you want */
public String toString() {
return "The volume is: " + getVolume() + "\n"
"The surface area is: " + getSurfaceArea();
}
}

使用 Block 类,您的 main 变得更加简单:

public static void main() {
Scanner in = new Scanner(System.in);
char choice = 'y';

do {
System.out.print("Please enter the dimensions of the block: ");
double length = in.nextDouble();
double width = in.nextDouble();
double height = in.nextDouble();
Block block = new Block(length, width, height);

System.out.println(block);
System.out.print("continue (y/n)? ");
choice = in.nextLine.toLowerCase().charAt(0);
} while (choice == 'y');
}

关于java - 有什么方法可以更好地重写我的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60962744/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com