刚开始学习Java,写了一个计算用户选择形状面积的基本程序。我可以对我做对错的事情进行批评和评论吗?我猜很多会是糟糕的编程,但这就是我在这里的原因。
还有一个问题,在调用我的方法时,我需要输入完整路径,即 areaprog.areacode.. 你知道这是为什么吗?以下两个类的代码:
主程序
package areaprog;
import java.util.Scanner;
public class mainprog {
public static void main (String [] args){
//Area Menu Selection
System.out.println("What shape do you need to know the area of?\n" +
"1: Square?\n" +
"2: Rectangle?\n" +
"3: Triangle?\n" +
"4: Circle? \n" +
"5: Exit\n"
);
//User input for menu
Scanner reader = new Scanner(System.in);
System.out.println("Number: ");
int input = reader.nextInt();
reader.nextLine();
//Depending on user selection, depends on what method is called using switch.
Scanner scan = new Scanner(System.in);
//Square selection
if (input == 1){
System.out.println("What is a length of 1 side of the Square?\n");
double s1 = scan.nextInt();
double SqAns = areaprog.areacode.square(s1);
System.out.println("The area of you square is: " + SqAns);
}
//Rectangle selection
if (input == 2){
System.out.println("What is the width of your rectangle?.\n");
double r1 = scan.nextInt();
System.out.println("What is the height of your rectangle?\n");
double r2 = scan.nextInt();
double RecAns = areaprog.areacode.rect(r1, r2);
System.out.println("The area of your rectangle is: " + RecAns);
}
//Triangle selection
if (input == 3){
System.out.println("What is the base length of the triangle?.");
double t1 = scan.nextInt();
System.out.println("What is the height of your triangle?");
double t2 = scan.nextInt();
double TriAns = areaprog.areacode.triangle(t1, t2);
System.out.println("The area of your triangle is " + TriAns);
}
//Circle selection
if (input == 4){
System.out.println("What is the radius of your circle?.");
double c1 = scan.nextInt();
double CircAns = areaprog.areacode.circle(c1);
System.out.println("The area of your circle is " + CircAns);
}
//Exit application
if (input == 5){
System.out.println("Goodbye.");
System.exit(0);
}
}
}
面积计算
package areaprog;
public class areacode {
public static double rect(double width, double height) {
double a_value = width * height;
return a_value;
}
public static double circle(double radius){
double PI = Math.PI;
double a_value = PI * Math.pow(radius, 2);
return a_value;
}
public static double square(double side) {
double a_value = Math.pow(side, 2);
return a_value;
}
public static double triangle(double base , double height) {
double a_value = (base/2)* height;
return a_value;
}
}