【问题标题】:Is there a way to use the code for OutOfOrder, to make InOrder as simple as OutOfOrder?有没有办法使用 OutOfOrder 的代码,让 InOrder 像 OutOfOrder 一样简单?
【发布时间】:2020-12-21 08:13:01
【问题描述】:

我很难尝试仅使用逻辑规则和使用 OutOfOrder 代码的方法,以使 InOrder 像 OurOfOrder 一样简单。

public class InOrder {
//Don't change this
public boolean OutOfOrder(int n1, int n2, int n3) {
return (n1 > n2) || (n2 > n3);
}

//The original and messy InOrder, leave this as an example of what not to do
public boolean inOrder(int n1, int n2, int n3) {
if (n2 > n1) {
  if (n3 > n2) {
    return true;
  } else {
    return false;
  }
} else if (n2 == n1) {
  if (n3 == n1) {
    return true;
  } else {
    return false;
  }
} else {
  return false;
}
}

//The new and improved InOrder for part 5, call OutOfOrder
public boolean inOrder5a(int n1, int n2, int n3) {
return true; //replace this
}

//The newer and improved InOrder for part 6, inline
public boolean inOrder5b(int n1, int n2, int n3) {
return true;//replace this
}

}

【问题讨论】:

  • 你的意思是return (n1 <= n2 && n2 <= n3);?您实际上并没有告诉我们这些方法应该做什么。
  • return !OutOfOrder(n1, n2, n3); - 假设它不是“乱序”,它必须是“有序”:/
  • 请注意,if (condition) { return true; } else { return false; } 之类的构造可以只替换为 return condition;,这已经极大地简化了您的逻辑。
  • 请注意,您当前的代码不正确。对于n1 < n2 和n2 == n3 的情况,它的行为是错误的。例如n1 = 4、n2 = 6、n3 = 6。你的代码是 false 虽然它是有序的。

标签: java if-statement return boolean call


【解决方案1】:

我会说:(n2 >= n1 && n3 >= n2)

【讨论】:

    【解决方案2】:

    似乎数字要么有序,要么乱序,没有第三种选择。

    所以你可以将inOrder 实现为:

    public boolean inOrder(int n1, int n2, int n3) {
        return !outOfOrder(n1, n2, n3);
    }
    

    【讨论】:

      猜你喜欢
      • 2020-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-10
      • 1970-01-01
      • 2022-11-16
      • 1970-01-01
      • 2014-06-16
      相关资源
      最近更新 更多