[명품자바] 7장 실습문제(5~9)
난이도 6 이상만
5. 학생 정보 저장&출력 프로그램 [난이도 6]
- 학생 정보를 저장하는 Student 클래스
- Student 클래스는 이름, 학과, 학번(int), 학점 평균(double)을 저장하는 필드를 가짐
- 학생마다 Student 객체를 생성하고 4명의 학생 정보를 ArrayList<Student> 컬렉션에 저장한 후, ArrayList<Student>의 모- - 든 학생 정보를 출력하고 학생 이름을 입력받아 해당 학생의 학점 평균을 출력하는 프로그램을 작성
- 실행 예시

>>풀이
public class Student {
String name; //이름
String dept; //학과
int stdID; //학번
double gpa; //학점 평균
public Student(String name, String dept, int stdID, double gpa) {
this.name=name;
this.dept=dept;
this.stdID=stdID;
this.gpa=gpa;
}
@Override
public String toString() {
return String.format("이름: %s\n학과: %s\n학번: %d\n학점 평균: %.2f", name, dept, stdID, gpa);
}
}
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
ArrayList<Student> arr=new ArrayList<>();
HashMap<String, Student> hashmap=new HashMap<>();
Student std;
//학생마다 Student 객체 생성 후 정보 저장
System.out.println("학생 이름, 학과, 학번, 학점평균 입력하세요.");
for(int i=0; i<4; i++) {
System.out.print(">> ");
StringTokenizer st=new StringTokenizer(scanner.nextLine(), ",");
String name=st.nextToken().trim(); //hashmap 위해 이름 필드만 따로 빼 놓음
std=new Student(
name,
st.nextToken().trim(),
Integer.valueOf(st.nextToken().trim()),
Double.valueOf(st.nextToken().trim())
);
arr.add(std);
hashmap.put(name, std); //검색용
}
//모든 학생 정보 출력
arr.forEach(Student->{
//iterator 대신 for each문 사용
System.out.println("-".repeat(15));
System.out.println(Student);
});
System.out.println("-".repeat(15));
//이름을 입력받고 해당 학생의 학점 평균 출력
while(true) {
System.out.print("학생 이름 >> ");
String input=scanner.next();
if(input.equals("그만")) break;
else {
Student s=hashmap.get(input);
System.out.print(s.name+", "+s.dept+", "+s.stdID+", "+s.gpa);
}
System.out.println();
}
}
}
(2)번에서 ArrayList 대신 HashMap으로 다시 해 보라고 해서... 따로 두 개 하려니 귀찮아서 그냥 둘 다 섞어 풀었습니다
학생 정보 출력하는 부분에서 for문이나 iterator 사용해서 하려고 했는데 for each문이 더 편할 것 같아서 그냥 그렇게 함
아래는 원래 하려고 했었던for문입니다
for(int i=0; i<arr.size(); i++) {
System.out.println("-".repeat(15));
System.out.println("이름: "+arr.get(i).name);
System.out.println("학과: "+arr.get(i).dept);
System.out.println("학번: "+arr.get(i).stdID);
System.out.println("학점 평균: "+arr.get(i).gpa);
}
System.out.println("-".repeat(15));
6. 도시 이름 저장&검색 프로그램 [난이도 6]
- 도시 이름, 위도, 경도 정보를 가진 Location 클래스 작성
- 도시 이름을 Key로 하는 HashMap<String, Location> 컬렉션
- 사용자로부터 4개의 도시를 입력 받아 저장
- 도시 이름으로 검색
>> 실행 예시

Location 클래스
public class Location {
String cityName;
int latitude; //위도
int longtitude; //경도
public void showInfo() {
System.out.println(cityName+" "+latitude+" "+longtitude);
}
@Override
public String toString() {
return cityName+" "+latitude+" "+longtitude;
}
}
toString 오버라이딩하는 거 매일 까먹음;
객체+문자열 연산이나 객체 출력할 때 오버라이딩 해야 합니다
CityEx 클래스(main)
import java.util.*;
public class CityEx {
public void run() {
System.out.println("도시 이름, 위도, 경도를 입력하세요.");
Scanner scanner=new Scanner(System.in);
Location[] location=new Location[4];
HashMap<String, Location> hm=new HashMap<>();
for(int i=0; i<location.length; i++) {
System.out.print(">> ");
StringTokenizer st=new StringTokenizer(scanner.nextLine(), ", ");
location[i]=new Location();
location[i].cityName=st.nextToken();
location[i].latitude=Integer.parseInt(st.nextToken());
location[i].longtitude=Integer.parseInt(st.nextToken());
hm.put(location[i].cityName, location[i]);
}
System.out.println("-".repeat(20));
for(int i=0; i<hm.size(); i++) {
location[i].showInfo();
}
System.out.println("-".repeat(20));
while(true) {
System.out.print("도시 이름 >> ");
String input=scanner.next();
if(input.equals("그만")) {
System.out.println("종료합니다.");
break;
}
else if(hm.get(input)==null)
System.out.println(input+"은(는) 없습니다.");
else
System.out.println(hm.get(input));
}
}
public static void main(String[] args) {
CityEx c=new CityEx();
c.run();
}
}
7. 장학생 명단 출력 프로그램 [난이도 6]
- 이름과 학점(4.5 만점)을 5개 입력받아 해시맵에 저장
- 장학생 선발 기준 학점을 입력받아 장학생 명단 출력
>> 실행 예시

Student 클래스
public class Student {
String name;
double gpa;
public Student(String name, double gpa) {
this.name=name;
this.gpa=gpa;
}
public boolean isAvailable(double score) {
return gpa>=score;
}
@Override
public String toString() {
return name+" ";
}
}
ScholarshipEx 클래스(main)
import java.util.*;
public class ScholarshipEx {
public void run() {
System.out.println("장학금 관리 시스템입니다.");
Student[] std=new Student[5];
HashMap<Double, Student> hm=new HashMap<>();
Scanner scanner=new Scanner(System.in);
for(int i=0; i<std.length; i++) {
System.out.print("이름과 학점 >> ");
String[] input=scanner.nextLine().split(" ");
std[i]=new Student(input[0], Double.parseDouble(input[1]));
hm.put(std[i].gpa, std[i]);
}
System.out.print("장학생 선발 기준 학점 입력 >> ");
double score=scanner.nextDouble();
System.out.print("장학생 명단: ");
for(int i=0; i<std.length; i++) {
if(std[i].isAvailable(score))
System.out.print(hm.get(std[i].gpa));
}
}
public static void main(String[] args) {
ScholarshipEx s=new ScholarshipEx();
s.run();
}
}
8. 고객 관리 프로그램 [난이도 6]
- 고객의 이름과 포인트 정보를 저장
- 포인트가 추가될 때마다 갱신
>> 실행 예시

Customer 클래스
public class Customer {
String name;
int point;
public Customer(String name, int point) {
this.name=name;
this.point=point;
}
public void showCustomers() {
System.out.print("("+name+", "+point+")");
}
}
CustomerEx 클래스(main)
import java.util.*;
//iterator 사용
public class CustomerEx {
public void run() {
Scanner scanner=new Scanner(System.in);
HashMap<String, Customer> hm=new HashMap<>();
System.out.println("** 포인트 관리 프로그램입니다 **");
while(true) {
System.out.print("이름과 포인트 입력 >>");
String input=scanner.nextLine();
if(input.equals("그만")) {
System.out.println("종료합니다.");
break;
}
String[] inputSplit=input.split(" ");
String name=inputSplit[0];
int point=Integer.parseInt(inputSplit[1]);
if(hm.containsKey(name)) //이미 해시맵에 존재하는 고객일 때
hm.get(name).point+=point;
else
hm.put(name, new Customer(name, point));
//전체 출력
Set<String> keys=hm.keySet();
Iterator<String> it=keys.iterator();
while(it.hasNext()) {
String key=it.next();
Customer value=hm.get(key);
value.showCustomers();
}
System.out.println();
}
}
public static void main(String[] args) {
CustomerEx c=new CustomerEx();
c.run();
}
}
- iterator 사용해서 해시맵 전체 요소 출력
import java.util.*;
//iterator 없이
public class CustomerEx {
public void run() {
Scanner scanner=new Scanner(System.in);
HashMap<String, Customer> hm=new HashMap<>();
System.out.println("** 포인트 관리 프로그램입니다 **");
while(true) {
System.out.print("이름과 포인트 입력 >>");
String input=scanner.nextLine();
if(input.equals("그만")) {
System.out.println("종료합니다.");
break;
}
String[] inputSplit=input.split(" ");
String name=inputSplit[0];
int point=Integer.parseInt(inputSplit[1]);
if(hm.containsKey(name)) //이미 해시맵에 존재하는 고객일 때
hm.get(name).point+=point;
else
hm.put(name, new Customer(name, point));
//전체 출력
for (Customer customer : hm.values()) {
customer.showCustomers();
}
System.out.println();
}
}
public static void main(String[] args) {
CustomerEx c=new CustomerEx();
c.run();
}
}
- iterator 안 쓰고 출력
9. IStack 인터페이스 구현 [난이도 6]
interface IStack<T>{
T pop();
boolean push(T ob);
}
- IStack<T> 인터페이스를 구현하는 MyStack<T> 클래스 작성
- 스택 원소는 Vector<E>를 이용하여 저장
public class StackManager {
public static void main(String[] args) {
IStack<Integer> stack=new MyStack<Integer>();
for(int i=0; i<10; i++) stack.push(i);
while(true) {
Integer n=stack.pop();
if(n==null) break;
System.out.print(n+" ");
}
}
}
- MyStack<Integer>로 구체화한 정수 스택을 생성하고 활용하는 코드
- 실행 결과 "9 8 7 6 5 4 3 2 1 0" 출력
MyStack<T> 클래스
import java.util.Vector;
interface IStack<T>{
T pop();
boolean push(T ob);
}
public class MyStack<T> implements IStack<T> {
Vector<T> v=new Vector<>();
@Override
public T pop() {
if(v.size()==0)
return null;
T pop=v.get(v.size()-1);
v.remove(v.size()-1);
return pop;
}
@Override
public boolean push(T ob) {
v.add(ob);
return true;
}
}