Java の学習を始めたばかりで、ユーザーが選択した図形の面積を計算する基本的なプログラムを作成しました。私が行った正しいことと間違ったことについて、批評やコメントをもらうことはできますか? 多くの場合、悪いプログラミングになると思いますが、それが私がここにいる理由です。
また、1 つの質問です。私のメソッドを呼び出すときは、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;
}
}