gpt4 book ai didi

java - 如何将函数和方法合并到 Java 中的 if-else 条件中?

转载 作者:行者123 更新时间:2023-12-01 17:20:05 25 4
gpt4 key购买 nike

我能够运行一个程序来计算形状的周长并使用 if-else 条件来确定它是什么形状。但是,我正在努力将 if-else 条件与函数和方法配对。

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int sideA;
int sideB;
int sideC;
int sideD;
int perimeter = 0;

System.out.println("Enter side 1: ");
sideA = scan.nextInt();

System.out.println("Enter side 2: ");
sideB = scan.nextInt();

System.out.println("Enter side 3: ");
sideC = scan.nextInt();

System.out.println("Enter side 4: ");
sideD = scan.nextInt();

System.out.println("Forms a square with a perimeter of " + perimeter);
System.out.println("Forms a rectangle with a perimeter of " + perimeter);
System.out.println("Does not form a rectangle or square.");
}

private static int add(int sideA, int sideB, int sideC, int sideD) {
int perimeter = sideA + sideB + sideC + sideD;
return perimeter;
}

private static void isSquare(int sideA, int sideB, int sideC, int sideD, int perimeter) {
if (sideA == sideB && sideB == sideC && sideC == sideD && sideD == sideA) {
System.out.println("Forms a square with a perimeter of " + perimeter);
}

else if (sideA == sideC && sideB == sideD) {
System.out.println("Forms a rectangle with a perimeter of " + perimeter);
}

else if (sideA == sideB && sideC == sideD) {
System.out.println("Forms a rectangle with a perimeter of " + perimeter);
}

else if (sideA == sideD && sideB == sideC) {
System.out.println("Forms a rectangle with a perimeter of " + perimeter);
}

else {
System.out.println("Does not form a rectangle or square.");
}
}

我正在处理的程序在解析时遇到到达文件末尾的问题。如何改进文件的末尾以便我的程序完成解析?

最佳答案

我的意思是你应该考虑调用你的方法 add 和 isSquare也许将你的变量移到 main 之外,这样它们就有更多的作用域

    add(sideA,sideB,sideC,sideD);
isSquare(sideA,sideB,sideC,sideD,perimeter);

关于java - 如何将函数和方法合并到 Java 中的 if-else 条件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61311579/

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