gpt4 book ai didi

java - 该函数是否使用了太多检查和变量?

转载 作者:行者123 更新时间:2023-12-02 00:56:35 25 4
gpt4 key购买 nike

我正在学习 Java 的 Udemy 类(class),任务是根据输入整数的相等性打印不同的内容。我的解决方案是正确的,但感觉太冗长了。有更优雅的解决方案吗?

注意:此任务只允许一个函数(除了插入的 main 函数),因此我不能只从第一次检查中返回

public class IntEqualityPrinter {
// write your code here
public static void printEqual(final int a, final int b, final int c) {
String message = "";
if(a < 0 || b < 0 || c < 0) {
message = "Invalid Value";
} else {
int count = 0;
if(a == b) {
++count;
}
if(b == c) {
++count;
}
if(a == c) {
++count;
}
switch(count) {
case 0: message = "All numbers are different"; break;
case 1: case 2: message = "Neither all are equal or different"; break;
case 3: message = "All numbers are equal"; break;
}
}


System.out.println( message );
}
}

最佳答案

...so I can't just return from the first check.

但是,你可以!怎么样:

public static void printEqual(final int a, final int b, final int c) {

if (a < 0 || b < 0 || c < 0) {
System.out.println("Invalid Value");
return;
}

String message = "";

if (a == b) {
if (a == c) {
message = "All numbers are equal";
} else {
message = "Neither all are equal or different";
}
} else {
if (a == c) {
message = "Neither all are equal or different";
} else {
message = "All numbers are different";
}
}

System.out.println(message);
}

我想这很简单,并将检查与消息的实际初始化结合起来。

关于java - 该函数是否使用了太多检查和变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61287449/

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