登录    关于
马育民老师的博客

马育民的博客

QQ:65242847

JAVA for和数组案例

案例1

有学生:"张三","李四","李雷","韩梅梅","lucy","lili",用程序判断 李雷王五 是否存在

String name="李雷";
String[] class1={"张三","李四","李雷","韩梅梅","lucy","lili"};

boolean has=false;
for (String item:class1){
    if(item.equals(name)){
        has=true;
        break;
    }
}
if(has){
    System.out.println(name+" 存在");
}else{
    System.out.println(name+" 不存在");
}

案例2

2个班的学生,分别放到2个数组里,找出同名的学生

String[] class1={"张三","李四","李雷","韩梅梅","lucy","lili"};
String[] class2={"鹿晗","韩梅梅","李现","冯提莫","lucy","李子琪"};

for(String item1:class1){

    for (String item2:class2){

        if(item1.equals(item2)){
            System.out.println(item1);
        }
    }
}

原文出处:https://malaoshi.top/show_1IX1HJZ9lyTU.html