gpt4 book ai didi

Java : How to improvise if else statements

转载 作者:行者123 更新时间:2023-11-30 08:07:00 25 4
gpt4 key购买 nike

在最近的java面试中,询问了有关if then else的问题,并且问题的提出方式是,如果给你1000个if else条件,例如

if(condition 1){
task 1
}else if (condition 2){
task 2
}else if (condition 3){
task 3
}
...
else if (condition 1000){
task 1000
}

我被要求即兴编写上面的代码。我给出的答案是可以通过使用 switch 来临时实现。但面试官并不满意,要求采取另一种方法。但我无法解释它。所以我想知道是否有更好的方法来做到这一点。

很抱歉问了这么愚蠢的问题,但我真的很想知道答案

最佳答案

从面试官的角度思考,问题的目的是获得答案,然后继续下一个问题

以下是改进使用集合的一种方法。对于java面试泛型自动装箱将是一个很好的segue,下面的答案正是包含这一点。您可以通过多种方式改进它,但以下是一个答案。

 List<Integer> myRnage = new ArrayList<Integer>(1000);
for(Integer theIndex : myRnage) {
//do the task for theIndex at this point.
}

Alternatively the same can be answered with code using Apache libraries to demonstrate the use of Range utility. Here is the SO link for that and more.

关于Java : How to improvise if else statements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30958778/

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