练习、
代码:
public class User{private String id;private String username;private int password;public User() {}public User(String id, String username, int password) {this.id = id;this.username = username;this.password = password;}public String getId() {return id;}public void setId(String id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public int getPassword() {return password;}public void setPassword(int password) {this.password = password;}
}
import java.util.ArrayList;
import java.util.Scanner;
public class practice {public static void main(String[] args) {//1、定义一个集合,Scanner input = new Scanner(System.in);ArrayList<User> list = new ArrayList<>();// 存入三个用户对象for (int i = 0; i < 3; i++) {User ui = new User();System.out.println("输入用户的id:");String id = input.next();System.out.println("输入用户的username:");String username = input.next();System.out.println("输入用户的密码:");int password = input.nextInt();ui.setId(id);ui.setUsername(username);ui.setPassword(password);list.add(ui);}for (int i = 0; i < list.size(); i++) {User u = list.get(i);System.out.println(u.getId() + "," + u.getUsername() + "," + u.getPassword());}System.out.println("输入要查找的id:");String id = input.next();boolean b = func(id, list);System.out.println(b);}public static boolean func(String id, ArrayList<User> list) {for (int i = 0; i < list.size(); i++) {if (id.equals(list.get(i).getId())) {return true;}}return false;}
}
结果:
注意点:带有返回值的方法在返回值返回后,会立即结束该方法的执行。任何在返回值后面的代码都不会执行。这是因为返回值是方法的结果,一旦返回结果,方法的任务就完成了,没有必要继续执行后续的代码。
升级练习、
代码:
javabean代码一样
import java.util.ArrayList;
import java.util.Scanner;
public class practice {public static void main(String[] args) {//1、定义一个集合,Scanner input = new Scanner(System.in);ArrayList<User> list = new ArrayList<>();// 存入三个用户对象for (int i = 0; i < 3; i++) {User ui = new User();System.out.println("输入用户的id:");String id = input.next();System.out.println("输入用户的username:");String username = input.next();System.out.println("输入用户的密码:");int password = input.nextInt();ui.setId(id);ui.setUsername(username);ui.setPassword(password);list.add(ui);}for (int i = 0; i < list.size(); i++) {User u = list.get(i);System.out.println(u.getId() + "," + u.getUsername() + "," + u.getPassword());}System.out.println("输入要查找的id:");String id = input.next();int b = func(id, list);System.out.println(b);}public static int func(String id, ArrayList<User> list) {for (int i = 0; i < list.size(); i++) {if (id.equals(list.get(i).getId())) {return i;}}return -1;}
}
截图:
视频代码:直接在contains方法中调用getIndex方法,这样不用再写一次循环