我不确定这个问题是否有一个更简单的答案,我正在考虑要解决什么问题,但是我目前正在编写一个矩形块程序来练习Java。它的结构具有4种方法:getInput
,volBlock
,saBlock
和display
,并且我只想对这些方法使用局部变量。有没有一种方法可以利用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的新手。
感谢您的帮助,谢谢!
答案 0 :(得分:1)
如果您正在练习Java,则在继续学习之前,您可能应该更熟悉面向对象编程,因为您的代码使我相信您已经习惯了过程语言(例如C,C ++等)。 Java主要不依赖于几个静态辅助方法。首选方法是构造一些为您执行这些计算的类,然后将这些函数创建的结果用于基本输入/输出,这通常是main的用途。
我实现了一个块类来演示我的意思:
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
类,您的主体变得更加简单:
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');
}
答案 1 :(得分:0)
如果您从getInput(),volBlock()和surfaceAreaBlock()方法返回值,则可以按需要构造其余部分。
例如surfaceAreaBlock变为:
public static double surfaceAreaBlock (double l, double w, double h){
double surfaceArea;
surfaceArea = 2 * (l*h+l*w+h*w);
return surfaceArea;
}
,然后在调用surfaceAreaBlock时可以执行以下操作:
public static void main(String[] args) {
...
double surfaceArea = surfaceAreaBlock();
// Do something with the surface area in this method
...
}