11
16

https://hyane.tistory.com/530

 

[JAVA] StringTokenizer, StringBuffer를 이용한 예제

* 아래의 결과가 나오도록 1~4의 조건을 보고 paring과 StrAppend를 작성하세요. (힌트: parsing-StringTokenizer이용, StrAppend-StringBuffer이용, 문자열과 숫자변환에는 Wrapper클래스 이용) Student 클래스 - 멤버변

hyane.tistory.com

↑기본 코드

 

1. 해시맵(key: 학번, value: Student 객체)생성

static HashMap<Integer,Student> makeHashMap(Student[] s)

2. Iterator를 이용하여 해시맵 출력

static void printHashMap(HashMap<Integer,Student> h)

3. 특정 key에 해당하는 Student 객체를 출력

static void searchHashMap(HashMap<Integer,Student> h, int key)

* 출력시 학생정보가 나오도록 Student 클래스에서 toString overriding 할 것

 


 

메인에서 새로운 메소드 만들어서 해쉬맵을 만들고 put하고 h 리턴, 또 새로운 메소드 만들어서 Integer 만들기.

searchHashMap h, key 가져와서 h.get(key)프린트.

 

toString 오버라이딩 해서 출력

 

이클립스 기준

이 결과를 봐야 함

import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
import java.util.StringTokenizer;

class Student{
	int num, c, java, net, tot;
	String name;
	String info;
	
	Student(String s){
		info = s;
		parsing(info);
	}
	
	void parsing(String s) {
		StringTokenizer st = new StringTokenizer(s,",");
		num = Integer.parseInt(st.nextToken());	//문자형이기 때문에 int형 변환
		name = st.nextToken();
		c = Integer.parseInt(st.nextToken());
		java = Integer.parseInt(st.nextToken());
		net = Integer.parseInt(st.nextToken());
		calTot();
	}
	
	void calTot() {
		tot = c + java + net;
	}
	
	void printInfo() {
		System.out.println(num+" "+name+" "+c+" "+java+" "+net+" "+tot);
	}
	
	String strAppend() {
		StringBuffer sb = new StringBuffer();
		sb.append(Integer.toString(num));	//문자열로 변환, 문자열 추가
		sb.append(" ");
		sb.append(name);
		sb.append(" ");
		sb.append(Integer.toString(tot));
		return sb.toString();
	}

	@Override
	public String toString() {
		return num+" "+name+" "+c+" "+java+" "+net+" "+tot;
	}
	
}

public class StudentEx {
	static HashMap<Integer, Student> makeHashMap(Student s[]){
		HashMap<Integer, Student> h = new HashMap<Integer,Student>();
		for(int i = 0; i < s.length; i++)
			h.put(s[i].num, s[i]);
		return h;
	}
	
	static void printHashMap(HashMap<Integer, Student> h) {
		Set<Integer> keys = h.keySet();
		Iterator<Integer> it = keys.iterator();
		
		while(it.hasNext()) {
			int key = it.next();	//toString 오버라이딩 하는 이유
			System.out.println(key+"==>"+h.get(key));	//객체를 프린트하려고 하면 toString으로 출력됨
		}
	}
	
	static void searchHashMap(HashMap<Integer, Student> h, int key) {
		System.out.println(h.get(key));
	}
	
	public static void main(String[] args) {
		Student []s = new Student[3];
		Scanner sc = new Scanner(System.in);
		for(int i = 0; i<s.length; i++) {
			System.out.print("Input num,name,c,java,net: ");
			s[i] = new Student(sc.nextLine());
		}
		for(int i = 0; i<s.length; i++) {
			System.out.println(s[i].strAppend());
		}
		
		HashMap<Integer, Student> h = makeHashMap(s);
		printHashMap(h);
		System.out.print("학번: ");
		int key = sc.nextInt();
		searchHashMap(h, key);
		
		sc.close();
	}
}

추가하는 것 번호 순대로 메인 메소드에 각각 만들어서 호출해줌.

728x90
반응형
COMMENT