对于带有string.split到数组的循环,满足条件后中断

在满足字符串文本(条件)之一后,我试图打破 for 循环并仅执行一次函数。


我尝试过 break,尝试了很多其他方法,但我无法让它与 for 循环等中的 if 条件一起工作。



static void show(@NonNull Context context, @NonNull Arri<Mylist> notification) {


            ....


        String strings = "text1,text2,text3,text4,...";

        String[] stringarray = strings.split(",");


        for(String name : stringarray){

            notifyMe(name, notification);

        }


    private static void notifyMe(String text, @NonNull Arri<Mylist> notification) {

        if (notification.loadr().project().toString().toLowerCase().contains(text.toLowerCase())) {

            Log.d("TAG", "contains:" + text);

        } else {

            Log.e("TAG", "doesnt contain:" + text);

        }

    }

目前它当然会执行更多次,但我只需要它一次来执行功能。任何帮助将不胜感激。


猛跑小猪
浏览 133回答 4
4回答

慕容3067478

我已经为我的问题找到了解决方案,如果有人需要它,它就在这里。如果有更好的方法欢迎留言。static void show(@NonNull Context context, @NonNull Arri<Mylist> notification) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ....&nbsp; &nbsp; &nbsp; &nbsp; String strings = "text1,text2,text3,text4,...";&nbsp; &nbsp; &nbsp; &nbsp; String[] stringarray = strings.split(",");&nbsp; &nbsp; &nbsp; &nbsp; for(String name : stringarray){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (notifyMe(name, notification)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; private static boolean notifyMe(String text, @NonNull Arri<Mylist> notification) {&nbsp; &nbsp; &nbsp; &nbsp; if (notification.loadr().project().toString().toLowerCase().contains(text.toLowerCase())) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }

www说

break如果您想在满足条件时中断循环,只需使用语句:public void breakIt(){&nbsp; &nbsp; String stringToSplit = "text1,text2,text3";&nbsp; &nbsp; String[] strings = stringToSplit.split(",");&nbsp; &nbsp; String condition = "text2";&nbsp; &nbsp; for (String s : strings){&nbsp; &nbsp; &nbsp; &nbsp; if (s.equals(condition)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(s);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}您也可以使用return“离开”循环。return查看有关和之间差异的更多信息break: break vs return

繁花不似锦

获取您的条件并从 notifyMe 中删除并放入 for 循环或在此使用布尔响应并评估为 for 循环。否则你不能停止这个循环。

泛舟湖上清波郎朗

您可以notifyMe在内部调用if:for (String name : stringArray) {&nbsp; &nbsp; if (someLogic(name)) {&nbsp; &nbsp; &nbsp; &nbsp; notifyMe(name, notification);&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java