简化if语句,Java
我想简化以下代码:简化if语句,Java,java,if-statement,Java,If Statement,我想简化以下代码: public static void main(String[] args) { int c1 = Integer.parseInt(args[0]); int c2 = Integer.parseInt(args[1]); int c3 = Integer.parseInt(args[2]); /* 1 */if (c2 - c1 == 0) { /* 2 */if (c1 != c
public static void main(String[] args) {
int c1 = Integer.parseInt(args[0]);
int c2 = Integer.parseInt(args[1]);
int c3 = Integer.parseInt(args[2]);
/* 1 */if (c2 - c1 == 0) {
/* 2 */if (c1 != c3) {
c3 += c1;
/* 4 */System.out.println(c3);
/* 5 */c3 *= c2;
/* 6 */}
}
/* 7 */if (c1 == c3)
/* 8 */if (c1 - c2 == 0)
/* 9 */{
c3 += c1;
/* 10 */System.out.println(c3);
/* 11 */c3 *= c1;
/* 12 */if (c1 < c2)
c2 += 7;
/* 13 */else
c2 += 5;
/* 14 */}
/* 15 */System.out.println(c1 + c2 + c3);
}
我的问题是现在什么可以简化?如果内部If在外部,我可以简化If。你觉得怎么样?试着在你的ifs中使用一些条件运算符,如果你能做一个&&,就没有理由嵌套它们
尝试在ifs中使用一些条件运算符,如果可以执行&&,则没有理由嵌套它们
警告:我假设您的代码的第二个版本是正确的,即您最初的简化是正确的 if语句的混乱可以简化为:
if (c1 == c2) {
c3 += c1;
System.out.println(c3);
if (c1 != c3) {
c3 *= c2;
} else {
c2 += 5;
c3 *= c1;
}
}
使用您的/*行号/*作为参考点,我简化了以下内容:
找出1和8中的常见情况
将4和10左右的通用代码计算出来。
警告:我假设您的代码的第二个版本是正确的,即您最初的简化是正确的 if语句的混乱可以简化为:
if (c1 == c2) {
c3 += c1;
System.out.println(c3);
if (c1 != c3) {
c3 *= c2;
} else {
c2 += 5;
c3 *= c1;
}
}
使用您的/*行号/*作为参考点,我简化了以下内容:
找出1和8中的常见情况
将4和10左右的通用代码计算出来。
}
}您无法排除if语句。它们按顺序执行,第一个更改第二个的值。结果会发生变化。您无法排除if语句。它们按顺序执行,第一个更改第二个的值。结果改变了。只是好奇;这是干什么的?你觉得呢?我认为,由于缩进和行号注释,代码几乎无法阅读,可能会妨碍您获得这个问题的答案。用规则的缩进和最右边的数字使代码可读,你可能会有更多的运气。@Evan:是的,看起来像家庭作业或考试。只是好奇;这是干什么的?你觉得呢?我认为,由于缩进和行号注释,代码几乎无法阅读,可能会妨碍您获得这个问题的答案。使用常规缩进和最右边的数字使代码可读,你可能会更幸运。@Evan:是的,看起来像是家庭作业或测试。可能是因为有人不明白条件运算符是什么:/@可能是marcog,虽然进一步简化了,即您的答案不需要它们,所以我的答案可能没有意义:你的观点仍然有效,OP可能会从中学习到一些东西。所以请保留在这里。可能是因为有人不明白条件运算符是什么:/@可能是marcog,虽然进一步简化了,即您的答案不需要它们,所以我的答案可能没有意义:你的观点仍然有效,OP可能会从中学习到一些东西。所以把它放在这里。
if (c1 == c2) {
c3 += c1;
System.out.println(c3);
if (c1 != c3) {
c3 *= c2;
} else {
c2 += 5;
c3 *= c1;
}
}
public static void main(String[] args)
{
int c1 = Integer.parseInt(args[0]);
int c2 = Integer.parseInt(args[1]);
int c3 = Integer.parseInt(args[2]);
if(c1 == c2)
{
c3 += c1;
System.out.println(c3);
if(c1 == c3)
{
c3 *= c1;
c2 += 5;
}
else
{
c3 *= c2;
}
}
System.out.println(c1 + c2 + c3);
}
public static void main(String[] args) {
int c1 = Integer.parseInt(args[0]);
int c2 = Integer.parseInt(args[1]);
int c3 = Integer.parseInt(args[2]);
if (c2 == c1)
{
if(c1!= c3)
{
c3 += c1;
System.out.println(c3);
c3 *= c2;
}
else {
c3 += c1;
System.out.println(c3);
c3 *= c1;
c2 += 5;
}
}
System.out.println(c1 + c2 + c3);