/*
이 소스 파일은 WinApi의 자바 강좌에서 작성한 예제들입니다.
각 예제별로 주석 처리되어 있으므로 주석 시작 위치에 /를 하나 더 삽입하여
주석을 푼 후 실행해 보시면 됩니다.
*/
/////////////////////////////////////////////////////////////////////
//1장. 자바
/* 첫 번째 예제
public class JavaExam {
public static void main(String[] args) {
System.out.println("Java Example Program");
}
}
//*/
/* print와 println
class JavaExam {
public static void main(String args[]) {
System.out.println("One");
System.out.println("Two");
System.out.print("One");
System.out.print("Two");
}
}
//*/
/* 여러 개의 변수 한꺼번에 출력하기
class JavaExam {
public static void main(String args[]) {
int i = 123;
double d = 3.14;
String str = "문자열";
System.out.println("i = " + i + ", d = " + d + ", str = " + str);
}
}
//*/
/* printf
class JavaExam {
public static void main(String args[]) {
int i = 123;
double d = 3.14;
String str = "문자열";
System.out.printf("i = %d, d = %f, str = %s\n", i, d, str);
System.out.printf("i = %3$d, d = %2$f, str = %1$s\n", str, d, i, d);
System.out.printf("__%5d__%-5d__%05d__%8.2f__\n", i, i, i, d);
}
}
//*/
/* 문자 단위 입력 - 바이트 스트림이라 한글은 안됨
import java.io.*;
class JavaExam {
public static void main(String args[]) {
int name;
System.out.println("이름을 입력한 후 Enter를 누르시오(끝낼 때는 Ctrl+Z).");
for (;;) {
try {
name = System.in.read();
if (name == -1) break;
System.out.print((char)name);
}
catch (IOException e) {
System.out.println("input error");
}
}
System.out.println("입력완료");
}
}
//*/
/* 문자 단위 입력 - 한글도 가능
import java.io.*;
class JavaExam {
public static void main(String args[]) {
int name;
System.out.println("이름을 입력한 후 Enter를 누르시오(끝낼 때는 Ctrl+Z).");
InputStreamReader r = new InputStreamReader(System.in);
for (;;) {
try {
name = r.read();
if (name == -1) break;
System.out.print((char)name);
}
catch (java.io.IOException e) {
System.out.println("input error");
}
}
System.out.println("입력완료");
}
}
//*/
/* 줄 단위 입력
import java.io.*;
class JavaExam {
public static void main(String args[]) {
InputStreamReader r = new InputStreamReader(System.in);
BufferedReader b = new BufferedReader(r);
try {
String str = b.readLine();
System.out.println(str);
System.out.println("입력완료");
}
catch (IOException e) {
System.out.println("input error");
}
}
}
//*/
/* 정수를 입력받아서 2배하여 출력하기
import java.io.*;
class JavaExam {
public static void main(String args[]) {
System.out.print("정수를 입력하시오 : ");
InputStreamReader r = new InputStreamReader(System.in);
BufferedReader b = new BufferedReader(r);
try {
String str = b.readLine();
int i = Integer.parseInt(str);
System.out.println("입력값의 2배 = " + i*2);
}
catch (IOException e) {
System.out.println("input error");
}
}
}
//*/
/////////////////////////////////////////////////////////////////////
//2장. 기본 문법
/* 변수 선언 및 대입
class JavaExam {
public static void main(String args[]) {
int value;
value = 1234;
System.out.println(value);
}
}
//*/
/* 부동 소수점의 오차
class JavaExam {
public static void main(String args[]) {
float f = 0f;
for (int i = 0; i < 1000; i++) {
f += 0.1f;
}
System.out.println(f);
}
}
//*/
/* 진위형 변수
class JavaExam {
public static void main(String args[]) {
int a = 3;
boolean b = (a == 3);
if (b) {
System.out.println("a가 3이다.");
}
}
}
//*/
/* 문자형 변수
class JavaExam {
public static void main(String args[]) {
char ch = '한';
System.out.println(ch);
//short s = ch;
int i = ch;
}
}
//*/
/* 문자열 변수
class JavaExam {
public static void main(String args[]) {
String str = "아름다운 이땅에 금수강산에\n" +
"단군 할아버지가 \"터\"잡으시고";
for (int i = 0; i < str.length(); i++) {
System.out.print(str.charAt(i));
}
}
}
//*/
/* 배열 선언 및 사용
class JavaExam {
public static void main(String args[]) {
int[] ar;
ar = new int[10];
for (int i =0;i<5;i++) {
ar[i]=i*2;
System.out.println(ar[i]);
}
}
}
//*/
/* 배열 초기화
class JavaExam {
public static void main(String args[]) {
int[] ar = { 8, 9, 0, 6, 2 };
//for (int i =0;i<5;i++) {
for (int i =0;i<ar.length;i++) {
System.out.println(ar[i]);
}
}
}
//*/
/* 배열 재초기화
class JavaExam {
public static void main(String args[]) {
int[] ar = { 8, 9, 0, 6, 2 };
ar = new int[] { 9, 1, 7, 6, 0, 0, 4, 0, 5, 1 };
for (int i =0;i<ar.length;i++) {
System.out.println(ar[i]);
}
}
}
//*/
/* 2차원 배열 초기화
class JavaExam {
public static void main(String args[]) {
int[][] ar = {
{ 77, 56, 70, 82},
{ 99, 96, 89, 88},
{ 81, 69, 62, 80}
};
for (int student = 0;student < ar.length; student++) {
for (int subject = 0;subject < ar[0].length;subject++) {
System.out.print(ar[student][subject] + " ");
}
System.out.println("");
}
}
}
//*/
/* Ragged 배열
class JavaExam {
public static void main(String args[]) {
int[][] ar;
ar = new int[3][];
ar[0] = new int[3];
ar[1] = new int[2];
ar[2] = new int[4];
for (int i =0;i < ar.length;i++) {
System.out.println(ar[i].length);
}
}
}
//*/
/* 조건문
class JavaExam {
public static void main(String args[]) {
int age = 21;
if (age >= 19) {
System.out.println("당신은 성인입니다.");
} else {
System.out.println("애들은 가라.");
}
}
}
//*/
/* for문으로 합계 구하기
class JavaExam {
public static void main(String args[]) {
int sum = 0;
for (int i = 1; i <= 100; i++){
sum += i;
}
System.out.println(sum);
}
}
//*/
/* 원주율 구하기
class JavaExam {
public static void main(String args[]) {
double pie=0;
int mother;
double sign=1.0;
for (mother=1;mother < 1000000;mother+=2) {
pie += (1.0/mother)*sign;
sign = -sign;
}
pie *= 4;
System.out.println("pie = " + pie);
}
}
//*/
/* for문의 제어 변수 - 에러 처리됨
class JavaExam {
public static void main(String args[]) {
int i = 10;
for (int i = 0; i <= 5; i++) {
System.out.println("루프 실행중");
}
System.out.println("i = " + i);
}
}
//*/
/* 두 개의 제어 변수
class JavaExam {
public static void main(String args[]) {
for (int i = 0, j = 1; i < 5; i++, j += 2){
System.out.printf("i = %d, j = %d\n", i, j);
}
}
}
//*/
/* 배열 순회
class JavaExam {
public static void main(String args[]) {
int[] ar = { 8, 9, 0, 6, 2 };
for (int i : ar) {
System.out.println(i);
}
}
}
//*/
/* while 문으로 합계 구하기
class JavaExam {
public static void main(String args[]) {
int sum = 0;
int i = 1;
while (i <= 100) {
sum += i;
i++;
}
System.out.println(sum);
}
}
//*/
/* do while 문으로 합계 구하기
class JavaExam {
public static void main(String args[]) {
int sum = 0;
int i = 1;
do {
sum += i;
i++;
} while (i <= 100);
System.out.println(sum);
}
}
//*/
/* 무한 루프와 break로 최소 공배수 찾기
class JavaExam {
public static void main(String args[]) {
int a = 6;
int b = 8;
int k = 1;
for (;;) {
if (k % a == 0 && k % b == 0) {
break;
}
k++;
}
System.out.printf("%d와 %d의 최소 공배수 = %d", a, b, k);
}
}
//*/
/* 이중 루프 탈출
class JavaExam {
public static void main(String args[]) {
outer:
for (int i = 0; i < 3 ; i++) {
for (int j = 0; j < 3; j++) {
if (i == 1 && j == 1)
break outer;
System.out.println("i = " + i + ", j = " + j);
}
}
}
}
//*/
/* switch 문
class JavaExam {
public static void main(String args[]) {
int num = 3;
switch (num) {
case 1:
System.out.println("하나");
break;
case 2:
System.out.println("둘");
break;
case 3:
System.out.println("셋");
break;
case 4:
System.out.println("넷");
break;
case 5:
System.out.println("다섯");
break;
default:
System.out.println("그 외의 숫자");
break;
}
}
}
//*/
/* 사칙 연산
class JavaExam {
public static void main(String args[]) {
int a = 4, b = 3;
System.out.printf("%d + %d = %d\n", a, b, a + b);
System.out.printf("%d - %d = %d\n", a, b, a - b);
System.out.printf("%d * %d = %d\n", a, b, a * b);
System.out.printf("%d / %d = %d\n", a, b, a / b);
System.out.printf("%d / %d = %f\n", a, b, (double)a / b);
System.out.printf("%d %% %d = %d\n", a, b, a % b);
System.out.printf("%f %% %f = %f\n", 5.0, 2.3, 5.0 % 2.3);
}
}
//*/
/* 문자열 연결
class JavaExam {
public static void main(String args[]) {
System.out.println(12 + 34);
System.out.println("miss" + "kim");
System.out.println("miss" + 12);
System.out.println(12 + "miss");
System.out.println("miss" + 12 + 34);
System.out.println(12 + 34 + "miss");
System.out.println("" + 12 + 34 + "miss");
}
}
//*/
/* 삼항 조건 연산자
class JavaExam {
public static void main(String args[]) {
int a = -3;
int absa = (a > 0 ? a:-a);
System.out.println(absa);
System.out.println(a == 3 ? 3:"3이 아님");
}
}
//*/
/* 증가 연산자
class JavaExam {
public static void main(String args[]) {
int a = 3;
System.out.println(a++);
System.out.println(++a);
}
}
//*/
/* 비교 연산자와 논리 연산자
class JavaExam {
public static void main(String args[]) {
int a = 1, b = 2;
if (a == 1 && b == 2) {
System.out.println("OK1");
}
if (a != 1 || b == 3) {
System.out.println("OK2");
}
if (a > 1 && b == 2) {
System.out.println("OK3");
}
}
}
//*/
/////////////////////////////////////////////////////////////////////
//3장.클래스
/* Car 클래스
class Car {
String Name;
String Color;
boolean Gasoline;
void Run() {
if (Gasoline) {
System.out.println("부릉 부릉");
} else {
System.out.println("덜컹 덜컹");
}
}
void Stop() {
System.out.println("끼이익");
}
}
class JavaExam {
public static void main(String args[]) {
Car Pride = new Car();
Pride.Name = "프라이드";
Pride.Color = "파랑";
Pride.Gasoline = true;
Pride.Run();
Pride.Stop();
}
}
//*/
/* 메소드 오버로딩
class Adder {
static int Add(int a, int b) { return a + b; }
static int Add(int a, int b, int c) { return a + b + c; }
static double Add(double a, double b) { return a + b; }
//long Add(int a, int b) { return (long)(a + b); }
}
class JavaExam {
public static void main(String args[]) {
System.out.println(Adder.Add(1,2));
System.out.println(Adder.Add(1,2,3));
System.out.println(Adder.Add(1.2,3.4));
}
}
//*/
/* 가변인수
class Adder {
static int Add(int ... a) {
int sum = 0;
for (int i=0;i<a.length;i++) {
sum += a[i];
}
//for (int i : a) {
// sum += i;
//}
return sum;
}
}
class JavaExam {
public static void main(String args[]) {
System.out.println(Adder.Add(1,2));
System.out.println(Adder.Add(1,2,3));
System.out.println(Adder.Add(4,5,6));
}
}
//*/
/* 값과 참조
class Car {
String Name;
}
class JavaExam {
public static void main(String args[]) {
int Value = 1;
int Value2 = Value;
Value2 = 2;
System.out.println(Value);
Car Pride = new Car();
Pride.Name = "프라이드";
Car Pride2 = Pride;
Pride2.Name = "쟤네실수";
System.out.println(Pride.Name);
}
}
//*/
/* 값에 의한 전달
class JavaExam {
public static void main(String args[]) {
int Value = 1;
System.out.println(Value);
method(Value);
System.out.println(Value);
}
static void method(int Value) {
Value = 2;
}
}
//*/
/* 참조형의 전달
class Car {
String Name;
}
class JavaExam {
public static void main(String args[]) {
Car Pride = new Car();
Pride.Name = "프라이드";
System.out.println(Pride.Name);
method(Pride);
System.out.println(Pride.Name);
}
static void method(Car aCar) {
aCar.Name = "쟤네실수";
}
}
//*/
/* 문자열 값 전달
class JavaExam {
public static void main(String args[]) {
String str = "abc";
System.out.println(str);
method(str);
System.out.println(str);
}
static void method(String str) {
str = "def";
}
}
//*/
/* 문자열 참조 전달
class JavaExam {
public static void main(String args[]) {
String str = "abc";
System.out.println(str);
str = method(str);
System.out.println(str);
}
static String method(String str) {
str = "def";
return str;
}
}
//*/
/* 초기화 블록
class Sales {
int[] table;
{
table = new int[10];
for (int i = 0; i < table.length; i++) {
table[i] = i*2;
}
}
}
class JavaExam {
public static void main(String args[]) {
Sales sales = new Sales();
System.out.println(sales.table[2]);
}
}
//*/
/* 생성자
class Car {
String Name;
String Color;
boolean Gasoline;
Car(String aName, String aColor, boolean aGasoline) {
Name = aName;
Color = aColor;
Gasoline = aGasoline;
}
//Car(String Name, String Color, boolean Gasoline) {
// this.Name = Name;
// this.Color = Color;
// this.Gasoline = Gasoline;
//}
void Run() {
if (Gasoline) {
System.out.println("부릉 부릉");
} else {
System.out.println("덜컹 덜컹");
}
}
void Stop() {
System.out.println("끼이익");
}
}
class JavaExam {
public static void main(String args[]) {
Car Pride = new Car("프라이드", "파랑", true);
Pride.Run();
Pride.Stop();
}
}
//*/
/* 생성자 오버로딩
class Car {
String Name = "모름";
String Color = "흰색";
boolean Gasoline = true;
Car(String aName) {
Name = aName;
}
Car(String aName, String aColor, boolean aGasoline) {
this(aName);
Color = aColor;
Gasoline = aGasoline;
}
void Run() {
if (Gasoline) {
System.out.println("부릉 부릉");
} else {
System.out.println("덜컹 덜컹");
}
}
void Stop() {
System.out.println("끼이익");
}
}
class JavaExam {
public static void main(String args[]) {
Car Pride = new Car("프라이드", "파랑", true);
Car Avante = new Car("아방떼");
Pride.Run();
Pride.Stop();
}
}
//*/
/* 디폴트 생성자
class Car {
String Name = "모름";
String Color = "흰색";
boolean Gasoline = true;
void Run() {
if (Gasoline) {
System.out.println("부릉 부릉");
} else {
System.out.println("덜컹 덜컹");
}
}
void Stop() {
System.out.println("끼이익");
}
}
class JavaExam {
public static void main(String args[]) {
Car Pride = new Car();
Pride.Run();
Pride.Stop();
}
}
//*/
/* finalizie
class Network {
Network() {
System.out.println("네트워크에 연결한다.");
}
public void finalize() {
System.out.println("연결을 끊는다.");
}
}
class JavaExam {
public static void main(String args[]) {
Network N = new Network();
N.finalize();
}
}
//*/
/* 액세스 지정자
class Car {
public String Name;
protected String Color;
boolean Gasoline;
private int ModelYear;
public void Internal() {
Name = "에꿍쓰";
Color = "금색";
Gasoline = true;
ModelYear = 2009;
}
public int GetModelYear() {
return ModelYear;
}
public void SetModelYear(int aModelYear) {
if (aModelYear > 2000) {
ModelYear = aModelYear;
}
}
}
class JavaExam {
public static void main(String args[]) {
Car Pride = new Car();
Pride.Name = "프라이드";
Pride.Color = "파랑";
Pride.Gasoline = true;
//Pride.ModelYear=2005;
Pride.SetModelYear(2005);
System.out.println(Pride.GetModelYear());
}
}
//*/
/* 정적 필드
class Car {
String Name;
static int CarNum = 0;
Car(String aName) {
Name = aName;
CarNum++;
}
}
class JavaExam {
public static void main(String args[]) {
Car Pride = new Car("프랑이");
Car Matis = new Car("마팅이");
Car Carnival = new Car("니발이");
System.out.println("차 " + Car.CarNum + "대 구입했다.");
}
}
//*/
/* 정적 초기화 블록
class Sales {
static int[] table;
static {
table = new int[10];
for (int i = 0; i < table.length; i++) {
table[i] = i*2;
}
}
}
class JavaExam {
public static void main(String args[]) {
Sales sales = new Sales();
System.out.println(Sales.table[2]);
}
}
//*/
/* 정적 메소드
class Hello {
static void Morning() {
System.out.println("좋은 아침");
}
static void Lunch() {
System.out.println("점심 먹었어?");
}
static void Evening() {
System.out.println("술 한잔 어때");
}
}
class JavaExam {
public static void main(String args[]) {
Hello.Morning();
Hello.Lunch();
Hello.Evening();
}
}
//*/
/* 정적 필드와 정적 메소드
class Statistics {
static int[] Info;
double ratio = 1.5;
static {
Info = new int[10];
Info[0] = 1415;
Info[1] = 9265;
Info[2] = 3589;
}
static int GetAverage() {
int sum = 0;
for (int i : Info) {
sum += i;
}
//sum *= ratio;
return sum/Info.length;
}
double GetSomeValue(double input) {
return input * ratio * GetAverage();
}
}
class JavaExam {
public static void main(String args[]) {
System.out.println(Statistics.GetAverage());
Statistics S = new Statistics();
System.out.println(S.GetSomeValue(3));
}
}
//*/
/* 상수 필드
class Circle {
static final double PIE = 3.14159265;
double Radius;
Circle(double aRadius) {
Radius = aRadius;
}
double GetCircum() { return 2*Radius*PIE; }
double GetArea() { return Radius*Radius*PIE; }
}
class JavaExam {
public static void main(String args[]) {
Circle C = new Circle(3);
System.out.println("원주 = " + C.GetCircum());
System.out.println("면적 = " + C.GetArea());
}
}
//*/
/* 생성자에서 초기화하는 상수 필드
class NoteBook {
final String CPU;
int Memory;
int HDD;
NoteBook(String aCPU, int aMemory, int aHDD) {
CPU = aCPU;
Memory = aMemory;
HDD = aHDD;
}
void UpgradeMemory(int aMemory, int aHDD) {
Memory = aMemory;
HDD = aHDD;
// CPU = "Super Strong 8 Core 4.5GHz";
}
void OutSpec() {
System.out.printf("CPU = %S, Memory = %d, HDD= %d\n", CPU, Memory, HDD);
}
}
class JavaExam {
public static void main(String args[]) {
NoteBook Sens = new NoteBook("Intel Q9000", 3, 500);
NoteBook XNote = new NoteBook("AMD Sampron", 2, 320);
Sens.OutSpec();
XNote.OutSpec();
Sens.UpgradeMemory(8,750);
Sens.OutSpec();
}
}
//*/
/* 열거형
enum Race {
TERRAN, ZERG, PROTOSS
}
class JavaExam {
public static void main(String args[]) {
Race MyTeam;
// Race MyTeam = new Race(TERRAN);
MyTeam = Race.ZERG;
// MyTeam = 1;
// int i = (int)MyTeam;
System.out.println(MyTeam);
for (Race R : Race.values()) {
System.out.print(R+" ");
}
System.out.println("");
Race YourTeam = Race.valueOf("PROTOSS");
System.out.println(YourTeam);
}
}
//*/
/* 열거형에 다른 타입의 값 연결하기
enum Race {
TERRAN("테란"), ZERG("저그"), PROTOSS("프로토스");
final private String HanRace;
Race(String Han) {
HanRace = Han;
}
String getHanName() {
return HanRace;
}
}
class JavaExam {
public static void main(String args[]) {
Race MyTeam;
MyTeam = Race.ZERG;
System.out.println(MyTeam.getHanName());
}
}
//*/
/* 자바 타입 열거형
enum JavaType {
SHORT("짧은 정수형",2), INT("정수형",4),DOUBLE("실수형",8);
final private String TypeName;
final private int Length;
JavaType(String Name, int Byte) {
TypeName = Name;
Length = Byte;
}
String getName() { return TypeName; }
int getLength() { return Length; }
}
class JavaExam {
public static void main(String args[]) {
JavaType Type;
Type = JavaType.INT;
System.out.println("타입 : " + Type + ", 이름 : " +
Type.getName() + ", 길이 : " + Type.getLength());
}
}
//*/
/* 상속
class Car {
public String Name;
protected String Color;
boolean Gasoline;
Car(String aName, String aColor, boolean aGasoline) {
Name = aName;
Color = aColor;
Gasoline = aGasoline;
}
void Run() {
if (Gasoline) {
System.out.println("부릉 부릉");
} else {
System.out.println("덜컹 덜컹");
}
}
void Stop() {
System.out.println("끼이익");
}
}
class Truck extends Car {
int Ton;
Truck(String aName, String aColor, boolean aGasoline, int aTon) {
super(aName,aColor,aGasoline);
//일부 멤버를 수정 가능
//super(aName,aColor,false);
Ton = aTon;
}
void Run() {
//슈퍼 클래스의 메소드 호출. 꼭 처음이 아니어도 상관없음
//super.Run();
System.out.println("우당탕 쿵탕");
}
void Convey() {
System.out.println("짐을 실어 나른다.");
}
}
class JavaExam {
public static void main(String args[]) {
Truck Porter = new Truck("포터", "흰색", false, 1000);
Porter.Run();
Porter.Convey();
}
}
//*/
/* 부모는 자식을 가리킨다.
class Car {
public String Name;
protected String Color;
boolean Gasoline;
Car(String aName, String aColor, boolean aGasoline) {
Name = aName;
Color = aColor;
Gasoline = aGasoline;
}
void Run() {
if (Gasoline) {
System.out.println("부릉 부릉");
} else {
System.out.println("덜컹 덜컹");
}
}
void Stop() {
System.out.println("끼이익");
}
}
class Truck extends Car {
int Ton;
Truck(String aName, String aColor, boolean aGasoline, int aTon) {
super(aName,aColor,aGasoline);
Ton = aTon;
}
void Run() {
System.out.println("우당탕 쿵탕");
}
void Convey() {
System.out.println("짐을 실어 나른다.");
}
}
class JavaExam {
public static void main(String args[]) {
Car MyCar = new Car("제네시스", "빨강", true);
Car YourCar = new Truck("봉고", "파랑", true, 1500);
MyCar.Run();
YourCar.Run();
//YourCar.Convey();
//Truck MyTruck = new Car("제네시스", "빨강", true);
//MyTruck.Run();
//MyTruck.Stop();
//MyTruck.Convey();
}
}
//*/
/* 다형성
class Car {
public String Name;
protected String Color;
boolean Gasoline;
Car(String aName, String aColor, boolean aGasoline) {
Name = aName;
Color = aColor;
Gasoline = aGasoline;
}
void Run() {
if (Gasoline) {
System.out.println("부릉 부릉");
} else {
System.out.println("덜컹 덜컹");
}
}
void Stop() {
System.out.println("끼이익");
}
}
class Truck extends Car {
int Ton;
Truck(String aName, String aColor, boolean aGasoline, int aTon) {
super(aName,aColor,aGasoline);
Ton = aTon;
}
void Run() {
System.out.println("우당탕 쿵탕");
}
void Convey() {
System.out.println("짐을 실어 나른다.");
}
}
class JavaExam {
public static void TestCar(Car car) {
car.Run();
car.Stop();
//car.Convey();
}
public static void main(String args[]) {
Car MyCar = new Car("제네시스", "빨강", true);
Car YourCar = new Truck("봉고", "파랑", true, 1500);
TestCar(MyCar);
TestCar(YourCar);
}
}
//*/
/* 객체 캐스팅
class Car {
public String Name;
protected String Color;
boolean Gasoline;
Car(String aName, String aColor, boolean aGasoline) {
Name = aName;
Color = aColor;
Gasoline = aGasoline;
}
void Run() {
if (Gasoline) {
System.out.println("부릉 부릉");
} else {
System.out.println("덜컹 덜컹");
}
}
void Stop() {
System.out.println("끼이익");
}
}
class Truck extends Car {
int Ton;
Truck(String aName, String aColor, boolean aGasoline, int aTon) {
super(aName,aColor,aGasoline);
Ton = aTon;
}
void Run() {
System.out.println("우당탕 쿵탕");
}
void Convey() {
System.out.println("짐을 실어 나른다.");
}
}
class JavaExam {
public static void main(String args[]) {
Car MyTruck = new Truck("봉고", "파랑", true, 1500);
Truck AnyTruck;
AnyTruck = (Truck)MyTruck;
AnyTruck.Convey();
}
}
//*/
/* 클래스간의 캐스트 연산
class Car {
public String Name;
protected String Color;
boolean Gasoline;
Car(String aName, String aColor, boolean aGasoline) {
Name = aName;
Color = aColor;
Gasoline = aGasoline;
}
void Run() {
if (Gasoline) {
System.out.println("부릉 부릉");
} else {
System.out.println("덜컹 덜컹");
}
}
void Stop() {
System.out.println("끼이익");
}
}
class Truck extends Car {
int Ton;
Truck(String aName, String aColor, boolean aGasoline, int aTon) {
super(aName,aColor,aGasoline);
Ton = aTon;
}
void Run() {
System.out.println("우당탕 쿵탕");
}
void Convey() {
System.out.println("짐을 실어 나른다.");
}
}
class JavaExam {
public static void TestCar(Car car) {
car.Run();
car.Stop();
if (car instanceof Truck) {
Truck truck = (Truck)car;
truck.Convey();
//((Truck)car).Convey();
}
}
public static void main(String args[]) {
Car[] arCar = {
new Car("그랜저", "검정", true),
new Truck("포터", "파랑", false, 1500),
new Car("소나타", "하양", true),
};
for (Car car: arCar) {
TestCar(car);
}
}
}
//*/
/* 추상 클래스
abstract class Dog {
void SwingTail() {
System.out.println("살랑살랑");
}
abstract void Bark();
}
class Jindo extends Dog {
void Bark() {
System.out.println("멍멍");
}
}
class Chihuahua extends Dog {
void Bark() {
System.out.println("왈왈");
}
}
class JavaExam {
public static void main(String args[]) {
Jindo Jindol = new Jindo();
Chihuahua Happy = new Chihuahua();
Jindol.Bark();
Happy.Bark();
}
}
//*/
/* 인터페이스
interface Animal {
void Eat();
void Sleep();
}
class Cow implements Animal {
public void Eat() {
System.out.println("우걱우걱");
}
public void Sleep() {
System.out.println("쿨쿨");
}
}
class JavaExam {
public static void main(String args[]) {
Cow So = new Cow();
So.Eat();
So.Sleep();
}
}
//*/
/* 다중 상속
abstract class Dog {
void SwingTail() {
System.out.println("살랑살랑");
}
abstract void Bark();
}
interface Animal {
void Eat();
void Sleep();
}
class Chihuahua extends Dog implements Animal {
void Bark() {
System.out.println("왈왈");
}
public void Eat() {
System.out.println("냠냠냠냠");
}
public void Sleep() {
System.out.println("쌔근쌔근");
}
}
class JavaExam {
public static void main(String args[]) {
Chihuahua Happy = new Chihuahua();
Happy.SwingTail();
Happy.Bark();
Happy.Eat();
Happy.Sleep();
//Animal Ddaeng7 = new Chihuahua();
//Ddaeng7.Eat();
//Ddaeng7.Sleep();
}
}
//*/
/* 클래스의 중첩
class CarName {
String Model;
int Year;
CarName(String aModel, int aYear) {
Model = aModel;
Year = aYear;
}
}
class Car {
CarName Name;
String Color;
Car(String aModel, int aYear,String aColor) {
Name = new CarName(aModel,aYear);
Color = aColor;
}
void OutInfo() {
System.out.printf("모델 = %s, 년식 = %d, 색상 = %s\n",
Name.Model, Name.Year, Color);
}
}
public class JavaExam {
public static void main(String[] args) {
Car Pride = new Car("프라이드", 2005, "파랑");
Pride.OutInfo();
CarName Grandeur = new CarName("그랜다이저", 2009);
System.out.printf("모델 = %s, 년식 = %d\n", Grandeur.Model,Grandeur.Year);
}
}
//*/
/* 정적 이너 클래스
class Car {
CarName Name;
String Color;
static class CarName {
String Model;
int Year;
CarName(String aModel, int aYear) {
Model = aModel;
Year = aYear;
}
}
Car(String aModel, int aYear,String aColor) {
Name = new CarName(aModel,aYear);
Color = aColor;
}
void OutInfo() {
System.out.printf("모델 = %s, 년식 = %d, 색상 = %s\n",
Name.Model, Name.Year, Color);
}
}
public class JavaExam {
public static void main(String[] args) {
Car Pride = new Car("프라이드", 2005, "파랑");
Pride.OutInfo();
Car.CarName Grandeur = new Car.CarName("그랜다이저", 2009);
System.out.printf("모델 = %s, 년식 = %d\n", Grandeur.Model,Grandeur.Year);
}
}
//*/
/* 이너 클래스
class Car {
CarName Name;
String Color;
class CarName {
String Model;
int Year;
CarName(String aModel, int aYear) {
Model = aModel;
Year = aYear;
}
void OutColor() {
System.out.println("색상은 " + Color + "입니다.");
}
}
Car(String aModel, int aYear,String aColor) {
Name = new CarName(aModel,aYear);
Color = aColor;
}
void OutInfo() {
System.out.printf("모델 = %s, 년식 = %d, 색상 = %s\n",
Name.Model, Name.Year, Color);
}
}
public class JavaExam {
public static void main(String[] args) {
Car Pride = new Car("프라이드", 2005, "파랑");
Pride.OutInfo();
Pride.Name.OutColor();
Car.CarName Pride2 = Pride.new CarName("프랑이", 2009);
Pride2.OutColor();
}
}
//*/
/* 로컬 이너 클래스
public class JavaExam {
public static void main(String[] args) {
class Car {
void Run() {
System.out.println("부릉 부릉");
}
}
Car Forte = new Car();
Forte.Run();
}
}
//*/
/* 외부 클래스를 상속받는 로컬 이너 클래스
class Car {
void Run() {
System.out.println("부릉 부릉");
}
}
public class JavaExam {
public static void main(String[] args) {
class Truck extends Car {
void Run() {
System.out.println("우당탕 쿵탕");
}
}
Truck Porter = new Truck();
Porter.Run();
}
}
//*/
/* 익명 로컬 이너 클래스
class Car {
void Run() {
System.out.println("부릉 부릉");
}
}
public class JavaExam {
public static void main(String[] args) {
Car Porter = new Car() {
void Run() {
System.out.println("우당탕 쿵탕");
}
};
Porter.Run();
}
}
//*/
/* 인터페이스를 구현하는 익명 로컬 이너 클래스
interface ICar {
void Run();
}
public class JavaExam {
public static void main(String[] args) {
ICar Porter = new ICar() {
public void Run() {
System.out.println("우당탕 쿵탕");
}
};
Porter.Run();
}
}
//*/
/* 인터페이스를 구현하는 익명 로컬 이너 클래스
interface ICar {
void Run();
}
public class JavaExam {
public static void main(String[] args) {
class Anonymous implements ICar {
public void Run() {
System.out.println("우당탕 쿵탕");
}
};
Anonymous Porter = new Anonymous();
Porter.Run();
}
}
//*/
/////////////////////////////////////////////////////////////////////
//4장.자바 라이브러리
/* PackageTest
package kr.winapi;
public class PackageTest {
public static void main(String[] args) {
kimutil.UtilClass.UtilMethod();
parkutil.UtilClass.UtilMethod();
}
}
//*/
/* kilutil.UtilClass.java
package kimutil;
public class UtilClass {
public static void UtilMethod() {
System.out.println("김차장의 유틸리티");
}
}
//*/
/* parkutil.UtilClass.java
package parkutil;
public class UtilClass {
public static void UtilMethod() {
System.out.println("박과장의 유틸리티");
}
}
//*/
/* import
package kr.winapi;
import kimutil.UtilClass;
public class PackageTest {
public static void main(String[] args) {
UtilClass.UtilMethod();
parkutil.UtilClass.UtilMethod();
}
}
//*/
/* toString
class Car {
String Name;
String Color;
Car(String aName, String aColor) { Name = aName; Color = aColor; }
//public String toString() { return Color + " " + Name; }
}
class JavaExam {
public static void main(String args[]) {
int i = 1234;
System.out.println(i);
Car Pride = new Car("프라이드", "파랑");
System.out.println(Pride);
}
}
//*/
/* equals
class Car {
String Name;
Car(String aName) { Name = aName; }
public boolean equals(Object obj) {
if (obj instanceof Car) {
Car other = (Car)obj;
return (Name.equals(other.Name));
}
return false;
}
}
class JavaExam {
public static void main(String args[]) {
Car Pride = new Car("프라이드");
Car Pride2 = new Car("프라이드");
Car Cerato = new Car("세라토");
Car PrideCopy = Pride;
System.out.println(Pride == Pride2 ? "같다":"다르다");
System.out.println(Pride == PrideCopy ? "같다":"다르다");
System.out.println(Pride.equals(Pride2) ? "같다":"다르다");
System.out.println(Pride.equals(Cerato) ? "같다":"다르다");
}
}
//*/
/* getClass
import java.lang.reflect.*;
class Car {
String Name;
String Color;
boolean Gasoline;
void Run() { }
void Stop() { }
}
class JavaExam {
public static void main(String args[]) {
Car Pride = new Car();
Class cls = Pride.getClass();
//Class cls = Car.class;
System.out.println("클래스 이름 = " + cls.getName());
System.out.println("슈퍼 클래스 = " + cls.getSuperclass().getName());
Field[] fields = cls.getDeclaredFields();
System.out.print("필드 : ");
for (Field F : fields) {
System.out.print(F.getName() + " ");
}
System.out.print("\n메소드 : ");
Method methods[] = cls.getDeclaredMethods();
for (Method M : methods) {
System.out.print(M.getName() + " ");
}
}
}
//*/
/* 박싱
class JavaExam {
public static void main(String args[]) {
int i = 1234;
String str;
//str = i.toString();
Integer wrapint = new Integer(i);
//Integer wrapint = i;
//Integer wrapint = Integer.valueOf(i);
str = wrapint.toString();
System.out.println(str);
}
}
//*/
/* 문자열로부터 박싱
class JavaExam {
public static void main(String args[]) {
Integer wrapint = new Integer("629");
String str = wrapint.toString();
int i = Integer.parseInt(str);
System.out.println(i);
String a = "12", b = "34";
System.out.println(a + b);
System.out.println(Integer.parseInt(a) + Integer.parseInt(b));
}
}
//*/
/* 언박싱
class JavaExam {
public static void main(String args[]) {
Integer wrapint = new Integer(629);
int i = wrapint.intValue();
System.out.println(i);
Double wrapdouble = new Double("3.14");
int di = wrapdouble.intValue();
System.out.println(di);
}
}
//*/
/* 래퍼의 기능
class JavaExam {
public static void main(String args[]) {
System.out.printf("int 타입의 크기 = %d, 최소값 = %d, 최대값 = %d\n",
Integer.SIZE, Integer.MIN_VALUE, Integer.MAX_VALUE);
System.out.printf("Double 타입의 크기 = %d, 지수 최소값 = %d, 지수 최대값 = %d\n",
Double.SIZE, Double.MIN_EXPONENT, Double.MAX_EXPONENT);
System.out.println(Integer.toBinaryString(1234));
System.out.println(Integer.toBinaryString(Float.floatToRawIntBits(3.14f)));
}
}
//*/
/* String의 생성자
public class JavaExam {
public static void main(String[] args) {
String str;
str = "아름다운";
System.out.println(str);
String str2 = "우리나라";
System.out.println(str2);
char[] ar = { 'k', 'o', 'r', 'e', 'a' };
String str3 = new String(ar);
System.out.println(str3);
System.out.println("대한민국".length());
}
}
//*/
/* 문자열 비교
public class JavaExam {
public static void main(String[] args) {
String str1 = "James Gosling";
String str2 = "James Gosling";
String str3 = "James ";
str3 += "Gosling";
String str4 = "james gosling";
System.out.println(str1 == str2 ? "같다":"다르다");
System.out.println(str1 == str3 ? "같다":"다르다");
System.out.println(str1.equals(str3) ? "같다":"다르다");
System.out.println(str1.equals(str4) ? "같다":"다르다");
System.out.println(str1.equalsIgnoreCase(str4) ? "같다":"다르다");
String Apple = "Apple";
String Orange = "Orange";
int Result = Apple.compareTo(Orange);
if (Result == 0) {
System.out.println("같다");
} else if (Result < 0) {
System.out.println("Apple이 더 앞쪽");
} else if (Result > 0) {
System.out.println("Apple이 더 뒤쪽");
}
}
}
//*/
/* 문자열 검색
public class JavaExam {
public static void main(String[] args) {
String str = "String Search Method of String Class";
System.out.println("앞쪽 t = " + str.indexOf('t'));
System.out.println("뒤쪽 t = " + str.lastIndexOf('t'));
System.out.println("앞쪽 z = " + str.indexOf('z'));
System.out.println("앞쪽 String = " + str.indexOf("String"));
System.out.println("뒤쪽 String = " + str.lastIndexOf("String"));
}
}
//*/
/* 문자열 변경
public class JavaExam {
public static void main(String[] args) {
String str = " Made In Korea ";
System.out.println(str.toLowerCase());
System.out.println(str.toUpperCase());
System.out.println(str.trim());
str.toUpperCase();
String str2 = str.toUpperCase();
System.out.println(str);
System.out.println(str2);
String str3 = "독도는 일본땅이다. 대마도는 일본땅이다.";
System.out.println(str3.replaceFirst("일본", "한국"));
System.out.println(str3.replaceAll("일본", "한국"));
}
}
//*/
/* 부분 문자열 추출
public class JavaExam {
public static void main(String[] args) {
String str = "0123456789";
System.out.println(str.substring(3,7));
String name = "제 이름은 <아무개>입니다.";
int st, ed;
st = name.indexOf('<');
ed = name.indexOf('>');
System.out.println(name.substring(st+1,ed));
}
}
//*/
/* String으로 문자열 조작
public class JavaExam {
public static void main(String[] args) {
String str = "";
for (int i = 0; i < 1000; i++) {
for (char ch = 'A'; ch <= 'z'; ch ++) {
str += ch;
}
str += '\n';
}
System.out.println(str);
}
}
//*/
/* StringBuilder로 문자열 조작
public class JavaExam {
public static void main(String[] args) {
StringBuilder str = new StringBuilder();
for (int i = 0; i < 1000; i++) {
for (char ch = 'A'; ch <= 'z'; ch ++) {
str.append(ch);
}
str.append('\n');
}
System.out.println(str);
}
}
//*/
/* 수행 시간 측정
class JavaExam {
public static void main(String args[]) {
long start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
System.out.println(i + "번째 줄");
}
long end = System.currentTimeMillis();
System.out.println((end-start)/1000.0 + " 초 걸림");
}
}
//*/
/* 난수 생성
import java.util.Random;
class JavaExam {
public static void main(String args[]) {
Random R = new Random();
for (int i = 0; i < 10; i++) {
System.out.println(R.nextInt(100));
System.out.println(3.14e-1);
}
}
}
//*/
/* 현재 시간 출력
import java.util.*;
class JavaExam {
public static void main(String args[]) {
GregorianCalendar C = new GregorianCalendar();
System.out.printf("%d년 %d월 %d일 %s %d시 %d분 %d초",
C.get(Calendar.YEAR),
C.get(Calendar.MONTH),
C.get(Calendar.DATE),
C.get(Calendar.AM_PM) == Calendar.AM ? "오전":"오후",
C.get(Calendar.HOUR),
C.get(Calendar.MINUTE),
C.get(Calendar.SECOND));
}
}
//*/
/* ArrayList
import java.util.*;
class JavaExam {
public static void main(String args[]) {
ArrayList<String> arName = new ArrayList<String>();
arName.add("전두환");
arName.add("김영삼");
arName.add("김대중");
arName.add(1,"노태우");
for (int i = 0;i < arName.size();i++) {
System.out.println(arName.get(i));
}
System.out.println("==========");
arName.remove(2);
arName.set(2,"원더걸스");
for (int i = 0;i < arName.size();i++) {
System.out.println(arName.get(i));
}
if (arName.indexOf("노태우") != -1) {
System.out.println("있다");
} else {
System.out.println("없다");
}
}
}
//*/
/* 기본형에 대한 ArrayList
import java.util.*;
class JavaExam {
public static void main(String args[]) {
ArrayList<Integer> arNum = new ArrayList<Integer>();
arNum.add(86);
arNum.add(92);
arNum.add(77);
for (Integer i : arNum) {
System.out.println(i);
}
}
}
//*/
/* LinkedList
import java.util.*;
class JavaExam {
public static void main(String args[]) {
LinkedList<String> arName = new LinkedList<String>();
arName.add("전두환");
arName.add("김영삼");
arName.add("김대중");
arName.add(1,"노태우");
//for (int i = 0;i < arName.size();i++) {
// System.out.println(arName.get(i));
//}
Iterator<String> it = arName.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
// 뇌 자바 539 페이지에 된다고 되어 있는데 안됨
//Iterator<String> it = arName.iterator();
//for (String Name : it) {
// System.out.println(Name);
//}
}
}
//*/
/* HashMap
import java.util.*;
class JavaExam {
public static void main(String args[]) {
HashMap<String,Integer> Snack = new HashMap<String,Integer>();
Snack.put("오징어 땅콩", 2500);
Snack.put("죠리퐁", 1900);
Snack.put("핫브레이크", 450);
Snack.put("빼빼로", 900);
String MySnack = "죠리퐁";
System.out.println(MySnack + "의 가격은 " + Snack.get(MySnack));
}
}
//*/
/////////////////////////////////////////////////////////////////////
//5장.고급 문법
/* 예외 처리
public class JavaExam {
public static void main(String[] args) {
int[] ar= {1,2,3,4,5};
int index = 5;
try {
System.out.println(ar[index]);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("첨자가 배열 범위를 넘어섰습니다.");
}
catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println("연산을 완료했습니다.");
}
}
//*/
/* 체크드 예외
public class JavaExam {
public static void main(String[] args) {
System.out.println("프로그램 시작");
try {
Thread.sleep(3000);
}
catch (InterruptedException e) {
System.out.println("예외 발생");
}
System.out.println("프로그램 끝");
}
}
//*/
/* 예외 객체의 메소드
public class JavaExam {
public static void main(String[] args) {
method();
}
static void method() {
submethod();
}
static void submethod() {
int i;
int a = 3, b = 0;
try {
i = a / b;
System.out.println(i);
}
catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
//*/
/* 예외 던지기
public class JavaExam {
public static void main(String[] args) {
try {
method();
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
static void method() throws Exception {
throw new Exception("뭔가 잘못됐음.");
}
}
//*/
/* Thread 상속
public class JavaExam {
public static void main(String[] args) {
MyThread worker = new MyThread();
worker.start();
for (int num = 0;num < 20;num++) {
try { Thread.sleep(50); } catch (InterruptedException e) { ; }
System.out.print("Java ");
}
}
}
class MyThread extends Thread {
public void run() {
for (int num = 0;num < 20;num++) {
try { Thread.sleep(30); } catch (InterruptedException e) { ; }
System.out.print("자바 ");
}
}
}
//*/
/* Runnable 구현
public class JavaExam {
public static void main(String[] args) {
MyRunnable MyRun = new MyRunnable();
Thread worker = new Thread(MyRun);
worker.start();
for (int num = 0;num < 20;num++) {
try { Thread.sleep(50); } catch (InterruptedException e) { ; }
System.out.print("Java ");
}
}
}
class MyRunnable implements Runnable {
public void run() {
for (int num = 0;num < 20;num++) {
try { Thread.sleep(30); } catch (InterruptedException e) { ; }
System.out.print("자바 ");
}
}
}
//*/
/* Runnable을 사용해야 하는 경우
public class JavaExam {
public static void main(String[] args) {
MyRunnable MyRun = new MyRunnable();
Thread worker = new Thread(MyRun);
worker.start();
for (int num = 0;num < 20;num++) {
try { Thread.sleep(50); } catch (InterruptedException e) { ; }
System.out.print("Java ");
}
}
}
class MyClass {
public void PrintJava() {
for (int num = 0;num < 20;num++) {
try { Thread.sleep(30); } catch (InterruptedException e) { ; }
System.out.print("자바 ");
}
}
}
class MyRunnable extends MyClass implements Runnable {
public void run() {
PrintJava();
}
}
//*/
/* Runnable 구현 - 익명 이너 클래스
public class JavaExam {
public static void main(String[] args) {
Thread worker = new Thread(mRunnable);
worker.start();
for (int num = 0;num < 20;num++) {
try { Thread.sleep(50); } catch (InterruptedException e) { ; }
System.out.print("Java ");
}
}
static Runnable mRunnable = new Runnable() {
public void run() {
for (int num = 0;num < 20;num++) {
try { Thread.sleep(30); } catch (InterruptedException e) { ; }
System.out.print("자바 ");
}
}
};
}
//*/
/* Runnable 구현 - 더 간단한 익명 이너 클래스 객체
public class JavaExam {
public static void main(String[] args) {
Thread worker = new Thread(new Runnable() {
public void run() {
for (int num = 0;num < 20;num++) {
try { Thread.sleep(30); } catch (InterruptedException e) { ; }
System.out.print("자바 ");
}
}
});
worker.start();
for (int num = 0;num < 20;num++) {
try { Thread.sleep(50); } catch (InterruptedException e) { ; }
System.out.print("Java ");
}
}
}
//*/
/* 공유 객체를 통한 스레드간의 통신
public class JavaExam {
public static void main(String[] args) {
Memory mem = new Memory(16);
DownLoad down = new DownLoad(mem);
Play play = new Play(mem);
down.start();
play.start();
}
}
class Memory {
int[] buffer;
int size;
int progress;
Memory(int asize) {
size = asize;
buffer = new int[asize];
progress = 0;
}
}
class DownLoad extends Thread {
Memory mem;
DownLoad(Memory amem) {
mem = amem;
}
public void run() {
for (int off = 0;off < mem.size;off++) {
mem.buffer[off] = off;
mem.progress = off + 1;
try { Thread.sleep(200); } catch (InterruptedException e) { ; }
}
}
}
class Play extends Thread {
Memory mem;
Play(Memory amem) {
mem = amem;
}
public void run() {
for (;;) {
for (int off = 0;off < mem.progress;off++) {
System.out.print(mem.buffer[off] + " ");
}
System.out.println();
if (mem.progress == mem.size) break;
try { Thread.sleep(500); } catch (InterruptedException e) { ; }
}
}
}
//*/
/* 동기화 - 두 청크가 한 블록을 구성해야 한다.
public class JavaExam {
public static void main(String[] args) {
Memory mem = new Memory(16);
DownLoad down = new DownLoad(mem);
Play play = new Play(mem);
down.start();
play.start();
}
}
class Memory {
int[] buffer;
int size;
int progress;
Memory(int asize) {
size = asize;
buffer = new int[asize];
progress = 0;
}
}
class DownLoad extends Thread {
Memory mem;
DownLoad(Memory amem) {
mem = amem;
}
public void run() {
for (int off = 0;off < mem.size;off += 2) {
synchronized(mem) {
for (int chunk = 0;chunk < 2;chunk++) {
mem.buffer[off+chunk] = off+chunk;
mem.progress = off+chunk+1;
try { Thread.sleep(200); } catch (InterruptedException e) { ; }
}
}
}
}
}
class Play extends Thread {
Memory mem;
Play(Memory amem) {
mem = amem;
}
public void run() {
for (;;) {
synchronized(mem) {
for (int off = 0;off < mem.progress;off++) {
System.out.print(mem.buffer[off] + " ");
}
System.out.println();
}
if (mem.progress == mem.size) break;
try { Thread.sleep(500); } catch (InterruptedException e) { ; }
}
}
}
//*/
/* 동기화 메소드
public class JavaExam {
public static void main(String[] args) {
Memory mem = new Memory(16);
DownLoad down = new DownLoad(mem);
Play play = new Play(mem);
down.start();
play.start();
}
}
class Memory {
int[] buffer;
int size;
int progress;
Memory(int asize) {
size = asize;
buffer = new int[asize];
progress = 0;
}
synchronized void DownChunk(int off) {
for (int chunk = 0;chunk < 2;chunk++) {
buffer[off+chunk] = off+chunk;
progress = off+chunk+1;
try { Thread.sleep(200); } catch (InterruptedException e) { ; }
}
}
synchronized void PlayDowned() {
for (int off = 0;off < progress;off++) {
System.out.print(buffer[off] + " ");
}
System.out.println();
}
}
class DownLoad extends Thread {
Memory mem;
DownLoad(Memory amem) {
mem = amem;
}
public void run() {
for (int off = 0;off < mem.size;off += 2) {
mem.DownChunk(off);
}
}
}
class Play extends Thread {
Memory mem;
Play(Memory amem) {
mem = amem;
}
public void run() {
for (;;) {
mem.PlayDowned();
if (mem.progress == mem.size) break;
try { Thread.sleep(500); } catch (InterruptedException e) { ; }
}
}
}
//*/
/* 다 받은 후에 재생하기
public class JavaExam {
public static void main(String[] args) {
Memory mem = new Memory(16);
DownLoad down = new DownLoad(mem);
Play play = new Play(mem);
down.start();
play.start();
}
}
class Memory {
int[] buffer;
int size;
int progress;
Memory(int asize) {
size = asize;
buffer = new int[asize];
progress = 0;
}
}
class DownLoad extends Thread {
Memory mem;
DownLoad(Memory amem) {
mem = amem;
}
public void run() {
for (int off = 0;off < mem.size;off++) {
mem.buffer[off] = off;
mem.progress = off + 1;
try { Thread.sleep(200); } catch (InterruptedException e) { ; }
}
synchronized(mem) { mem.notify(); }
}
}
class Play extends Thread {
Memory mem;
Play(Memory amem) {
mem = amem;
}
public void run() {
//while (mem.progress != mem.size) {;}
try {
synchronized(mem) { mem.wait(); }
} catch(InterruptedException e) { }
for (int off = 0;off < mem.progress;off++) {
System.out.print(mem.buffer[off] + " ");
}
System.out.println();
}
}
//*/
/* 이진 파일 쓰기 - 원칙적으로 예외 처리
public class JavaExam {
public static void main(String[] args) {
FileOutputStream out = null;
try {
byte[] data = { 8, 9, 0, 6, 2, 9, 9 };
out = new FileOutputStream("test.bin");
out.write(data);
System.out.println("Write success");
}
catch (IOException e) {
System.out.println("File output error");
}
finally {
try {
out.close();
}
catch (Exception e) {;}
}
}
}
//*/
/* 이진 파일 쓰기 - 간략화된 형식
public class JavaExam {
public static void main(String[] args) throws Exception {
byte[] data = { 8, 9, 0, 6, 2, 9, 9 };
FileOutputStream out = new FileOutputStream("test.bin");
out.write(data);
out.close();
System.out.println("Write success");
}
}
//*/
/* 이진 파일 읽기
public class JavaExam {
public static void main(String[] args) throws Exception {
FileInputStream in = new FileInputStream("test.bin");
int avail = in.available();
byte[] data = new byte[avail];
in.read(data);
in.close();
for (byte b : data) {
System.out.print(b);
}
}
}
//*/
/* 문자열 입출력 - UTF8로 저장된다.
public class JavaExam {
public static void main(String[] args) throws Exception {
String str = "자바 Stream 입출력";
FileWriter out = new FileWriter("test.txt");
out.write(str);
out.close();
System.out.println("Write success");
// 한 문자씩 읽기
FileReader in = new FileReader("test.txt");
int ch;
for (;;) {
ch = in.read();
if (ch == -1) break;
System.out.print((char)ch);
}
in.close();
System.out.println();
// 한꺼번에 읽기
in = new FileReader("test.txt");
char[] text = new char[100];
int num = in.read(text);
System.out.println("읽은 문자 개수 = " + num);
System.out.println(text);
in.close();
}
}
//*/
/* ANSI 문자열 읽기 - 바로 읽지 못함. BOM이 없는 UTF8 문서만 읽음
public class JavaExam {
public static void main(String[] args) throws Exception {
//FileReader in = new FileReader("애국가.txt");
//FileReader in = new FileReader("애국가-Uincode.txt");
//FileReader in = new FileReader("애국가-Utf8.txt");
FileReader in = new FileReader("애국가-Utf8nb.txt");
char[] text = new char[1000];
int num = in.read(text);
System.out.println("읽은 문자 개수 = " + num);
System.out.println(text);
in.close();
}
}
//*/
/* 버퍼 이진 입출력
public class JavaExam {
public static void main(String[] args) throws Exception {
byte[] data = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9 };
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("test.buf"));
//FileOutputStream fout = new FileOutputStream("test.buf");
//BufferedOutputStream out = new BufferedOutputStream(fout);
out.write(data);
out.close();
System.out.println("Write success");
BufferedInputStream in = new BufferedInputStream(new FileInputStream("test.buf"));
byte[] indata = new byte[15];
in.read(indata,0,15);
in.close();
for (byte b : indata) {
System.out.print(b);
}
}
}
//*/
/* 버퍼 문자열 입출력
public class JavaExam {
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new FileReader("애국가-Utf8nb.txt"));
char[] text = new char[1000];
int num = in.read(text);
System.out.println("읽은 문자 개수 = " + num);
System.out.println(text);
in.close();
}
}
//*/
/* 텍스트 파일을 String 타입으로 문자열로 읽기
public class JavaExam {
public static void main(String[] args) {
String str = ReadFileToString("애국가-Utf8nb.txt");
System.out.println(str);
}
static String ReadFileToString(String Path) {
StringBuilder Result = new StringBuilder();
int ch;
try {
BufferedReader in = new BufferedReader(new FileReader(Path));
for (;;) {
ch = in.read();
if (ch == -1) break;
Result.append((char)ch);
}
}
catch (Exception e) {;}
return Result.toString();
}
}
//*/
/* 변수 입출력
public class JavaExam {
public static void main(String[] args) throws Exception {
DataOutputStream out = new DataOutputStream(new FileOutputStream("test.dat"));
out.writeInt(1234);
out.writeDouble(3.14159265);
out.writeUTF("String 문자열");
out.close();
System.out.println("Write success");
DataInputStream in = new DataInputStream(new FileInputStream("test.dat"));
int i = in.readInt();
double d = in.readDouble();
String str = in.readUTF();
System.out.printf("i = %d, d = %f, str = %s", i, d, str);
}
}
//*/
/* 행별로 읽어들이기
public class JavaExam {
public static void main(String[] args) throws Exception {
LineNumberReader in = new LineNumberReader(new FileReader("애국가-Utf8nb.txt"));
for (;;) {
String Line = in.readLine();
if (Line == null) break;
int Num = in.getLineNumber();
System.out.printf("%4d : %s\n", Num, Line);
}
in.close();
}
}
//*/
/* 서식 출력
public class JavaExam {
public static void main(String[] args) throws Exception {
PrintWriter out = new PrintWriter("format.txt");
int i = 1234;
double d = 56.789;
String str = "문자열";
out.printf("%6d, %10.2f, %s", i, d, str);
out.close();
}
}
//*/
/* 파일의 정보 조사
public class JavaExam {
public static void main(String[] args) {
File f = new File("c:\\Temp\\test.txt");
if (f.exists()) {
if (f.isFile()) {
System.out.println("파일입니다.");
System.out.println("파일경로 : " + f.getParent());
System.out.println("파일이름 : " + f.getName());
System.out.println("파일크기 : " + f.length());
System.out.println("숨김 파일 : " + f.isHidden());
System.out.println("절대 경로 : " + f.isAbsolute());
} else if (f.isDirectory()) {
System.out.println("디렉토리입니다.");
}
} else {
System.out.println("파일이 없습니다.");
}
}
}
//*/
/* 디렉토리 및 파일 생성
public class JavaExam {
public static void main(String[] args) throws Exception {
File folder = new File("c:\\TestFolder");
if (folder.mkdir()) {
File file = new File("c:\\TestFolder\\MyFile.txt");
if (file.createNewFile()) {
FileWriter out = new FileWriter(file);
out.write("테스트 파일");
out.close();
}
}
}
}
//*/
/* 파일 목록 조사
public class JavaExam {
public static void main(String[] args) {
File f = new File("c:\\");
File[] arFile = f.listFiles();
for (int i = 0; i < arFile.length; i++) {
if (arFile[i].isFile()) {
System.out.printf("%s %d 바이트\n",arFile[i].getName(), arFile[i].length());
} else {
System.out.printf("[%s] <폴더>\n",arFile[i].getName());
}
}
}
}
//*/
/* 객체 직렬화
class Car implements Serializable {
String Name;
String Color;
boolean Gasoline;
Car(String aName, String aColor, boolean aGasoline) {
Name = aName;
Color = aColor;
Gasoline = aGasoline;
}
void OutInfo() {
System.out.printf("이름 = %s, 색상 = %s, 연료 = %s\n",
Name, Color, Gasoline ? "휘발유":"경유");
}
}
public class JavaExam {
public static void main(String[] args) throws Exception {
Car Pride = new Car("프라이드", "파랑", true);
// 파일로 출력
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("pride.car"));
out.writeObject(Pride);
out.close();
System.out.println("파일로 기록");
// 파일로부터 입력
ObjectInputStream in = new ObjectInputStream(new FileInputStream("pride.car"));
Car Pride2 = (Car)in.readObject();
in.close();
Pride2.OutInfo();
}
}
//*/
/* 직렬화 대상. static, transient는 제외된다.
class Car implements Serializable {
String Name;
String Color;
transient boolean Gasoline;
static int Count = 0;
Car(String aName, String aColor, boolean aGasoline) {
Name = aName;
Color = aColor;
Gasoline = aGasoline;
}
void OutInfo() {
System.out.printf("이름 = %s, 색상 = %s, 연료 = %s\n",
Name, Color, Gasoline ? "휘발유":"경유");
}
}
public class JavaExam {
public static void main(String[] args) throws Exception {
Car Pride = new Car("프라이드", "파랑", true);
// 파일로 출력
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("pride2.car"));
out.writeObject(Pride);
out.close();
System.out.println("파일로 기록");
// 파일로부터 입력
ObjectInputStream in = new ObjectInputStream(new FileInputStream("pride2.car"));
Car Pride2 = (Car)in.readObject();
in.close();
Pride2.OutInfo();
}
}
//*/
/* 디폴트 직렬화
class Bitmap implements Serializable {
byte[] raster;
public Bitmap(int width) {
raster = new byte[width];
int i;
for (i=0;i<100;i++) raster[i] = 1;
for (i=100;i<width/2;i++) raster[i] = 8;
for (i=width/2;i<width;i++) raster[i] = 7;
}
}
public class JavaExam {
public static void main(String[] args) throws Exception {
Bitmap girl = new Bitmap(32000);
// 파일로 출력
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("girl.bitmap"));
out.writeObject(girl);
out.close();
// 파일로부터 입력
ObjectInputStream in = new ObjectInputStream(new FileInputStream("girl.bitmap"));
Bitmap girl2 = (Bitmap)in.readObject();
in.close();
}
}
//*/
/* 커스텀 직렬화
class Bitmap implements Serializable {
byte[] raster;
public Bitmap(int width) {
raster = new byte[width];
int i;
for (i=0;i<100;i++) raster[i] = 1;
for (i=100;i<width/2;i++) raster[i] = 8;
for (i=width/2;i<width;i++) raster[i] = 7;
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.writeInt(raster.length);
int num = 1;
byte value = raster[0];
for (int i = 1; i < raster.length; i++) {
if (value == raster[i]) {
num++;
} else {
out.writeByte(value);
out.writeInt(num);
num = 1;
value = raster[i];
}
}
if (num != 1) {
out.writeByte(value);
out.writeInt(num);
}
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
int length = in.readInt();
raster = new byte[length];
int num;
byte value;
int offset;
for (offset = 0;offset < length;) {
value = in.readByte();
num = in.readInt();
for (int i = 0; i < num ; i++) {
raster[offset] = value;
offset++;
}
}
}
}
public class JavaExam {
public static void main(String[] args) throws Exception {
Bitmap girl = new Bitmap(32000);
// 파일로 출력
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("girl2.bitmap"));
out.writeObject(girl);
out.close();
// 파일로부터 입력
ObjectInputStream in = new ObjectInputStream(new FileInputStream("girl2.bitmap"));
Bitmap girl2 = (Bitmap)in.readObject();
in.close();
}
}
//*/
댓글