在java中搜索arraylist中的整数

public class FindNumber {


            static String findNumber(List<Integer> arr, int k) {

                String res = "YES";

    //Unable to identify problem with this part of the code

                for (int i = 0; i < arr.size(); i++) {

                    if (k == arr.get(i))

                        res = "YES";

                    else

                        res = "NO";


                }


                return res;


            }

}

即使整数存在于列表中,上面的代码也会返回 NO 作为答案。


呼啦一阵风
浏览 140回答 5
5回答

米脂

您可以只使用来获取是否在列表中的arr.contains()布尔值。Integer然后您可以将此值转换为YESor&nbsp;NO(如果您确实需要它):String&nbsp;yesNo&nbsp;=&nbsp;arr.contains(k)&nbsp;?&nbsp;"YES"&nbsp;:&nbsp;"NO";

青春有我

这将起作用:static String findNumber(List<Integer> arr, int k) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String res = "YES";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < arr.size(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (k == arr.get(i))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; res = "YES";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; res = "NO";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return res;&nbsp; &nbsp; &nbsp; &nbsp; }一旦找到整数,就必须停止循环,您可以使用break

暮色呼如

使用流:static String findNumber(List<Integer> arr, int k) {&nbsp; &nbsp; return arr.stream()&nbsp; &nbsp; &nbsp; &nbsp; .filter(e -> e == k)&nbsp; &nbsp; &nbsp; &nbsp; .findFirst()&nbsp; &nbsp; &nbsp; &nbsp; .map(e -> "YES")&nbsp; &nbsp; &nbsp; &nbsp; .orElse("NO");}

慕丝7291255

尝试优化您的代码....方式 1(使用 for-each 循环):&nbsp;static String findNumber(List<Integer> arr, int k) {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; for (Integer integer : arr) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (integer == k) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return "YES";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return "NO";&nbsp;&nbsp; &nbsp; }另一种方法是(使用三元运算符):static String findNumber(List<Integer> arr, int k) {&nbsp;&nbsp; &nbsp; return arr.contains(k) ? "YES" : "NO";}

qq_花开花谢_0

你的代码的主要问题是,即使它在 ArrayList 中找到了一个整数对象,在设置 res = Yes 之后,它仍然继续迭代。因此,有可能列表中有其他值不是所需的数据类型,从而将 res 设置回否。这里的解决方案是使用跳转语句,例如 break,它会在出现时立即终止循环过程。遇到整数。希望能帮助到你!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java