StringBuffer
import java.util.StringTokenizer;
public class StringBufferEx {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("This");
System.out.println(sb);
sb.append(" is pencil.");
System.out.println(sb);
sb.insert(8, "my "); // 8번째 인덱스에 my를 추가할 것
System.out.println(sb);
sb.replace(8, 10, "your"); // 8-10번째 인덱스를 your로 바꿀 것
System.out.println(sb);
sb.delete(8, 13); // 8-13 인덱스를 지울 것
System.out.println(sb);
String query = "name=kitae&addr=seoul&age=21";
StringTokenizer st = new StringTokenizer(query, "&"); // 쿼리를 &기준으로 잘라서 객체로 보관하겠다
while (st.hasMoreTokens()) {
System.out.print(st.nextToken() + "\t");
}
System.out.println();
for (int i = 0; i < st.countTokens(); i++) {
System.out.print(st.nextToken() + "\t");
}
String txt = "릴리/아이리스/로즈/아네모네";
String[] txtArr = txt.split("/"); // 문장을 /기준으로 잘라서 배열로 보관하겠다
for (int i = 0; i < txtArr.length; i++) {
System.out.print(txtArr[i] + "\t");
}
System.out.println();
String txt02 = "릴리/아이리스/로즈/아네모네:토끼:고양이:강아지";
StringTokenizer st02 = new StringTokenizer(txt02, ":/");
// :와 / 둘 다기준으로 하여 잘라 객체로 보관하겠다
while (st02.hasMoreTokens()) {
System.out.print(st02.nextToken() + "\t");
}
System.out.println();
}
}
### 출력
This
This is pencil.
This is my pencil.
This is your pencil.
This is pencil.
name=kitae addr=seoul age=21
릴리 아이리스 로즈 아네모네
릴리 아이리스 로즈 아네모네 토끼 고양이 강아지
Math
import java.util.Arrays;
public class MathEx {
public static boolean exist(int num, int[] numArr) {
for (int i = 0; i < numArr.length; i++) {
if (num == numArr[i]) {
return true;
}
}
return false;
}
public static void main(String[] args) {
System.out.println(Math.PI);
System.out.println(Math.ceil(3.14));
System.out.println(Math.floor(Math.PI));
System.out.println(Math.sqrt(9)); // 루트(제곱근) 구하기
System.out.println(Math.exp(2)); // e^x(:파라미터) 값을 반환 (자연상수 e : 2.71)
System.out.println(Math.round(Math.PI));
int[] count = new int[6];
int index = 0;
for (int i = 0; i < count.length; i++) {
do { // 중복 안 되게 로또 번호 추출
index = (int) (Math.random() * 45) + 1;
} while (MathEx.exist(index, count));
count[i] = index;
}
Arrays.sort(count); // 오름차순 정렬
for (int i = 0; i < count.length; i++) {
System.out.print(count[i] + " ");
}
}
}
### 출력
3.141592653589793
4.0
3.0
3.0
7.38905609893065
3
1 2 6 26 37 42
Calendar
import java.util.Calendar;
public class CalendarEx {
public static void main(String[] args) {
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH) + 1;
int day = now.get(Calendar.DAY_OF_WEEK);
//int day2 = now.get(Calendar.DAY_OF_MONTH);
int hour = now.get(Calendar.HOUR);
String yoil;
// prettier-ignore
if (day == 1) yoil = "일";
else if (day == 2) yoil = "월"; else if (day == 3) yoil = "화";
else if (day == 4) yoil = "수"; else if (day == 5) yoil = "목";
else if (day == 6) yoil = "금"; else if (day == 7) yoil = "토";
else yoil = "None";
// prettier-ignore
System.out.println(
year + "년\t" + month + "월\t" + yoil + "요일(" + day + ")\t" + hour + "시"
);
System.out.println(Calendar.HOUR_OF_DAY);
System.out.println(Calendar.AM_PM);
}
}
### 출력
2023년 2월 목요일(5) 10시
11
9
실습
데이터 변형
package Practice;
public class Practice050607 {
public static void main(String[] args) {
/*** 6 */
// (1)
Integer s1 = new Integer(20);
int s1Val = s1.intValue();
System.out.println(s1Val);
// (2)
String str = "35.9";
double d = Double.valueOf(str);
System.out.println(d);
// (3)
String str2 = "true";
boolean b = Boolean.valueOf(str2);
System.out.println(b);
// (4)
String biNum = Integer.toBinaryString(30);
System.out.println(biNum);
// (5)
String c = String.valueOf('c');
System.out.println(c);
/*** 7 */
// (1)
String a = "가나다";
String b1 = new String(a);
System.out.println(a + "/" + b1);
System.out.println(a == b1);
// false가 나옴. 서로 다른 객체이기 때문.
// 반면에 -> System.out.println(a.equals(b1)); 이건 true가 나옴
/*** 8 */
String a8 = new String(" Oh, Happy ");
String b8 = a8.trim();
String c8 = b8.concat(" Day.");
System.out.println(a8 + "\n" + b8 + "\n" + c8);
}
}
### 출력
20
35.9
true
11110
c
가나다/가나다
false
Oh, Happy
Oh, Happy
Oh, Happy Day.
객체를 배열로 생성
import java.util.Scanner;
class Person2 {
private String name;
private int[] gameResult = new int[3];
Scanner sc = new Scanner(System.in);
public Person2(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int[] getGameResult() {
return this.gameResult;
}
public int[] playGamble() {
System.out.print(name + " 님 게임을 시작합니다 (Enter) >> ");
sc.nextLine();
for (int i = 0; i < gameResult.length; i++) {
gameResult[i] = (int) ((Math.random()) * 3) + 1;
}
if (!jackpot(gameResult)) {
for (int i = 0; i < gameResult.length; i++) {
System.out.print("\t" + gameResult[i] + "\t");
}
System.out.println(" ( " + name + "님 이겼습니다. ) ");
} else {
for (int i = 0; i < gameResult.length; i++) {
System.out.print("\t" + gameResult[i] + "\t");
}
System.out.println(" ( " + name + "님 아쉽군요! ) ");
}
return gameResult;
}
public boolean jackpot(int[] gameResult) {
int num = gameResult[0];
for (int i = 0; i < gameResult.length; i++) {
if (gameResult[i] != num) {
return true; // 게임에서 졌음
}
}
return false; // 게임에서 이겼음
}
}
public class Gambling2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("게임에 참가할 선수 숫자 >> ");
int participants = scanner.nextInt();
Person2[] players = new Person2[participants];
for (int i = 0; i < players.length; i++) {
System.out.print((i + 1) + " 번째 선수 이름 >> ");
String name = scanner.next();
players[i] = new Person2(name);
}
boolean gameEnding = true;
while (gameEnding) {
int res[] = {};
for (int i = 0; i < players.length; i++) {
res = players[i].playGamble();
gameEnding = players[i].jackpot(res);
if (!gameEnding) {
System.out.println(players[i].getName() + " 님의 승리로 종료");
break;
}
}
}
scanner.close();
}
}
Calendar 응용
package practice;
import java.util.Calendar;
import java.util.Scanner;
class Player01 {
private String name;
private Scanner scanner = new Scanner(System.in);
public Player01(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public int turn() {
// 현재 시간 추출
System.out.println(name + "님 시작 enter를 누르세요.");
scanner.nextLine();
Calendar calendar = Calendar.getInstance();
int startSec = calendar.get(Calendar.SECOND);
System.out.println("현재 초 : " + startSec);
System.out.println("10초 기다렸다가 enter 눌러주세요.");
scanner.nextLine();
calendar = Calendar.getInstance();
int endSec = calendar.get(Calendar.SECOND);
if (startSec > endSec) {
endSec += 60;
}
System.out.println("현재 초 : " + endSec);
return Math.abs(endSec - startSec);
}
}
class Game {
public void run() {
Player01 p01 = new Player01("황기태");
Player01 p02 = new Player01("이재문");
System.out.println("10초에 가깝게 누른 사람이 승리하는 게임입니다.");
int duration01 = p01.turn();
int duration02 = p02.turn();
System.out.println(
p01.getName() +
"의 결과 " +
duration01 +
"===" +
p02.getName() +
"의 결과 " +
duration02
);
System.out.println("두구두구두구 둥둥둥 승자는 : ");
if (Math.abs(10 - duration01) < Math.abs(10 - duration02)) {
System.out.println(p01.getName() + "님 승리");
} else if (Math.abs(10 - duration01) > Math.abs(10 - duration02)) {
System.out.println(p02.getName() + "님 승리");
} else {
System.out.println("비김");
}
}
}
public class Practice06 {
public static void main(String[] args) {
Game game = new Game();
game.run();
}
}
Vector
Ex.01
import java.util.Vector;
public class VectorEx {
public static void main(String[] args) {
Vector<Integer> vec = new Vector<>();
vec.add(1);
vec.add(3);
vec.add(4);
System.out.println(vec.size());
vec.add(1, 2);
for (int i = 0; i < vec.size(); i++) {
System.out.print(vec.get(i) + " ");
}
System.out.println();
for (int item : vec) {
System.out.print(item + " ");
}
}
}
Ex.02
package Practice;
import java.util.Scanner;
import java.util.Vector;
public class Practice01 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Vector<Integer> vec = new Vector<>();
int biggest = 0;
while (true) {
System.out.print("정수 입력 (until -1) >> ");
int num01 = sc.nextInt();
if (num01 == -1) break;
vec.add(num01);
}
for (int i = 0; i < vec.size() - 1; i++) {
if (vec.get(biggest) < vec.get(i)) {
biggest = i;
}
}
System.out.println("제일 큰 수는 : " + vec.get(biggest));
sc.close();
}
}
Iterator
import java.util.Iterator;
import java.util.Vector;
public class IteratorEx {
public void main(String[] args) {
Vector<Integer> vec = new Vector<>();
vec.add(1);
vec.add(2);
vec.add(2, 3);
vec.add(88);
vec.add(77);
vec.add(99);
Iterator<Integer> it = vec.iterator(); // 순환 가능한지 아닌지
int sum = 0;
while (it.hasNext()) {
int num = it.next();
System.out.print(num + " : " + it.hasNext() + "\n");
sum += num;
}
System.out.println("sum : " + sum);
}
}
ArrayList
Ex.01
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayListEx {
public static void main(String[] args) {
ArrayList<String> arrlist = new ArrayList<>();
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 4; i++) {
System.out.print("이름 입력 >> ");
String name = sc.nextLine();
arrlist.add(name);
}
int longest = 0;
for (int i = 0; i < arrlist.size(); i++) {
if (arrlist.get(longest).length() < arrlist.get(i).length()) {
longest = i;
}
}
System.out.println("이름 제일 긴 사람 : " + arrlist.get(longest));
sc.close();
}
}
Ex.02
package Practice;
import java.util.ArrayList;
import java.util.Scanner;
class Student {
private String stuName;
private String stuDepart;
private String stuNum;
private double stuGrade;
public String getStuName() {
return this.stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public String getStuDepart() {
return this.stuDepart;
}
public void setStuDepart(String stuDepart) {
this.stuDepart = stuDepart;
}
public String getStuNum() {
return this.stuNum;
}
public void setStuNum(String stuNum) {
this.stuNum = stuNum;
}
public double getStuGrade() {
return this.stuGrade;
}
public void setStuGrade(double stuGrade) {
this.stuGrade = stuGrade;
}
}
public class Practice05 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<Student> students = new ArrayList<>();
while (true) {
Student stu = new Student();
System.out.print(
"학생 이름, 학과, 학번, 학점평균 입력 (학생 이름에 '그만' 적으면 종료) >>>> "
);
String stuInfo = sc.nextLine();
String[] stuInfos = stuInfo.split(", ");
if (stuInfos[0].equals("그만")) break;
stu.setStuName(stuInfos[0]);
stu.setStuDepart(stuInfos[1]);
stu.setStuNum(stuInfos[2]);
String stuNumStr = stuInfos[3];
double stuNum = Double.parseDouble(stuNumStr);
stu.setStuGrade(stuNum);
students.add(stu);
}
System.out.println("----------------------------------------");
for (int i = 0; i < students.size(); i++) {
System.out.println("이름 : " + students.get(i).getStuName());
System.out.println("학과 : " + students.get(i).getStuDepart());
System.out.println("학번 : " + students.get(i).getStuNum());
System.out.println("학점평균 : " + students.get(i).getStuGrade());
System.out.println("----------------------------------------");
}
sc.close();
}
}
HashMap
- Map, Entry와 함께 써서 인덱스로 접근하듯 사용할 수도 있다.
01
// Entry 사용
int count = 0;
for (Map.Entry<Integer, String> pair : map.entrySet()) {
if (count % 10 == 0 && count != 0) System.out.println();
System.out.print(pair.getKey() + ":" + pair.getValue() + "\t");
count++;
}
System.out.println("\n");
// Iterator 사용
Iterator<Map.Entry<Integer, String>> itr = map.entrySet().iterator();
02
for (Map.Entry<String, String> pair : nations.entrySet()) {
System.out.print(pair.getKey() + ":" + pair.getValue() + "\t");
}
Ex.01
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class HashMapEx {
public static void main(String[] args) {
// 비교 : 파이썬의 딕셔너리
HashMap<Integer, String> map = new HashMap<>();
for (int i = 0; i < 30; i++) {
map.put(i, "글" + (i + 1));
}
for (int i = 0; i < map.size(); i++) {
if ((i % 10 == 0) && !(i == 0)) System.out.println();
System.out.print(map.get(i) + "\t");
}
System.out.println("\n");
// Entry 사용
int count = 0;
for (Map.Entry<Integer, String> pair : map.entrySet()) {
if (count % 10 == 0 && count != 0) System.out.println();
System.out.print(pair.getKey() + ":" + pair.getValue() + "\t");
count++;
}
System.out.println("\n");
// Iterator 사용
Iterator<Map.Entry<Integer, String>> itr = map.entrySet().iterator();
count = 0;
while (itr.hasNext()) {
Map.Entry<Integer, String> entry = itr.next();
if (count % 10 == 0 && count != 0) System.out.println();
System.out.print(entry.getKey() + ":" + entry.getValue() + "\t");
count++;
}
}
}
Ex.02
Split()으로 풀기
package Practice;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Practice07 {
public static void main(String[] args) {
HashMap<String, Double> maps = new HashMap<>();
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.print("이름, 학점을 입력 (홍길동 4.1) >> ");
String input = sc.nextLine();
String[] scholars = input.split(" ");
Double grade = Double.parseDouble(scholars[1]);
maps.put(scholars[0], grade);
}
//int genius = 0;
double scholarGrade = 0;
String scholarName = "";
for (Map.Entry<String, Double> pair : maps.entrySet()) {
if (pair.getValue() > scholarGrade) {
scholarGrade = pair.getValue();
scholarName = pair.getKey();
}
}
if (scholarGrade < 3.2) {
System.out.println("기준에 준하는 학생이 없으므로 장학생 선발 유예.");
} else if (scholarGrade >= 3.2) {
System.out.println(
"장학생 명단 : " + scholarName + " (" + scholarGrade + ")"
);
}
sc.close();
}
}
StringTokenizer로 풀기
package Practice;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.StringTokenizer;
class ScholarManager {
HashMap<String, Double> maps = new HashMap<>();
Scanner sc = new Scanner(System.in);
public void insertScholar(int num) {
for (int i = 0; i < num; i++) {
System.out.print("이름, 학점을 입력 (홍길동 4.1) >> ");
String input = sc.nextLine();
StringTokenizer st = new StringTokenizer(input, " ");
String name = st.nextToken().trim();
Double grade = Double.parseDouble(st.nextToken().trim());
maps.put(name, grade);
}
}
public void selectScholar() {
double scholarGrade = 0;
String scholarName = "";
for (Map.Entry<String, Double> pair : maps.entrySet()) {
if (pair.getValue() > scholarGrade) {
scholarGrade = pair.getValue();
scholarName = pair.getKey();
}
}
System.out.print("장학점 기준 >>> ");
double scholarPoint = sc.nextDouble();
if (scholarGrade < scholarPoint) {
System.out.println("기준에 준하는 학생이 없으므로 장학생 선발 유예.");
} else if (scholarGrade >= scholarPoint) {
System.out.println(
"장학생 명단 : " + scholarName + " (" + scholarGrade + ")"
);
}
}
}
public class Practice07 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ScholarManager sm = new ScholarManager();
System.out.print("몇 명의 학생이 장학생 판별 대상입니까 (정수입력) >>> ");
int num = sc.nextInt();
sm.insertScholar(num);
sm.selectScholar();
sc.close();
}
}
Ex.03
package Practice;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
/*** 3번 문제 */
public class Practice03 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
HashMap<String, String> nations = new HashMap<>();
// 입력해서 HashMap에 넣기
while (true) {
System.out.print("나라 이름과 인구 입력 (ex. Korea 5000) >>> ");
String input = sc.nextLine();
if (input.equals("그만")) {
break;
}
String[] inputArr = input.split(" ");
nations.put(inputArr[0], inputArr[1]);
}
// 출력하기
for (Map.Entry<String, String> pair : nations.entrySet()) {
System.out.print(pair.getKey() + ":" + pair.getValue() + "\t");
}
System.out.println("\n");
// 인구 검색
while (true) {
System.out.print("인구 검색 >>> ");
String searchPop = sc.next();
if (searchPop.equals("그만")) {
break;
}
if (nations.get(searchPop) != null) {
System.out.println(searchPop + "의 인구는 " + nations.get(searchPop));
} else {
System.out.println(searchPop + "라는 나라는 자료에 없습니다.");
}
}
sc.close();
}
}
Ex.04
Split()으로 풀기
package Practice;
// 6번 문제
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
class Location {
private String cityName;
private String latitude;
private String longitude;
public String getCityName() {
return this.cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getLatitude() {
return this.latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return this.longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
}
public class Practice06 {
public static void main(String[] args) {
HashMap<String, Location> locations = new HashMap<>();
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 4; i++) {
Location lc = new Location();
System.out.print("도시이름, 위도, 경도를 입력하세요 >>>> ");
String loca = sc.nextLine();
String[] location = loca.split(", ");
lc.setCityName(location[0]);
lc.setLatitude(location[1]);
lc.setLongitude(location[2]);
locations.put(lc.getCityName(), lc);
}
Iterator<Map.Entry<String, Location>> iteratorE = locations
.entrySet()
.iterator();
System.out.println("-------------");
while (iteratorE.hasNext()) {
Map.Entry<String, Location> entry = (Map.Entry<String, Location>) iteratorE.next();
String key = entry.getKey();
Location value = entry.getValue();
System.out.println(
key + "\t" + value.getLatitude() + "\t" + value.getLongitude()
);
}
System.out.println("-------------");
while (true) {
System.out.print("도시 이름 >>> ");
String search = sc.next();
if (search.equals("그만")) break;
if (locations.containsKey(search)) {
Location lc = locations.get(search);
System.out.println(
lc.getCityName() + "\t" + lc.getLatitude() + "\t" + lc.getLongitude()
);
} else {
System.out.println("그런 나라 없음.");
}
}
sc.close();
}
}
StringTokenizer로 풀기
package Practice;
// 6번 문제
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.StringTokenizer;
class Location {
private String cityName;
private Double latitude;
private Double longitude;
public String getCityName() {
return this.cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public Double getLatitude() {
return this.latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLongitude() {
return this.longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
}
class locationManager {
Location lc;
HashMap<String, Location> locations = new HashMap<>();
Scanner sc = new Scanner(System.in);
public void insertLocation(int num) {
for (int i = 0; i < num; i++) {
lc = new Location();
System.out.print("도시이름, 위도, 경도를 입력하세요 >>>> ");
String loca = sc.nextLine();
//String[] location = loca.split(", ");
StringTokenizer st = new StringTokenizer(loca, ",");
String cityName = st.nextToken().trim();
String latitude = st.nextToken().trim();
String longitude = st.nextToken().trim();
lc.setCityName(cityName);
lc.setLatitude(Double.parseDouble(latitude));
lc.setLongitude(Double.parseDouble(longitude));
locations.put(lc.getCityName(), lc);
}
}
public void showAll() {
Iterator<Map.Entry<String, Location>> iteratorE = locations
.entrySet()
.iterator();
System.out.println("-------------");
while (iteratorE.hasNext()) {
Map.Entry<String, Location> entry = (Map.Entry<String, Location>) iteratorE.next();
String key = entry.getKey();
Location value = entry.getValue();
System.out.println(
key + "\t" + value.getLatitude() + "\t" + value.getLongitude()
);
}
System.out.println("-------------");
}
public void showInfo() {
while (true) {
System.out.print("도시 이름 >>> ");
String search = sc.next();
if (search.equals("그만")) break;
if (locations.containsKey(search)) {
Location lc = locations.get(search);
System.out.println(
lc.getCityName() + "\t" + lc.getLatitude() + "\t" + lc.getLongitude()
);
} else {
System.out.println("그런 나라 없음.");
}
}
}
}
public class Practice06 {
public static void main(String[] args) {
//HashMap<String, Location> locations = new HashMap<>();
Scanner sc = new Scanner(System.in);
locationManager lm = new locationManager();
lm.insertLocation(4);
lm.showAll();
lm.showInfo();
sc.close();
}
}