ArrayList 상당히 길다. Map으로 사용한다면 이보다 더 간단히 코딩할 수 있다.
public class Main {
static List<Student> stdList = new ArrayList<>();
public Main() {
stdList.add(new Student("dsg", 1001));
stdList.add(new Student("kmb", 1002));
}
public class Student{
String name;
Integer no;
public Student(String name, Integer no) {
this.name = name;
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getNo() {
return no;
}
public void setNo(Integer no) {
this.no = no;
}
}
public String solution(String name) {
int no = 0;
for (Student stu : stdList) {
if (stu.name.equals(name)) {
no = stu.getNo();
}
}
return String.valueOf(no);
}
public static void main(String[] args) {
Main T = new Main();
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
System.out.println(T.solution(name));
}
}
public class Main {
static Map<String, Integer> students = new HashMap<>();
public Main() {
students.put("dsg", 1001);
students.put("kmb", 1002);
}
public String solution(String name) {
if(!students.containsKey(name)){
return "없는 학생이름입니다.";
}
return String.valueOf(students.get(name));
}
public static void main(String[] args) {
Main T = new Main();
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
System.out.println(T.solution(name));
}
}