diff --git a/flash/Array.exe b/flash/Array.exe new file mode 100644 index 0000000..dd86822 Binary files /dev/null and b/flash/Array.exe differ diff --git a/flash/Array.swf b/flash/Array.swf new file mode 100644 index 0000000..a757ea8 Binary files /dev/null and b/flash/Array.swf differ diff --git a/flash/Initialization.exe b/flash/Initialization.exe new file mode 100644 index 0000000..f86ee3b Binary files /dev/null and b/flash/Initialization.exe differ diff --git a/flash/Initialization.swf b/flash/Initialization.swf new file mode 100644 index 0000000..fc55461 Binary files /dev/null and b/flash/Initialization.swf differ diff --git a/flash/MemberVar.exe b/flash/MemberVar.exe new file mode 100644 index 0000000..d225126 Binary files /dev/null and b/flash/MemberVar.exe differ diff --git a/flash/MemberVar.swf b/flash/MemberVar.swf new file mode 100644 index 0000000..6e11fbf Binary files /dev/null and b/flash/MemberVar.swf differ diff --git a/flash/MultiDim.exe b/flash/MultiDim.exe new file mode 100644 index 0000000..039c163 Binary files /dev/null and b/flash/MultiDim.exe differ diff --git a/flash/MultiDim.swf b/flash/MultiDim.swf new file mode 100644 index 0000000..8938795 Binary files /dev/null and b/flash/MultiDim.swf differ diff --git a/flash/PrimitiveParam.exe b/flash/PrimitiveParam.exe new file mode 100644 index 0000000..e3a2e54 Binary files /dev/null and b/flash/PrimitiveParam.exe differ diff --git a/flash/PrimitiveParam.swf b/flash/PrimitiveParam.swf new file mode 100644 index 0000000..50c6b3d Binary files /dev/null and b/flash/PrimitiveParam.swf differ diff --git a/flash/RecursiveCall.exe b/flash/RecursiveCall.exe new file mode 100644 index 0000000..ef91154 Binary files /dev/null and b/flash/RecursiveCall.exe differ diff --git a/flash/RecursiveCall.swf b/flash/RecursiveCall.swf new file mode 100644 index 0000000..9b49b59 Binary files /dev/null and b/flash/RecursiveCall.swf differ diff --git a/flash/ReferenceParam.exe b/flash/ReferenceParam.exe new file mode 100644 index 0000000..4f6d54f Binary files /dev/null and b/flash/ReferenceParam.exe differ diff --git a/flash/ReferenceParam.swf b/flash/ReferenceParam.swf new file mode 100644 index 0000000..61b2ab5 Binary files /dev/null and b/flash/ReferenceParam.swf differ diff --git a/flash/SerialNo.exe b/flash/SerialNo.exe new file mode 100644 index 0000000..54f8f98 Binary files /dev/null and b/flash/SerialNo.exe differ diff --git a/flash/SerialNo.swf b/flash/SerialNo.swf new file mode 100644 index 0000000..224bedb Binary files /dev/null and b/flash/SerialNo.swf differ diff --git a/flash/Super.exe b/flash/Super.exe new file mode 100644 index 0000000..10c4269 Binary files /dev/null and b/flash/Super.exe differ diff --git a/flash/Super.swf b/flash/Super.swf new file mode 100644 index 0000000..e5fb225 Binary files /dev/null and b/flash/Super.swf differ diff --git a/flash/logo.swf b/flash/logo.swf new file mode 100644 index 0000000..806021a Binary files /dev/null and b/flash/logo.swf differ diff --git a/java_jungsuk3e_src_20170601.zip b/java_jungsuk3e_src_20170601.zip new file mode 100644 index 0000000..e438a2d Binary files /dev/null and b/java_jungsuk3e_src_20170601.zip differ diff --git a/source/ch1/Hello.java b/source/ch1/Hello.java new file mode 100644 index 0000000..3a601b8 --- /dev/null +++ b/source/ch1/Hello.java @@ -0,0 +1,5 @@ +class Hello { + public static void main(String[] args) { + System.out.println("Hello, world."); // È­¸é¿¡ ±ÛÀÚ¸¦ Ãâ·ÂÇÑ´Ù. + } +} diff --git a/source/ch10/CalendarEx1.java b/source/ch10/CalendarEx1.java new file mode 100644 index 0000000..ca90502 --- /dev/null +++ b/source/ch10/CalendarEx1.java @@ -0,0 +1,28 @@ +import java.util.*; + +class CalendarEx1 { + public static void main(String[] args) + { // ±âº»ÀûÀ¸·Î ÇöÀ糯¥¿Í ½Ã°£À¸·Î ¼³Á¤µÈ´Ù. + Calendar today = Calendar.getInstance(); + System.out.println("ÀÌ ÇØÀÇ ³âµµ : " + today.get(Calendar.YEAR)); + System.out.println("¿ù(0~11, 0:1¿ù): " + today.get(Calendar.MONTH)); + System.out.println("ÀÌ ÇØÀÇ ¸î ° ÁÖ: " + today.get(Calendar.WEEK_OF_YEAR)); + System.out.println("ÀÌ ´ÞÀÇ ¸î ° ÁÖ: " + today.get(Calendar.WEEK_OF_MONTH)); + // DATE¿Í DAY_OF_MONTH´Â °°´Ù. + System.out.println("ÀÌ ´ÞÀÇ ¸î ÀÏ: " + today.get(Calendar.DATE)); + System.out.println("ÀÌ ´ÞÀÇ ¸î ÀÏ: " + today.get(Calendar.DAY_OF_MONTH)); + System.out.println("ÀÌ ÇØÀÇ ¸î ÀÏ: " + today.get(Calendar.DAY_OF_YEAR)); + System.out.println("¿äÀÏ(1~7, 1:ÀÏ¿äÀÏ): " + today.get(Calendar.DAY_OF_WEEK)); // 1:ÀÏ¿äÀÏ, 2:¿ù¿äÀÏ, ... 7:Åä¿äÀÏ + System.out.println("ÀÌ ´ÞÀÇ ¸î ° ¿äÀÏ: " + today.get(Calendar.DAY_OF_WEEK_IN_MONTH)); + System.out.println("¿ÀÀü_¿ÀÈÄ(0:¿ÀÀü, 1:¿ÀÈÄ): " + today.get(Calendar.AM_PM)); + System.out.println("½Ã°£(0~11): " + today.get(Calendar.HOUR)); + System.out.println("½Ã°£(0~23): " + today.get(Calendar.HOUR_OF_DAY)); + System.out.println("ºÐ(0~59): " + today.get(Calendar.MINUTE)); + System.out.println("ÃÊ(0~59): " + today.get(Calendar.SECOND)); + System.out.println("1000ºÐÀÇ 1ÃÊ(0~999): " + today.get(Calendar.MILLISECOND)); + + // õºÐÀÇ 1Ãʸ¦ ½Ã°£À¸·Î Ç¥½ÃÇϱâ À§ÇØ 3600000À¸·Î ³ª´©¾ú´Ù.(1½Ã°£ = 60 * 60ÃÊ) + System.out.println("TimeZone(-12~+12): " + (today.get(Calendar.ZONE_OFFSET)/(60*60*1000))); + System.out.println("ÀÌ ´ÞÀÇ ¸¶Áö¸· ³¯: " + today.getActualMaximum(Calendar.DATE) ); // ÀÌ ´ÞÀÇ ¸¶Áö¸· ÀÏÀ» ã´Â´Ù. + } +} diff --git a/source/ch10/CalendarEx2.java b/source/ch10/CalendarEx2.java new file mode 100644 index 0000000..55ab4c2 --- /dev/null +++ b/source/ch10/CalendarEx2.java @@ -0,0 +1,26 @@ +import java.util.*; + +class CalendarEx2 { + public static void main(String[] args) { + // ¿äÀÏÀº 1ºÎÅÍ ½ÃÀÛÇϱ⠶§¹®¿¡, DAY_OF_WEEK[0]Àº ºñ¿öµÎ¾ú´Ù. + final String[] DAY_OF_WEEK = {"", "ÀÏ", "¿ù", "È­", "¼ö", "¸ñ", "±Ý", "Åä"}; + + Calendar date1 = Calendar.getInstance(); + Calendar date2 = Calendar.getInstance(); + + // monthÀÇ °æ¿ì 0ºÎÅÍ ½ÃÀÛÇϱ⠶§¹®¿¡ 8¿ùÀÎ °æ¿ì, 7·Î ÁöÁ¤ÇؾßÇÑ´Ù. + // date1.set(2015, Calendar.AUGUST, 15);¿Í °°ÀÌ ÇÒ ¼öµµ ÀÖ´Ù. + date1.set(2015, 7, 15); // 2015³â 8¿ù 15ÀÏ·Î ³¯Â¥¸¦ ¼³Á¤ÇÑ´Ù. + System.out.println("date1Àº "+ toString(date1) + DAY_OF_WEEK[date1.get(Calendar.DAY_OF_WEEK)]+"¿äÀÏÀÌ°í,"); + System.out.println("¿À´Ã(date2)Àº " + toString(date2) + DAY_OF_WEEK[date2.get(Calendar.DAY_OF_WEEK)]+"¿äÀÏÀÔ´Ï´Ù."); + + // µÎ ³¯Â¥°£ÀÇ Â÷À̸¦ ¾òÀ¸·Á¸é, getTimeInMillis() õºÐÀÇ ÀÏÃÊ ´ÜÀ§·Î º¯È¯ÇؾßÇÑ´Ù. + long difference = (date2.getTimeInMillis() - date1.getTimeInMillis())/1000; + System.out.println("±× ³¯(date1)ºÎÅÍ Áö±Ý(date2)±îÁö " + difference +"ÃÊ°¡ Áö³µ½À´Ï´Ù."); + System.out.println("ÀÏ(day)·Î °è»êÇϸé " + difference/(24*60*60) +"ÀÏÀÔ´Ï´Ù."); // 1ÀÏ = 24 * 60 * 60 + } + + public static String toString(Calendar date) { + return date.get(Calendar.YEAR)+"³â "+ (date.get(Calendar.MONTH)+1) +"¿ù " + date.get(Calendar.DATE) + "ÀÏ "; + } +} diff --git a/source/ch10/CalendarEx3.java b/source/ch10/CalendarEx3.java new file mode 100644 index 0000000..c03f9c5 --- /dev/null +++ b/source/ch10/CalendarEx3.java @@ -0,0 +1,36 @@ +import java.util.*; + +class CalendarEx3 { + public static void main(String[] args) { + final int[] TIME_UNIT = {3600, 60, 1}; // Å« ´ÜÀ§¸¦ ¾Õ¿¡ ³õ´Â´Ù. + final String[] TIME_UNIT_NAME = {"½Ã°£ ", "ºÐ ", "ÃÊ "}; + + Calendar time1 = Calendar.getInstance(); + Calendar time2 = Calendar.getInstance(); + + // time1ÀÇ ½Ã°£À» 10½Ã 20ºÐ 30ÃÊ·Î ¼³Á¤ÇÑ´Ù. + time1.set(Calendar.HOUR_OF_DAY, 10); + time1.set(Calendar.MINUTE, 20); + time1.set(Calendar.SECOND, 30); + + // time2ÀÇ ½Ã°£À» 20½Ã 30ºÐ 10ÃÊ·Î ¼³Á¤ÇÑ´Ù. + time2.set(Calendar.HOUR_OF_DAY, 20); + time2.set(Calendar.MINUTE, 30); + time2.set(Calendar.SECOND, 10); + + System.out.println("time1 :"+time1.get(Calendar.HOUR_OF_DAY)+"½Ã " + time1.get(Calendar.MINUTE) +"ºÐ " + time1.get(Calendar.SECOND) + "ÃÊ"); + System.out.println("time2 :"+time2.get(Calendar.HOUR_OF_DAY)+"½Ã " + time2.get(Calendar.MINUTE) +"ºÐ " + time2.get(Calendar.SECOND) + "ÃÊ"); + + long difference = Math.abs(time2.getTimeInMillis() - time1.getTimeInMillis())/1000; + System.out.println("time1°ú time2ÀÇ Â÷ÀÌ´Â "+ difference +"ÃÊ ÀÔ´Ï´Ù."); + + String tmp = ""; + + for(int i=0; i < TIME_UNIT.length;i++) { + tmp += difference/TIME_UNIT[i]+ TIME_UNIT_NAME[i]; + difference %= TIME_UNIT[i]; + } + + System.out.println("½ÃºÐÃÊ·Î º¯È¯Çϸé " + tmp + "ÀÔ´Ï´Ù."); + } +} diff --git a/source/ch10/CalendarEx4.java b/source/ch10/CalendarEx4.java new file mode 100644 index 0000000..264d48d --- /dev/null +++ b/source/ch10/CalendarEx4.java @@ -0,0 +1,30 @@ +import java.util.*; + +class CalendarEx4 { + public static void main(String[] args) { + Calendar date = Calendar.getInstance(); + + date.set(2005, 7, 31); // 2005³â 8¿ù 31ÀÏ + + System.out.println(toString(date)); + System.out.println("= 1ÀÏ ÈÄ ="); + date.add(Calendar.DATE, 1); + System.out.println(toString(date)); + + System.out.println("= 6´Þ Àü ="); + date.add(Calendar.MONTH, -6); + System.out.println(toString(date)); + + System.out.println("= 31ÀÏ ÈÄ(roll) ="); + date.roll(Calendar.DATE, 31); + System.out.println(toString(date)); + + System.out.println("= 31ÀÏ ÈÄ(add) ="); + date.add(Calendar.DATE, 31); + System.out.println(toString(date)); + } + + public static String toString(Calendar date) { + return date.get(Calendar.YEAR)+"³â "+ (date.get(Calendar.MONTH)+1) +"¿ù " + date.get(Calendar.DATE) + "ÀÏ"; + } +} diff --git a/source/ch10/CalendarEx5.java b/source/ch10/CalendarEx5.java new file mode 100644 index 0000000..6983705 --- /dev/null +++ b/source/ch10/CalendarEx5.java @@ -0,0 +1,16 @@ +import java.util.*; + +class CalendarEx5 { + public static void main(String[] args) { + Calendar date = Calendar.getInstance(); + + date.set(2015, 0, 31); // 2005³â 1¿ù 31ÀÏ + System.out.println(toString(date)); + date.roll(Calendar.MONTH, 1); + System.out.println(toString(date)); + } + + public static String toString(Calendar date) { + return date.get(Calendar.YEAR)+"³â "+ (date.get(Calendar.MONTH)+1) +"¿ù " + date.get(Calendar.DATE) + "ÀÏ"; + } +} diff --git a/source/ch10/CalendarEx6.java b/source/ch10/CalendarEx6.java new file mode 100644 index 0000000..7301406 --- /dev/null +++ b/source/ch10/CalendarEx6.java @@ -0,0 +1,46 @@ +import java.util.*; + +class CalendarEx6 { + public static void main(String[] args) { + if(args.length !=2) { + System.out.println("Usage : java CalendarEx6 2015 9"); + return; + } + int year = Integer.parseInt(args[0]); + int month = Integer.parseInt(args[1]); + + int START_DAY_OF_WEEK = 0; + int END_DAY = 0; + + Calendar sDay = Calendar.getInstance(); // ½ÃÀÛÀÏ + Calendar eDay = Calendar.getInstance(); // ³¡ÀÏ + + // ¿ùÀÇ °æ¿ì 0 ºÎÅÍ 11±îÁöÀÇ °ªÀ» °¡Áö¹Ç·Î 1À» »©ÁÖ¾î¾ß ÇÑ´Ù. + // ¿¹¸¦ µé¾î, 2004³â 11¿ù 1ÀÏÀº sDay.set(2004, 10, 1);°ú °°ÀÌ ÇØÁà¾ß ÇÑ´Ù. + sDay.set(year, month-1, 1); + eDay.set(year, month, 1); + + // ´ÙÀ½´ÞÀÇ Ã¹³¯¿¡¼­ ÇϷ縦 »©¸é ÇöÀç´ÞÀÇ ¸¶Áö¸· ³¯ÀÌ µÈ´Ù. + // 12¿ù 1ÀÏ¿¡¼­ ÇϷ縦 »©¸é 11¿ù 30ÀÏÀÌ µÈ´Ù. + eDay.add(Calendar.DATE, -1); + + // ù ¹ø° ¿äÀÏÀÌ ¹«½¼ ¿äÀÏÀÎÁö ¾Ë¾Æ³½´Ù. + START_DAY_OF_WEEK = sDay.get(Calendar.DAY_OF_WEEK); + // eDay¿¡ ÁöÁ¤µÈ ³¯Â¥¸¦ ¾ò¾î¿Â´Ù. + END_DAY = eDay.get(Calendar.DATE); + + System.out.println(" " + args[0] +"³â " + args[1] +"¿ù"); + System.out.println(" SU MO TU WE TH FR SA"); + + // ÇØ´ç ¿ùÀÇ 1ÀÏÀÌ ¾î´À ¿äÀÏÀÎÁö¿¡ µû¶ó¼­ °ø¹éÀ» Ãâ·ÂÇÑ´Ù. + // ¸¸ÀÏ 1ÀÏÀÌ ¼ö¿äÀÏÀ̶ó¸é °ø¹éÀ» ¼¼ ¹ø Âï´Â´Ù.(ÀÏ¿äÀϺÎÅÍ ½ÃÀÛ) + for(int i=1; i < START_DAY_OF_WEEK; i++) { + System.out.print(" "); + } + + for(int i=1, n=START_DAY_OF_WEEK ; i <= END_DAY; i++, n++) { + System.out.print((i < 10)? " "+i : " "+i ); + if(n%7==0) System.out.println(); + } + } +} diff --git a/source/ch10/CalendarEx7.java b/source/ch10/CalendarEx7.java new file mode 100644 index 0000000..d1fd22b --- /dev/null +++ b/source/ch10/CalendarEx7.java @@ -0,0 +1,37 @@ +import java.util.*; + +class CalendarEx7 { + public static void main(String[] args) { + if(args.length !=2) { + System.out.println("Usage : java CalendarEx7 2015 11"); + return; + } + + int year = Integer.parseInt(args[0]); + int month = Integer.parseInt(args[1]); + + Calendar sDay = Calendar.getInstance(); // ½ÃÀÛÀÏ + Calendar eDay = Calendar.getInstance(); // ³¡ÀÏ + + // ¿ùÀÇ °æ¿ì 0 ºÎÅÍ 11±îÁöÀÇ °ªÀ» °¡Áö¹Ç·Î 1À» »©Áà¾ßÇÑ´Ù. + // ¿¹¸¦ µé¾î, 2004³â 11¿ù 1ÀÏÀº sDay.set(2004, 10, 1);°ú °°ÀÌ ÇØÁà¾ß ÇÑ´Ù. + sDay.set(year, month-1, 1); // ÀԷ¿ùÀÇ 1ÀÏ·Î ¼³Á¤ÇÑ´Ù. + // ÀԷ¿ùÀÇ ¸»ÀÏ·Î ¼³Á¤ÇÑ´Ù. + eDay.set(year, month-1, sDay.getActualMaximum(Calendar.DATE)); + // 1ÀÏÀÌ ¼ÓÇÑ ÁÖÀÇ ÀÏ¿äÀÏ·Î ³¯Â¥¼³Á¤. + sDay.add(Calendar.DATE, -sDay.get(Calendar.DAY_OF_WEEK) + 1); + // ¸»ÀÏÀÌ ¼ÓÇÑ ÁÖÀÇ Åä¿äÀÏ·Î ³¯Â¥¼³Á¤ + eDay.add(Calendar.DATE, 7 - eDay.get(Calendar.DAY_OF_WEEK)); + + System.out.println(" " + year +"³â " + month +"¿ù"); + System.out.println(" SU MO TU WE TH FR SA"); + + //½ÃÀÛ ÀϺÎÅÍ ¸¶Áö¸· ÀϱîÁö(sDay <= eDay) 1ÀϾ¿ Áõ°¡½ÃÅ°¸é¼­ ÀÏ(Calendar.DATE)À» Ãâ·Â + for(int n=1; sDay.before(eDay) || sDay.equals(eDay); sDay.add(Calendar.DATE, 1)) { + int day = sDay.get(Calendar.DATE); + System.out.print((day < 10)? " "+day : " "+day ); + + if(n++%7==0) System.out.println(); // 7ÀÏÄ¡¸¦ Âï°í ³ª¼­ ÁÙÀ» ¹Ù²Û´Ù. + } + } // main +} diff --git a/source/ch10/CalendarEx8.java b/source/ch10/CalendarEx8.java new file mode 100644 index 0000000..f571a9d --- /dev/null +++ b/source/ch10/CalendarEx8.java @@ -0,0 +1,13 @@ +class CalendarEx8 { + public static void main(String[] args){ + String date1 = "201508"; + String date2 = "201405"; + + // ³â°ú ¿ùÀ» substringÀ¸·Î Àß¶ó¼­ Á¤¼ö·Î º¯È¯ÇÑ´Ù. + // ³â¿¡ 12¸¦ °öÇؼ­ ¿ù·Î º¯È¯ÇÑ ´ÙÀ½¿¡ »¬¼ÀÀ» ÇÏ¸é °³¿ùÂ÷¸¦ ±¸ÇÒ ¼ö ÀÖ´Ù. + int month1 = Integer.parseInt(date1.substring(0,4))* 12 + Integer.parseInt(date1.substring(4)); + int month2 = Integer.parseInt(date2.substring(0,4))* 12 + Integer.parseInt(date2.substring(4)); + + System.out.println(date1 +"°ú " + date2 + "ÀÇ Â÷ÀÌ´Â " + Math.abs(month1-month2) + "°³¿ù ÀÔ´Ï´Ù."); + } +} diff --git a/source/ch10/CalendarEx9.java b/source/ch10/CalendarEx9.java new file mode 100644 index 0000000..f013b7b --- /dev/null +++ b/source/ch10/CalendarEx9.java @@ -0,0 +1,84 @@ +class CalendarEx9 { + public static void main(String[] args) { + System.out.println("2014. 5. 31 :" + getDayOfWeek(2014, 5, 31)); + System.out.println("2012. 6. 1 :" + getDayOfWeek(2012, 6, 1)); + System.out.println("2014. 5. 1 - 2014.4.28 :" + dayDiff(2014,5,1,2014,4,28)); + System.out.println("2015. 6. 29 : "+convertDateToDay(2015, 6, 29)); + System.out.println("735778 : "+convertDayToDate(735778)); + } + + // °¢ ´ÞÀÇ ¸¶Áö¸·ÀÏ + public static int[] endOfMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + + public static boolean isLeapYear(int year) { + return ((year%4==0)&&(year%100!=0)||(year%400==0)); + } + + public static int dayDiff(int y1, int m1, int d1, int y2, int m2, int d2) { + return convertDateToDay(y1, m1, d1) - convertDateToDay(y2, m2, d2); + } + + public static int getDayOfWeek(int year, int month, int day) { + // 1~7ÀÇ °ªÀ» ¹ÝȯÇÑ´Ù. °á°ú°¡ 1À̸é ÀÏ¿äÀÏÀÌ´Ù. + return convertDateToDay(year, month, day)%7 + 1; + } + + public static String convertDayToDate(int day) { + int year=1; + int month=0; + int numOfLeapYear =0; // À±³âÀÇ ¼ö + + while(true) { + int aYear = isLeapYear(year)? 366 :365; + if (day > aYear ) { + day-= aYear; + year++; + } else { + break; + } + } + + while(true) { + int endDay = endOfMonth[month]; + // À±³âÀÌ°í À±´ÞÀÌ Æ÷ÇԵǾî ÀÖÀ¸¸é, 1ÀÏÀ» ´õ »«´Ù. + if(isLeapYear(year) && month == 1) endDay++; + + if(day > endDay) { + day -= endDay; + month++; + } else { + break; + } + } + + return year+"-"+(month+1)+"-"+day; + } + + public static int convertDateToDay(int year, int month, int day) { + int numOfLeapYear =0; // À±³âÀÇ ¼ö + + // Àü³âµµ±îÁöÀÇ À±³âÀÇ ¼ö¸¦ ±¸ÇÑ´Ù. + for(int i=1;i < year; i++) { + if(isLeapYear(i)) + numOfLeapYear++; + } + + // Àü³âµµ±îÁöÀÇ ÀÏ ¼ö¸¦ ±¸ÇÑ´Ù. + int toLastYearDaySum = (year-1) * 365 + numOfLeapYear; + + // ¿ÃÇØÀÇ ÇöÀç ¿ù±îÁöÀÇ Àϼö °è»ê + int thisYearDaySum =0; + + for(int i=0; i < month-1; i++) { + thisYearDaySum+=endOfMonth[i]; + } + + // À±³âÀÌ°í, 2¿ùÀÌ Æ÷ÇԵǾî ÀÖÀ¸¸é 1ÀÏÀ» Áõ°¡½ÃŲ´Ù. + if (month > 2 && isLeapYear(year)) + thisYearDaySum++; + + thisYearDaySum+=day; + + return toLastYearDaySum+thisYearDaySum; + } +} diff --git a/source/ch10/ChoiceFormatEx1.java b/source/ch10/ChoiceFormatEx1.java new file mode 100644 index 0000000..56078ad --- /dev/null +++ b/source/ch10/ChoiceFormatEx1.java @@ -0,0 +1,18 @@ +import java.util.*; +import java.text.*; + +class n { + public static void main(String[] args) { + double[] limits = {60, 70, 80, 90}; // ³·Àº °ªºÎÅÍ Å« °ªÀÇ ¼ø¼­·Î Àû¾î¾ßÇÑ´Ù. + // limits, grades°£ÀÇ ¼ø¼­¿Í °³¼ö¸¦ ¸ÂÃß¾î¾ß ÇÑ´Ù. + String[] grades = {"D", "C", "B", "A"}; + + int[] scores = { 100, 95, 88, 70, 52, 60, 70}; + + ChoiceFormat form = new ChoiceFormat(limits, grades); + + for(int i=0;i "); + + double d = num.doubleValue(); + System.out.print(d + " -> "); + + System.out.println(df2.format(num)); + } catch(Exception e) {} + } // main +} diff --git a/source/ch10/MessageFormatEx1.java b/source/ch10/MessageFormatEx1.java new file mode 100644 index 0000000..26b67d2 --- /dev/null +++ b/source/ch10/MessageFormatEx1.java @@ -0,0 +1,15 @@ +import java.util.*; +import java.text.*; + +class MessageFormatEx1 { + public static void main(String[] args) { + String msg = "Name: {0} \nTel: {1} \nAge:{2} \nBirthday:{3}"; + + Object[] arguments = { + "ÀÌÀÚ¹Ù","02-123-1234", "27", "07-09" + }; + + String result = MessageFormat.format(msg, arguments); + System.out.println(result); + } +} diff --git a/source/ch10/MessageFormatEx2.java b/source/ch10/MessageFormatEx2.java new file mode 100644 index 0000000..aad32c3 --- /dev/null +++ b/source/ch10/MessageFormatEx2.java @@ -0,0 +1,19 @@ +import java.util.*; +import java.text.*; + +class MessageFormatEx2 { + public static void main(String[] args) { + String tableName = "CUST_INFO"; + String msg = "INSERT INTO "+ tableName +" VALUES (''{0}'',''{1}'',{2},''{3}'');"; + + Object[][] arguments = { + {"ÀÌÀÚ¹Ù","02-123-1234", "27", "07-09"}, + {"±èÇÁ·Î","032-333-1234", "33", "10-07"}, + }; + + for(int i=0; i < arguments.length;i++) { + String result = MessageFormat.format(msg, arguments[i]); + System.out.println(result); + } + } // main +} diff --git a/source/ch10/MessageFormatEx3.java b/source/ch10/MessageFormatEx3.java new file mode 100644 index 0000000..b2e546a --- /dev/null +++ b/source/ch10/MessageFormatEx3.java @@ -0,0 +1,21 @@ +import java.text.*; + +class MessageFormatEx3 { + public static void main(String[] args) throws Exception { + String[] data = { + "INSERT INTO CUST_INFO VALUES ('ÀÌÀÚ¹Ù','02-123-1234',27,'07-09');", + "INSERT INTO CUST_INFO VALUES ('±èÇÁ·Î','032-333-1234',33,'10-07');" + }; + + String pattern = "INSERT INTO CUST_INFO VALUES ({0},{1},{2},{3});"; + MessageFormat mf = new MessageFormat(pattern); + + for(int i=0; i < data.length;i++) { + Object[] objs = mf.parse(data[i]); + for(int j=0; j < objs.length; j++) { + System.out.print(objs[j] + ","); + } + System.out.println(); + } + } // main +} diff --git a/source/ch10/MessageFormatEx4.java b/source/ch10/MessageFormatEx4.java new file mode 100644 index 0000000..a580f98 --- /dev/null +++ b/source/ch10/MessageFormatEx4.java @@ -0,0 +1,23 @@ +import java.util.*; +import java.text.*; +import java.io.*; + +class MessageFormatEx4 { + public static void main(String[] args) throws Exception { + String tableName = "CUST_INFO"; + String fileName = "data4.txt"; + String msg = "INSERT INTO "+ tableName + " VALUES ({0},{1},{2},{3});"; + Scanner s = new Scanner(new File(fileName)); + + String pattern = "{0},{1},{2},{3}"; + MessageFormat mf = new MessageFormat(pattern); + + while(s.hasNextLine()) { + String line = s.nextLine(); + Object[] objs = mf.parse(line); + System.out.println(MessageFormat.format(msg, objs)); + } + + s.close(); // ÀÛ¾÷ÀÌ ³¡³µÀ¸´Ï Scanner¿¡¼­ »ç¿ëÇÑ ÆÄÀÏÀ» ´Ý¾Æ ÁØ´Ù. + } // main +} diff --git a/source/ch10/NewTimeEx1.java b/source/ch10/NewTimeEx1.java new file mode 100644 index 0000000..b09c5a4 --- /dev/null +++ b/source/ch10/NewTimeEx1.java @@ -0,0 +1,27 @@ +import java.time.*; +import java.time.temporal.*; + +class NewTimeEx1 { + public static void main(String[] args) { + LocalDate today = LocalDate.now(); // ¿À´ÃÀÇ ³¯Â¥ + LocalTime now = LocalTime.now(); // ÇöÀç ½Ã°£ + + LocalDate birthDate = LocalDate.of(1999, 12, 31); // 1999³â 12¿ù 31ÀÏ + LocalTime birthTime = LocalTime.of(23, 59, 59); // 23½Ã 59ºÐ 59ÃÊ + + System.out.println("today="+today); + System.out.println("now="+now); + System.out.println("birthDate="+birthDate); // 1999-12-31 + System.out.println("birthTime="+birthTime); // 23:59:59 + + System.out.println(birthDate.withYear(2000)); // 2000-12-31 + System.out.println(birthDate.plusDays(1)); // 2001-01-01 + System.out.println(birthDate.plus(1,ChronoUnit.DAYS)); //2001-01-02 + + // 23:59:59 -> 23:00 + System.out.println(birthTime.truncatedTo(ChronoUnit.HOURS)); + // ƯÁ¤ ChronoFieldÀÇ ¹üÀ§¸¦ ¾Ë¾Æ³»´Â ¹æ¹ý + System.out.println(ChronoField.CLOCK_HOUR_OF_DAY.range()); // 1-24 + System.out.println(ChronoField.HOUR_OF_DAY.range()); // 0-23 + } +} diff --git a/source/ch10/NewTimeEx2.java b/source/ch10/NewTimeEx2.java new file mode 100644 index 0000000..8df985f --- /dev/null +++ b/source/ch10/NewTimeEx2.java @@ -0,0 +1,30 @@ +import java.time.*; +import java.time.temporal.*; + +class NewTimeEx2 { + public static void main(String[] args) { + LocalDate date = LocalDate.of(2015, 12, 31); // 2015³â 12¿ù 31ÀÏ + LocalTime time = LocalTime.of(12,34,56); // 12½Ã 23ºÐ 56ÃÊ + + // 2015³â 12¿ù 31ÀÏ 12½Ã 23ºÐ 56ÃÊ + LocalDateTime dt = LocalDateTime.of(date, time); + + ZoneId zid = ZoneId.of("Asia/Seoul"); + ZonedDateTime zdt = dt.atZone(zid); +// String strZid = zdt.getZone().getId(); + + ZonedDateTime seoulTime = ZonedDateTime.now(); + ZoneId nyId = ZoneId.of("America/New_York"); + ZonedDateTime nyTime = ZonedDateTime.now().withZoneSameInstant(nyId); + + // ZonedDatetime -> OffsetDateTime + OffsetDateTime odt = zdt.toOffsetDateTime(); + + System.out.println(dt); + System.out.println(zid); + System.out.println(zdt); + System.out.println(seoulTime); + System.out.println(nyTime); + System.out.println(odt); + } +} diff --git a/source/ch10/NewTimeEx3.java b/source/ch10/NewTimeEx3.java new file mode 100644 index 0000000..facc952 --- /dev/null +++ b/source/ch10/NewTimeEx3.java @@ -0,0 +1,36 @@ +import java.time.*; +import java.time.temporal.*; +import static java.time.DayOfWeek.*; +import static java.time.temporal.TemporalAdjusters.*; + +class DayAfterTomorrow implements TemporalAdjuster { + @Override + public Temporal adjustInto(Temporal temporal) { + return temporal.plus(2, ChronoUnit.DAYS); + } +} + +class NewTimeEx3 { + public static void main(String[] args) { + LocalDate today = LocalDate.now(); + LocalDate date = today.with(new DayAfterTomorrow()); + + p(today); // System.out.println(today); + p(date); + + p(today.with(firstDayOfNextMonth())); // ´ÙÀ½ ´ÞÀÇ Ã¹ ³¯ + p(today.with(firstDayOfMonth())); // ÀÌ ´ÞÀÇ Ã¹ ³¯ + p(today.with(lastDayOfMonth())); // ÀÌ ´ÞÀÇ ¸¶Áö¸· ³¯ + p(today.with(firstInMonth(TUESDAY))); // ÀÌ ´ÞÀÇ Ã¹¹ø° È­¿äÀÏ + p(today.with(lastInMonth(TUESDAY))); // ÀÌ ´ÞÀÇ ¸¶Áö¸· È­¿äÀÏ + p(today.with(previous(TUESDAY))); // Áö³­ ÁÖ È­¿äÀÏ + p(today.with(previousOrSame(TUESDAY))); // Áö³­ ÁÖ È­¿äÀÏ(¿À´Ã Æ÷ÇÔ) + p(today.with(next(TUESDAY))); // ´ÙÀ½ ÁÖ È­¿äÀÏ + p(today.with(nextOrSame(TUESDAY))); // ´ÙÀ½ ÁÖ È­¿äÀÏ(¿À´Ã Æ÷ÇÔ) + p(today.with(dayOfWeekInMonth(4, TUESDAY))); // ÀÌ ´ÞÀÇ 4¹ø° È­¿äÀÏ + } + + static void p(Object obj) { // ¶óÀÎÀÇ ±æÀ̸¦ ÁÙÀ̱â À§ÇØ »õ·Î Á¤ÀÇÇÑ ¸Þ¼­µå + System.out.println(obj); + } +} diff --git a/source/ch10/NewTimeEx4.java b/source/ch10/NewTimeEx4.java new file mode 100644 index 0000000..020e93b --- /dev/null +++ b/source/ch10/NewTimeEx4.java @@ -0,0 +1,35 @@ +import java.time.*; +import java.time.temporal.*; + +class NewTimeEx4 { + public static void main(String[] args) { + LocalDate date1 = LocalDate.of(2014, 1, 1); + LocalDate date2 = LocalDate.of(2015, 12, 31); + + Period pe = Period.between(date1, date2); + + System.out.println("date1="+date1); + System.out.println("date2="+date2); + System.out.println("pe="+pe); + + System.out.println("YEAR=" +pe.get(ChronoUnit.YEARS)); + System.out.println("MONTH="+pe.get(ChronoUnit.MONTHS)); + System.out.println("DAY=" +pe.get(ChronoUnit.DAYS)); + + LocalTime time1 = LocalTime.of( 0, 0, 0); + LocalTime time2 = LocalTime.of(12,34,56); // 12½Ã°£ 23ºÐ 56ÃÊ + + Duration du = Duration.between(time1, time2); + + System.out.println("time1="+time1); + System.out.println("time2="+time2); + System.out.println("du="+du); + + LocalTime tmpTime = LocalTime.of(0,0).plusSeconds(du.getSeconds()); + + System.out.println("HOUR=" +tmpTime.getHour()); + System.out.println("MINUTE="+tmpTime.getMinute()); + System.out.println("SECOND="+tmpTime.getSecond()); + System.out.println("NANO=" +tmpTime.getNano()); + } +} diff --git a/source/ch11/ArrayListEx1.java b/source/ch11/ArrayListEx1.java new file mode 100644 index 0000000..db431fe --- /dev/null +++ b/source/ch11/ArrayListEx1.java @@ -0,0 +1,47 @@ +import java.util.*; + +class ArrayListEx1{ + public static void main(String[] args) { + ArrayList list1 = new ArrayList(10); + list1.add(new Integer(5)); + list1.add(new Integer(4)); + list1.add(new Integer(2)); + list1.add(new Integer(0)); + list1.add(new Integer(1)); + list1.add(new Integer(3)); + + ArrayList list2 = new ArrayList(list1.subList(1,4)); + print(list1, list2); + + Collections.sort(list1); // list1°ú list2¸¦ Á¤·ÄÇÑ´Ù. + Collections.sort(list2); // Collections.sort(List l) + print(list1, list2); + + System.out.println("list1.containsAll(list2):" + list1.containsAll(list2)); + + list2.add("B"); + list2.add("C"); + list2.add(3, "A"); + print(list1, list2); + + list2.set(3, "AA"); + print(list1, list2); + + // list1¿¡¼­ list2¿Í °ãÄ¡´Â ºÎºÐ¸¸ ³²±â°í ³ª¸ÓÁö´Â »èÁ¦ÇÑ´Ù. + System.out.println("list1.retainAll(list2):" + list1.retainAll(list2)); + print(list1, list2); + + // list2¿¡¼­ list1¿¡ Æ÷ÇÔµÈ °´Ã¼µéÀ» »èÁ¦ÇÑ´Ù. + for(int i= list2.size()-1; i >= 0; i--) { + if(list1.contains(list2.get(i))) + list2.remove(i); + } + print(list1, list2); + } // mainÀÇ ³¡ + + static void print(ArrayList list1, ArrayList list2) { + System.out.println("list1:"+list1); + System.out.println("list2:"+list2); + System.out.println(); + } +} // class diff --git a/source/ch11/ArrayListEx2.java b/source/ch11/ArrayListEx2.java new file mode 100644 index 0000000..b2b9c15 --- /dev/null +++ b/source/ch11/ArrayListEx2.java @@ -0,0 +1,22 @@ +import java.util.*; + +class ArrayListEx2 { + public static void main(String[] args) { + final int LIMIT = 10; // ÀÚ¸£°íÀÚ ÇÏ´Â ±ÛÀÚÀÇ °³¼ö¸¦ ÁöÁ¤ÇÑ´Ù. + String source = "0123456789abcdefghijABCDEFGHIJ!@#$%^&*()ZZZ"; + int length = source.length(); + + List list = new ArrayList(length/LIMIT + 10); // Å©±â¸¦ ¾à°£ ¿©À¯ ÀÖ°Ô Àâ´Â´Ù. + + for(int i=0; i < length; i+=LIMIT) { + if(i+LIMIT < length ) + list.add(source.substring(i, i+LIMIT)); + else + list.add(source.substring(i)); + } + + for(int i=0; i < list.size(); i++) { + System.out.println(list.get(i)); + } + } // main() +} diff --git a/source/ch11/ArrayListLinkedListTest.java b/source/ch11/ArrayListLinkedListTest.java new file mode 100644 index 0000000..ba64aac --- /dev/null +++ b/source/ch11/ArrayListLinkedListTest.java @@ -0,0 +1,53 @@ +import java.util.*; + +public class ArrayListLinkedListTest { + public static void main(String args[]) { + // Ãß°¡ÇÒ µ¥ÀÌÅÍÀÇ °³¼ö¸¦ °í·ÁÇÏ¿© ÃæºÐÈ÷ Àâ¾Æ¾ßÇÑ´Ù. + ArrayList al = new ArrayList(2000000); + LinkedList ll = new LinkedList(); + + System.out.println("= ¼øÂ÷ÀûÀ¸·Î Ãß°¡Çϱâ ="); + System.out.println("ArrayList :"+add1(al)); + System.out.println("LinkedList :"+add1(ll)); + System.out.println(); + System.out.println("= Áß°£¿¡ Ãß°¡Çϱâ ="); + System.out.println("ArrayList :"+add2(al)); + System.out.println("LinkedList :"+add2(ll)); + System.out.println(); + System.out.println("= Áß°£¿¡¼­ »èÁ¦Çϱâ ="); + System.out.println("ArrayList :"+remove2(al)); + System.out.println("LinkedList :"+remove2(ll)); + System.out.println(); + System.out.println("= ¼øÂ÷ÀûÀ¸·Î »èÁ¦Çϱâ ="); + System.out.println("ArrayList :"+remove1(al)); + System.out.println("LinkedList :"+remove1(ll)); + } + + public static long add1(List list) { + long start = System.currentTimeMillis(); + for(int i=0; i<1000000;i++) list.add(i+""); + long end = System.currentTimeMillis(); + return end - start; + } + + public static long add2(List list) { + long start = System.currentTimeMillis(); + for(int i=0; i<10000;i++) list.add(500, "X"); + long end = System.currentTimeMillis(); + return end - start; + } + + public static long remove1(List list) { + long start = System.currentTimeMillis(); + for(int i=list.size()-1; i >= 0;i--) list.remove(i); + long end = System.currentTimeMillis(); + return end - start; + } + + public static long remove2(List list) { + long start = System.currentTimeMillis(); + for(int i=0; i<10000;i++) list.remove(i); + long end = System.currentTimeMillis(); + return end - start; + } +} diff --git a/source/ch11/ArrayListLinkedListTest2.java b/source/ch11/ArrayListLinkedListTest2.java new file mode 100644 index 0000000..7da4011 --- /dev/null +++ b/source/ch11/ArrayListLinkedListTest2.java @@ -0,0 +1,28 @@ +import java.util.*; + +public class ArrayListLinkedListTest2 { + public static void main(String args[]) { + ArrayList al = new ArrayList(1000000); + LinkedList ll = new LinkedList(); + add(al); + add(ll); + + System.out.println("= Á¢±Ù½Ã°£Å×½ºÆ® ="); + System.out.println("ArrayList :"+access(al)); + System.out.println("LinkedList :"+access(ll)); + } + + public static void add(List list) { + for(int i=0; i<100000;i++) list.add(i+""); + } + + public static long access(List list) { + long start = System.currentTimeMillis(); + + for(int i=0; i<10000;i++) list.get(i); + + long end = System.currentTimeMillis(); + + return end - start; + } +} diff --git a/source/ch11/ArraysEx.java b/source/ch11/ArraysEx.java new file mode 100644 index 0000000..058889f --- /dev/null +++ b/source/ch11/ArraysEx.java @@ -0,0 +1,52 @@ +import java.util.*; + +class ArraysEx { + public static void main(String[] args) { + int[] arr = {0,1,2,3,4}; + int[][] arr2D = {{11,12,13}, {21,22,23}}; + + System.out.println("arr="+Arrays.toString(arr)); + System.out.println("arr2D="+Arrays.deepToString(arr2D)); + + int[] arr2 = Arrays.copyOf(arr, arr.length); + int[] arr3 = Arrays.copyOf(arr, 3); + int[] arr4 = Arrays.copyOf(arr, 7); + int[] arr5 = Arrays.copyOfRange(arr, 2, 4); + int[] arr6 = Arrays.copyOfRange(arr, 0, 7); + + System.out.println("arr2="+ Arrays.toString(arr2)); + System.out.println("arr3="+ Arrays.toString(arr3)); + System.out.println("arr4="+ Arrays.toString(arr4)); + System.out.println("arr5="+ Arrays.toString(arr5)); + System.out.println("arr6="+ Arrays.toString(arr6)); + + int[] arr7 = new int[5]; + Arrays.fill(arr7, 9); // arr=[9,9,9,9,9] + System.out.println("arr7="+Arrays.toString(arr7)); + + Arrays.setAll(arr7, i -> (int)(Math.random()*6)+1); + System.out.println("arr7="+Arrays.toString(arr7)); + + for(int i : arr7) { + char[] graph = new char[i]; + Arrays.fill(graph, '*'); + System.out.println(new String(graph)+i); + } + + String[][] str2D = new String[][]{{"aaa","bbb"},{"AAA","BBB"}}; + String[][] str2D2 = new String[][]{{"aaa","bbb"},{"AAA","BBB"}}; + + System.out.println(Arrays.equals(str2D, str2D2)); // false + System.out.println(Arrays.deepEquals(str2D, str2D2)); // true + + char[] chArr = { 'A', 'D', 'C', 'B', 'E' }; + + int idx = Arrays.binarySearch(chArr, 'B'); + System.out.println("chArr="+Arrays.toString(chArr)); + System.out.println("index of B ="+Arrays.binarySearch(chArr, 'B')); + System.out.println("= After sorting ="); + Arrays.sort(chArr); + System.out.println("chArr="+Arrays.toString(chArr)); + System.out.println("index of B ="+Arrays.binarySearch(chArr, 'B')); + } +} diff --git a/source/ch11/AsciiPrint.java b/source/ch11/AsciiPrint.java new file mode 100644 index 0000000..f25b857 --- /dev/null +++ b/source/ch11/AsciiPrint.java @@ -0,0 +1,7 @@ +class AsciiPrint{ + public static void main(String[] args) { + char ch = ' '; + for(int i=0; i < 95; i++) // °ø¹é(' ')ÀÌÈÄÀÇ ¹®ÀÚµéÀ» Ãâ·ÂÇÑ´Ù. + System.out.print(ch++); + } +} diff --git a/source/ch11/Bingo.java b/source/ch11/Bingo.java new file mode 100644 index 0000000..9a807ba --- /dev/null +++ b/source/ch11/Bingo.java @@ -0,0 +1,23 @@ +import java.util.*; + +class Bingo { + public static void main(String[] args) { + Set set = new HashSet(); +// Set set = new LinkedHashSet(); + int[][] board = new int[5][5]; + + for(int i=0; set.size() < 25; i++) { + set.add((int)(Math.random()*50)+1+""); + } + + Iterator it = set.iterator(); + + for(int i=0; i < board.length; i++) { + for(int j=0; j < board[i].length; j++) { + board[i][j] = Integer.parseInt((String)it.next()); + System.out.print((board[i][j] < 10 ? " " : " ") + board[i][j]); + } + System.out.println(); + } + } // main +} diff --git a/source/ch11/ComparatorEx.java b/source/ch11/ComparatorEx.java new file mode 100644 index 0000000..168b244 --- /dev/null +++ b/source/ch11/ComparatorEx.java @@ -0,0 +1,29 @@ +import java.util.*; + +class ComparatorEx { + public static void main(String[] args) { + String[] strArr = {"cat", "Dog", "lion", "tiger"}; + + Arrays.sort(strArr); // StringÀÇ Comparable±¸Çö¿¡ ÀÇÇÑ Á¤·Ä + System.out.println("strArr=" + Arrays.toString(strArr)); + + Arrays.sort(strArr, String.CASE_INSENSITIVE_ORDER); // ´ë¼Ò¹®ÀÚ ±¸ºÐ¾ÈÇÔ + System.out.println("strArr=" + Arrays.toString(strArr)); + + Arrays.sort(strArr, new Descending()); // ¿ª¼ø Á¤·Ä + System.out.println("strArr=" + Arrays.toString(strArr)); + } +} + +class Descending implements Comparator { + public int compare(Object o1, Object o2){ + if( o1 instanceof Comparable && o2 instanceof Comparable) { + Comparable c1 = (Comparable)o1; + Comparable c2 = (Comparable)o2; + return c1.compareTo(c2) * -1 ; // -1À» °öÇؼ­ ±âº» Á¤·Ä¹æ½ÄÀÇ ¿ªÀ¸·Î º¯°æÇÑ´Ù. + // ¶Ç´Â c2.compareTo(c1)¿Í °°ÀÌ ¼ø¼­¸¦ ¹Ù²ãµµ µÈ´Ù. + + } + return -1; + } +} diff --git a/source/ch11/ExpValidCheck.java b/source/ch11/ExpValidCheck.java new file mode 100644 index 0000000..edb3198 --- /dev/null +++ b/source/ch11/ExpValidCheck.java @@ -0,0 +1,36 @@ +import java.util.*; + +public class ExpValidCheck { + public static void main(String[] args) { + if(args.length!=1){ + System.out.println("Usage : java ExpValidCheck \"EXPRESSION\""); + System.out.println("Example : java ExpValidCheck \"((2+3)*1)+3\""); + System.exit(0); + } + + Stack st = new Stack(); + String expression = args[0]; + + System.out.println("expression:"+expression); + + try { + for(int i=0; i < expression.length();i++){ + char ch = expression.charAt(i); + + if(ch=='('){ + st.push(ch+""); + } else if(ch==')') { + st.pop(); + } + } + + if(st.isEmpty()){ + System.out.println("°ýÈ£°¡ ÀÏÄ¡ÇÕ´Ï´Ù."); + } else { + System.out.println("°ýÈ£°¡ ÀÏÄ¡ÇÏÁö ¾Ê½À´Ï´Ù."); + } + } catch (EmptyStackException e) { + System.out.println("°ýÈ£°¡ ÀÏÄ¡ÇÏÁö ¾Ê½À´Ï´Ù."); + } // try + } +} diff --git a/source/ch11/HashMapEx1.java b/source/ch11/HashMapEx1.java new file mode 100644 index 0000000..1b605a9 --- /dev/null +++ b/source/ch11/HashMapEx1.java @@ -0,0 +1,34 @@ +import java.util.*; + +class HashMapEx1 { + public static void main(String[] args) { + HashMap map = new HashMap(); + map.put("myId", "1234"); + map.put("asdf", "1111"); + map.put("asdf", "1234"); + + Scanner s = new Scanner(System.in); // È­¸éÀ¸·ÎºÎÅÍ ¶óÀδÜÀ§·Î ÀԷ¹޴´Ù. + + while(true) { + System.out.println("id¿Í password¸¦ ÀÔ·ÂÇØÁÖ¼¼¿ä."); + System.out.print("id :"); + String id = s.nextLine().trim(); + + System.out.print("password :"); + String password = s.nextLine().trim(); + System.out.println(); + + if(!map.containsKey(id)) { + System.out.println("ÀÔ·ÂÇϽŠid´Â Á¸ÀçÇÏÁö ¾Ê½À´Ï´Ù. ´Ù½Ã ÀÔ·ÂÇØÁÖ¼¼¿ä."); + continue; + } else { + if(!(map.get(id)).equals(password)) { + System.out.println("ºñ¹Ð¹øÈ£°¡ ÀÏÄ¡ÇÏÁö ¾Ê½À´Ï´Ù. ´Ù½Ã ÀÔ·ÂÇØÁÖ¼¼¿ä."); + } else { + System.out.println("id¿Í ºñ¹Ð¹øÈ£°¡ ÀÏÄ¡ÇÕ´Ï´Ù."); + break; + } + } + } // while + } // mainÀÇ ³¡ +} diff --git a/source/ch11/HashMapEx2.java b/source/ch11/HashMapEx2.java new file mode 100644 index 0000000..d538dfa --- /dev/null +++ b/source/ch11/HashMapEx2.java @@ -0,0 +1,38 @@ +import java.util.*; + +class HashMapEx2 { + public static void main(String[] args) { + HashMap map = new HashMap(); + map.put("±èÀÚ¹Ù", new Integer(90)); + map.put("±èÀÚ¹Ù", new Integer(100)); + map.put("ÀÌÀÚ¹Ù", new Integer(100)); + map.put("°­ÀÚ¹Ù", new Integer(80)); + map.put("¾ÈÀÚ¹Ù", new Integer(90)); + + Set set = map.entrySet(); + Iterator it = set.iterator(); + + while(it.hasNext()) { + Map.Entry e = (Map.Entry)it.next(); + System.out.println("À̸§ : "+ e.getKey() + ", Á¡¼ö : " + e.getValue()); + } + + set = map.keySet(); + System.out.println("Âü°¡ÀÚ ¸í´Ü : " + set); + + Collection values = map.values(); + it = values.iterator(); + + int total = 0; + + while(it.hasNext()) { + Integer i = (Integer)it.next(); + total += i.intValue(); + } + + System.out.println("ÃÑÁ¡ : " + total); + System.out.println("Æò±Õ : " + (float)total/set.size()); + System.out.println("ÃÖ°íÁ¡¼ö : " + Collections.max(values)); + System.out.println("ÃÖÀúÁ¡¼ö : " + Collections.min(values)); + } +} diff --git a/source/ch11/HashMapEx3.java b/source/ch11/HashMapEx3.java new file mode 100644 index 0000000..8fdcf76 --- /dev/null +++ b/source/ch11/HashMapEx3.java @@ -0,0 +1,58 @@ +import java.util.*; + +class HashMapEx3 { + static HashMap phoneBook = new HashMap(); + + public static void main(String[] args) { + addPhoneNo("Ä£±¸", "ÀÌÀÚ¹Ù", "010-111-1111"); + addPhoneNo("Ä£±¸", "±èÀÚ¹Ù", "010-222-2222"); + addPhoneNo("Ä£±¸", "±èÀÚ¹Ù", "010-333-3333"); + addPhoneNo("ȸ»ç", "±è´ë¸®", "010-444-4444"); + addPhoneNo("ȸ»ç", "±è´ë¸®", "010-555-5555"); + addPhoneNo("ȸ»ç", "¹Ú´ë¸®", "010-666-6666"); + addPhoneNo("ȸ»ç", "ÀÌ°úÀå", "010-777-7777"); + addPhoneNo("¼¼Å¹", "010-888-8888"); + + printList(); + } // main + + // ±×·ìÀ» Ãß°¡ÇÏ´Â ¸Þ¼­µå + static void addGroup(String groupName) { + if(!phoneBook.containsKey(groupName)) + phoneBook.put(groupName, new HashMap()); + } + + // ±×·ì¿¡ ÀüÈ­¹øÈ£¸¦ Ãß°¡ÇÏ´Â ¸Þ¼­µå + static void addPhoneNo(String groupName, String name, String tel) { + addGroup(groupName); + HashMap group = (HashMap)phoneBook.get(groupName); + group.put(tel, name); // À̸§Àº Áߺ¹µÉ ¼ö ÀÖÀ¸´Ï ÀüÈ­¹øÈ£¸¦ key·Î ÀúÀåÇÑ´Ù. + } + + static void addPhoneNo(String name, String tel) { + addPhoneNo("±âŸ", name, tel); + } + + // ÀüÈ­¹øÈ£ºÎ Àüü¸¦ Ãâ·ÂÇÏ´Â ¸Þ¼­µå + static void printList() { + Set set = phoneBook.entrySet(); + Iterator it = set.iterator(); + + while(it.hasNext()) { + Map.Entry e = (Map.Entry)it.next(); + + Set subSet = ((HashMap)e.getValue()).entrySet(); + Iterator subIt = subSet.iterator(); + + System.out.println(" * "+e.getKey()+"["+subSet.size()+"]"); + + while(subIt.hasNext()) { + Map.Entry subE = (Map.Entry)subIt.next(); + String telNo = (String)subE.getKey(); + String name = (String)subE.getValue(); + System.out.println(name + " " + telNo ); + } + System.out.println(); + } + } // printList() +} // class diff --git a/source/ch11/HashMapEx4.java b/source/ch11/HashMapEx4.java new file mode 100644 index 0000000..1e4bb9d --- /dev/null +++ b/source/ch11/HashMapEx4.java @@ -0,0 +1,36 @@ +import java.util.*; + +class HashMapEx4 { + public static void main(String[] args) { + String[] data = { "A","K","A","K","D","K","A","K","K","K","Z","D" }; + + HashMap map = new HashMap(); + + for(int i=0; i < data.length; i++) { + if(map.containsKey(data[i])) { + Integer value = (Integer)map.get(data[i]); + map.put(data[i], new Integer(value.intValue() + 1)); + } else { + map.put(data[i], new Integer(1)); + } + } + + Iterator it = map.entrySet().iterator(); + + while(it.hasNext()) { + Map.Entry entry = (Map.Entry)it.next(); + int value = ((Integer)entry.getValue()).intValue(); + System.out.println(entry.getKey() + " : " + printBar('#', value) + " " + value ); + } + } // main + + public static String printBar(char ch, int value) { + char[] bar = new char[value]; + + for(int i=0; i < bar.length; i++) { + bar[i] = ch; + } + + return new String(bar); // String(char[] chArr) + } +} diff --git a/source/ch11/HashSetEx1.java b/source/ch11/HashSetEx1.java new file mode 100644 index 0000000..9e1ba1f --- /dev/null +++ b/source/ch11/HashSetEx1.java @@ -0,0 +1,14 @@ +import java.util.*; + +class HashSetEx1 { + public static void main(String[] args) { + Object[] objArr = {"1",new Integer(1),"2","2","3","3","4","4","4"}; + Set set = new HashSet(); + + for(int i=0; i < objArr.length; i++) { + set.add(objArr[i]); // HashSet¿¡ objArrÀÇ ¿ä¼ÒµéÀ» ÀúÀåÇÑ´Ù. + } + // HashSet¿¡ ÀúÀåµÈ ¿ä¼ÒµéÀ» Ãâ·ÂÇÑ´Ù. + System.out.println(set); + } +} diff --git a/source/ch11/HashSetEx3.java b/source/ch11/HashSetEx3.java new file mode 100644 index 0000000..d80cafb --- /dev/null +++ b/source/ch11/HashSetEx3.java @@ -0,0 +1,28 @@ +import java.util.*; + +class HashSetEx3 { + public static void main(String[] args) { + HashSet set = new HashSet(); + + set.add("abc"); + set.add("abc"); + set.add(new Person("David",10)); + set.add(new Person("David",10)); + + System.out.println(set); + } +} + +class Person { + String name; + int age; + + Person(String name, int age) { + this.name = name; + this.age = age; + } + + public String toString() { + return name +":"+ age; + } +} diff --git a/source/ch11/HashSetEx4.java b/source/ch11/HashSetEx4.java new file mode 100644 index 0000000..2b46388 --- /dev/null +++ b/source/ch11/HashSetEx4.java @@ -0,0 +1,41 @@ +import java.util.*; + +class HashSetEx4 { + public static void main(String[] args) { + HashSet set = new HashSet(); + + set.add(new String("abc")); + set.add(new String("abc")); + set.add(new Person2("David",10)); + set.add(new Person2("David",10)); + + System.out.println(set); + } +} + +class Person2 { + String name; + int age; + + Person2(String name, int age) { + this.name = name; + this.age = age; + } + + public boolean equals(Object obj) { + if(obj instanceof Person2) { + Person2 tmp = (Person2)obj; + return name.equals(tmp.name) && age==tmp.age; + } + + return false; + } + + public int hashCode() { + return (name+age).hashCode(); + } + + public String toString() { + return name +":"+ age; + } +} diff --git a/source/ch11/HashSetEx5.java b/source/ch11/HashSetEx5.java new file mode 100644 index 0000000..22d2293 --- /dev/null +++ b/source/ch11/HashSetEx5.java @@ -0,0 +1,47 @@ +import java.util.*; + +class HashSetEx5 { + public static void main(String args[]) { + HashSet setA = new HashSet(); + HashSet setB = new HashSet(); + HashSet setHab = new HashSet(); + HashSet setKyo = new HashSet(); + HashSet setCha = new HashSet(); + + setA.add("1"); setA.add("2"); + setA.add("3"); setA.add("4"); + setA.add("5"); + System.out.println("A = "+setA); + + setB.add("4"); setB.add("5"); + setB.add("6"); setB.add("7"); + setB.add("8"); + System.out.println("B = "+setB); + + Iterator it = setB.iterator(); + while(it.hasNext()) { + Object tmp = it.next(); + if(setA.contains(tmp)) + setKyo.add(tmp); + } + + it = setA.iterator(); + while(it.hasNext()) { + Object tmp = it.next(); + if(!setB.contains(tmp)) + setCha.add(tmp); + } + + it = setA.iterator(); + while(it.hasNext()) + setHab.add(it.next()); + + it = setB.iterator(); + while(it.hasNext()) + setHab.add(it.next()); + + System.out.println("A ¡û B = "+setKyo); // ÇÑ±Û ¤§À» ´©¸£°í ÇÑÀÚÅ° + System.out.println("A ¡ú B = "+setHab); // ÇÑ±Û ¤§À» ´©¸£°í ÇÑÀÚÅ° + System.out.println("A - B = "+setCha); + } +} diff --git a/source/ch11/HashSetLotto.java b/source/ch11/HashSetLotto.java new file mode 100644 index 0000000..c2a4aa1 --- /dev/null +++ b/source/ch11/HashSetLotto.java @@ -0,0 +1,16 @@ +import java.util.*; + +class HashSetLotto { + public static void main(String[] args) { + Set set = new HashSet(); + + for (int i = 0; set.size() < 6 ; i++) { + int num = (int)(Math.random()*45) + 1; + set.add(new Integer(num)); + } + + List list = new LinkedList(set); // LinkedList(Collection c) + Collections.sort(list); // Collections.sort(List list) + System.out.println(list); + } +} diff --git a/source/ch11/IteratorEx1.java b/source/ch11/IteratorEx1.java new file mode 100644 index 0000000..226e56e --- /dev/null +++ b/source/ch11/IteratorEx1.java @@ -0,0 +1,18 @@ +import java.util.*; + +class IteratorEx1 { + public static void main(String[] args) { + ArrayList list = new ArrayList(); + list.add("1"); + list.add("2"); + list.add("3"); + list.add("4"); + list.add("5"); + + Iterator it = list.iterator(); + while(it.hasNext()) { + Object obj = it.next(); + System.out.println(obj); + } + } // main +} diff --git a/source/ch11/IteratorEx2.java b/source/ch11/IteratorEx2.java new file mode 100644 index 0000000..f02906e --- /dev/null +++ b/source/ch11/IteratorEx2.java @@ -0,0 +1,33 @@ +import java.util.*; + +public class IteratorEx2 { + public static void main(String[] args) { + ArrayList original = new ArrayList(10); + ArrayList copy1 = new ArrayList(10); + ArrayList copy2 = new ArrayList(10); + + for(int i=0; i < 10; i++) + original.add(i+""); + + Iterator it = original.iterator(); + + while(it.hasNext()) + copy1.add(it.next()); + + System.out.println("= Original¿¡¼­ copy1·Î º¹»ç(copy) ="); + System.out.println("original:"+original); + System.out.println("copy1:"+copy1); + System.out.println(); + + it = original.iterator(); // Iterator´Â Àç»ç¿ëÀÌ ¾ÈµÇ¹Ç·Î, ´Ù½Ã ¾ò¾î¿Í¾ß ÇÑ´Ù. + + while(it.hasNext()){ + copy2.add(it.next()); + it.remove(); + } + + System.out.println("= Original¿¡¼­ copy2·Î À̵¿(move) ="); + System.out.println("original:"+original); + System.out.println("copy2:"+copy2); + } // main +} // class diff --git a/source/ch11/ListIteratorEx1.java b/source/ch11/ListIteratorEx1.java new file mode 100644 index 0000000..f4b0a7c --- /dev/null +++ b/source/ch11/ListIteratorEx1.java @@ -0,0 +1,24 @@ +import java.util.*; + +class ListIteratorEx1 { + public static void main(String[] args) { + ArrayList list = new ArrayList(); + list.add("1"); + list.add("2"); + list.add("3"); + list.add("4"); + list.add("5"); + + ListIterator it = list.listIterator(); + + while(it.hasNext()) { + System.out.print(it.next()); // ¼ø¹æÇâÀ¸·Î ÁøÇàÇϸ鼭 Àоî¿Â´Ù. + } + System.out.println(); + + while(it.hasPrevious()) { + System.out.print(it.previous()); // ¿ª¹æÇâÀ¸·Î ÁøÇàÇϸ鼭 Àоî¿Â´Ù. + } + System.out.println(); + } +} diff --git a/source/ch11/MyStack.java b/source/ch11/MyStack.java new file mode 100644 index 0000000..03971d5 --- /dev/null +++ b/source/ch11/MyStack.java @@ -0,0 +1,41 @@ +import java.util.*; + +class MyStack extends Vector { + public Object push(Object item) { + addElement(item); + return item; + } + + public Object pop() { + Object obj = peek(); // Stack¿¡ ÀúÀåµÈ ¸¶Áö¸· ¿ä¼Ò¸¦ Àоî¿Â´Ù. + // ¸¸ÀÏ StackÀÌ ºñ¾îÀÖÀ¸¸é peek()¸Þ¼­µå°¡ EmptyStackExceptionÀ» ¹ß»ý½ÃŲ´Ù. + // ¸¶Áö¸· ¿ä¼Ò¸¦ »èÁ¦ÇÑ´Ù. ¹è¿­ÀÇ index°¡ 0 ºÎÅÍ ½ÃÀÛÇϹǷΠ1À» »©ÁØ´Ù. + removeElementAt(size() - 1); + + return obj; + } + + public Object peek() { + int len = size(); + + if (len == 0) + throw new EmptyStackException(); + // ¸¶Áö¸· ¿ä¼Ò¸¦ ¹ÝȯÇÑ´Ù. ¹è¿­ÀÇ index°¡ 0 ºÎÅÍ ½ÃÀÛÇϹǷΠ1À» »©ÁØ´Ù. + return elementAt(len - 1); + } + + public boolean empty() { + return size() == 0; + } + + public int search(Object o) { + int i = lastIndexOf(o); // ³¡¿¡¼­ºÎÅÍ °´Ã¼¸¦ ã´Â´Ù. + // ¹Ýȯ°ªÀº ÀúÀåµÈ À§Ä¡(¹è¿­ÀÇ index)ÀÌ´Ù. + if (i >= 0) { // °´Ã¼¸¦ ãÀº °æ¿ì + return size() - i; // StackÀº ¸Ç À§¿¡ ÀúÀåµÈ °´Ã¼ÀÇ index¸¦ 1·Î Á¤ÀÇÇϱ⠶§¹®¿¡ + // °è»êÀ» ÅëÇؼ­ ±¸ÇÑ´Ù. + } + + return - 1; // ÇØ´ç °´Ã¼¸¦ ãÁö ¸øÇϸé -1¸¦ ¹ÝȯÇÑ´Ù. + } +} diff --git a/source/ch11/MyVector.java b/source/ch11/MyVector.java new file mode 100644 index 0000000..2f66831 --- /dev/null +++ b/source/ch11/MyVector.java @@ -0,0 +1,130 @@ +import java.util.*; + +public class MyVector implements List { + Object[] data = null; // °´Ã¼¸¦ ´ã±â À§ÇÑ °´Ã¼¹è¿­À» ¼±¾ðÇÑ´Ù. + int capacity = 0; // ¿ë·® + int size = 0; // Å©±â + + public MyVector(int capacity) { + if (capacity < 0) + throw new IllegalArgumentException("À¯È¿ÇÏÁö ¾ÊÀº °ªÀÔ´Ï´Ù. :"+ capacity); + + this.capacity = capacity; + data = new Object[capacity]; + } + + public MyVector() { + this(10); // Å©±â¸¦ ÁöÁ¤ÇÏÁö ¾ÊÀ¸¸é Å©±â¸¦ 10À¸·Î ÇÑ´Ù. + } + + // ÃÖ¼ÒÇÑÀÇ ÀúÀå°ø°£(capacity)¸¦ È®º¸ÇÏ´Â ¸Þ¼­µå + public void ensureCapacity(int minCapacity) { + if (minCapacity - data.length > 0) + setCapacity(minCapacity); + } + + public boolean add(Object obj) { + // »õ·Î¿î °´Ã¼¸¦ ÀúÀåÇϱâ Àü¿¡ ÀúÀåÇÒ °ø°£À» È®º¸ÇÑ´Ù. + ensureCapacity(size+1); + data[size++] = obj; + return true; + } + + public Object get(int index) { + if(index < 0 || index >= size) + throw new IndexOutOfBoundsException("¹üÀ§¸¦ ¹þ¾î³µ½À´Ï´Ù."); + + return data[index]; + } + + public Object remove(int index) { + Object oldObj = null; + + if(index < 0 || index >= size) + throw new IndexOutOfBoundsException("¹üÀ§¸¦ ¹þ¾î³µ½À´Ï´Ù."); + + oldObj = data[index]; + + // »èÁ¦ÇÏ°íÀÚ ÇÏ´Â °´Ã¼°¡ ¸¶Áö¸· °´Ã¼°¡ ¾Æ´Ï¶ó¸é, ¹è¿­º¹»ç¸¦ ÅëÇØ ºóÀÚ¸®¸¦ ä¿öÁà¾ß ÇÑ´Ù. + if(index != size-1) { + System.arraycopy(data, index+1, data, index, size-index-1); + } + + // ¸¶Áö¸· µ¥ÀÌÅ͸¦ null·Î ÇÑ´Ù. ¹è¿­Àº 0 ºÎÅÍ ½ÃÀÛÇϹǷΠ¸¶Áö¸· ¿ä¼Ò´Â index°¡ size-1ÀÌ´Ù. + data[size-1] = null; + size--; + return oldObj; + } + + public boolean remove(Object obj) { + for(int i=0; i< size; i++) { + if(obj.equals(data[i])) { + remove(i); + return true; + } + } + return false; + } + + public void trimToSize() { + setCapacity(size); + } + + private void setCapacity(int capacity) { + if(this.capacity==capacity) return; // Å©±â°¡ °°À¸¸é º¯°æÇÏÁö ¾Ê´Â´Ù. + + Object[] tmp = new Object[capacity]; + System.arraycopy(data,0, tmp, 0, size); + data = tmp; + this.capacity = capacity; + } + + public void clear(){ + for (int i = 0; i < size; i++) + data[i] = null; + size = 0; + } + + public Object[] toArray(){ + Object[] result = new Object[size]; + System.arraycopy(data, 0, result, 0, size); + + return result; + } + + public boolean isEmpty() { return size==0;} + public int capacity() { return capacity; } + public int size() { return size; } +/****************************************/ +/* ListÀÎÅÍÆäÀ̽º·ÎºÎÅÍ »ó¼Ó¹ÞÀº ¸Þ¼­µåµé */ +/****************************************/ +// public int size(); +// public boolean isEmpty(); + public boolean contains(Object o){ return false;} + public Iterator iterator(){ return null; } +// public Object[] toArray(); + public Object[] toArray(Object a[]){ return null;} +// public boolean add(Object o); +// public boolean remove(Object o); + public boolean containsAll(Collection c){ return false; } + public boolean addAll(Collection c){ return false; } + public boolean addAll(int index, Collection c){ return false; } + public boolean removeAll(Collection c){ return false; } + public boolean retainAll(Collection c){ return false; } +// public void clear(); + public boolean equals(Object o){ return false; } +// public int hashCode(); +// public Object get(int index); + public Object set(int index, Object element){ return null;} + public void add(int index, Object element){} +// public Object remove(int index); + public int indexOf(Object o){ return -1;} + public int lastIndexOf(Object o){ return -1;} + public ListIterator listIterator(){ return null; } + public ListIterator listIterator(int index){ return null; } + public List subList(int fromIndex, int toIndex){ return null; } + + default void sort(Comparator c) { /* ³»¿ë»ý·« */ } // JDK1.8ºÎÅÍ + default Spliterator spliterator() { /* ³»¿ë»ý·« */ } // JDK1.8ºÎÅÍ + default void replaceAll(UnaryOperator operator){/* ³»¿ë»ý·« */} //JDK1.8ºÎÅÍ +} diff --git a/source/ch11/MyVector2.java b/source/ch11/MyVector2.java new file mode 100644 index 0000000..0d95af7 --- /dev/null +++ b/source/ch11/MyVector2.java @@ -0,0 +1,53 @@ +import java.util.*; + +public class MyVector2 extends MyVector implements Iterator { + int cursor = 0; + int lastRet = -1; + + public MyVector2(int capacity) { + super(capacity); + } + + public MyVector2() { + this(10); + } + + public String toString() { + String tmp = ""; + Iterator it = iterator(); + + for(int i=0; it.hasNext();i++) { + if(i!=0) tmp+=", "; + tmp += it.next(); // tmp += next().toString(); + } + + return "["+ tmp +"]"; + } + + public Iterator iterator() { + cursor=0; // cursor¿Í lastRet¸¦ ÃʱâÈ­ ÇÑ´Ù. + lastRet = -1; + return this; + } + + public boolean hasNext() { + return cursor != size(); + } + + public Object next(){ + Object next = get(cursor); + lastRet = cursor++; + return next; + } + + public void remove() { + // ´õÀÌ»ó »èÁ¦ÇÒ °ÍÀÌ ¾øÀ¸¸é IllegalStateException¸¦ ¹ß»ý½ÃŲ´Ù. + if(lastRet==-1) { + throw new IllegalStateException(); + } else { + remove(lastRet); + cursor--; // »èÁ¦ ÈÄ¿¡ cursorÀÇ À§Ä¡¸¦ °¨¼Ò½ÃŲ´Ù. + lastRet = -1; // lastRetÀÇ °ªÀ» ÃʱâÈ­ ÇÑ´Ù. + } + } +} // class diff --git a/source/ch11/MyVector2Test.java b/source/ch11/MyVector2Test.java new file mode 100644 index 0000000..09910c0 --- /dev/null +++ b/source/ch11/MyVector2Test.java @@ -0,0 +1,21 @@ +import java.util.*; + +class MyVector2Test { + public static void main(String args[]) { + MyVector2 v = new MyVector2(); + v.add("0"); + v.add("1"); + v.add("2"); + v.add("3"); + v.add("4"); + + System.out.println("»èÁ¦ Àü : " + v); + Iterator it = v.iterator(); + it.next(); + it.remove(); + it.next(); + it.remove(); + + System.out.println("»èÁ¦ ÈÄ : " + v); + } +} diff --git a/source/ch11/PriorityQueueEx.java b/source/ch11/PriorityQueueEx.java new file mode 100644 index 0000000..dcb2e76 --- /dev/null +++ b/source/ch11/PriorityQueueEx.java @@ -0,0 +1,20 @@ +import java.util.*; + +class PriorityQueueEx { + public static void main(String[] args) { + Queue pq = new PriorityQueue(); + pq.offer(3); // pq.offer(new Integer(3)); ¿ÀÅä¹Ú½Ì + pq.offer(1); + pq.offer(5); + pq.offer(2); + pq.offer(4); + + System.out.println(pq); // pqÀÇ ³»ºÎ ¹è¿­À» Ãâ·Â + + Object obj = null; + + // PriorityQueue¿¡ ÀúÀåµÈ ¿ä¼Ò¸¦ Çϳª¾¿ ²¨³½´Ù. + while((obj = pq.poll())!=null) + System.out.println(obj); + } +} diff --git a/source/ch11/PropertiesEx1.java b/source/ch11/PropertiesEx1.java new file mode 100644 index 0000000..928c4f5 --- /dev/null +++ b/source/ch11/PropertiesEx1.java @@ -0,0 +1,30 @@ +import java.util.*; + +class PropertiesEx1 { + public static void main(String[] args) { + Properties prop = new Properties(); + + // prop¿¡ Å°¿Í °ª(key, value)À» ÀúÀåÇÑ´Ù. + prop.setProperty("timeout","30"); + prop.setProperty("language","kr"); + prop.setProperty("size","10"); + prop.setProperty("capacity","10"); + + // prop¿¡ ÀúÀåµÈ ¿ä¼ÒµéÀ» EnumerationÀ» ÀÌ¿ëÇؼ­ Ãâ·ÂÇÑ´Ù. + Enumeration e = prop.propertyNames(); + + while(e.hasMoreElements()) { + String element = (String)e.nextElement(); + System.out.println(element + "="+ prop.getProperty(element)); + } + + System.out.println(); + prop.setProperty("size","20"); // sizeÀÇ °ªÀ» 20À¸·Î º¯°æÇÑ´Ù. + System.out.println("size=" + prop.getProperty("size")); + System.out.println("capacity=" + prop.getProperty("capacity", "20")); + System.out.println("loadfactor=" + prop.getProperty("loadfactor", "0.75")); + + System.out.println(prop); // prop¿¡ ÀúÀåµÈ ¿ä¼ÒµéÀ» Ãâ·ÂÇÑ´Ù. + prop.list(System.out); // prop¿¡ ÀúÀåµÈ ¿ä¼ÒµéÀ» È­¸é(System.out)¿¡ Ãâ·ÂÇÑ´Ù. + } +} diff --git a/source/ch11/PropertiesEx2.java b/source/ch11/PropertiesEx2.java new file mode 100644 index 0000000..f9e5b64 --- /dev/null +++ b/source/ch11/PropertiesEx2.java @@ -0,0 +1,48 @@ +import java.io.*; +import java.util.*; + +class PropertiesEx2 { + public static void main(String[] args) { + // commandline¿¡¼­ inputfileÀ» ÁöÁ¤ÇØÁÖÁö ¾ÊÀ¸¸é ÇÁ·Î±×·¥À» Á¾·áÇÑ´Ù. + if(args.length != 1) { + System.out.println("USAGE: java PropertiesEx2 INPUTFILENAME"); + System.exit(0); + } + + Properties prop = new Properties(); + + String inputFile = args[0]; + + try { + prop.load(new FileInputStream(inputFile)); + } catch(IOException e) { + System.out.println("ÁöÁ¤µÈ ÆÄÀÏÀ» ãÀ» ¼ö ¾ø½À´Ï´Ù."); + System.exit(0); + } + + String name = prop.getProperty("name"); + String[] data = prop.getProperty("data").split(","); + int max = 0; + int min = 0; + int sum = 0; + + for(int i=0; i < data.length; i++) { + int intValue = Integer.parseInt(data[i]); + if (i==0) max = min = intValue; + + if (max < intValue) { + max = intValue; + } else if (min > intValue) { + min = intValue; + } + + sum += intValue; + } + + System.out.println("À̸§ :" + name); + System.out.println("ÃÖ´ë°ª :" + max); + System.out.println("ÃÖ¼Ò°ª :" + min); + System.out.println("ÇÕ°è :" + sum); + System.out.println("Æò±Õ :" + (sum*100.0/data.length)/100); + } +} diff --git a/source/ch11/PropertiesEx3.java b/source/ch11/PropertiesEx3.java new file mode 100644 index 0000000..1d90ec6 --- /dev/null +++ b/source/ch11/PropertiesEx3.java @@ -0,0 +1,20 @@ +import java.util.*; +import java.io.*; + +class PropertiesEx3 { + public static void main(String[] args) { + Properties prop = new Properties(); + + prop.setProperty("timeout","30"); + prop.setProperty("language","ÇѱÛ"); + prop.setProperty("size","10"); + prop.setProperty("capacity","10"); + + try { + prop.store(new FileOutputStream("output.txt"), "Properties Example"); + prop.storeToXML(new FileOutputStream("output.xml"), "Properties Example"); + } catch(IOException e) { + e.printStackTrace(); + } + } // mainÀÇ ³¡ +} diff --git a/source/ch11/PropertiesEx4.java b/source/ch11/PropertiesEx4.java new file mode 100644 index 0000000..2afe6da --- /dev/null +++ b/source/ch11/PropertiesEx4.java @@ -0,0 +1,10 @@ +import java.util.*; + +class PropertiesEx4{ + public static void main(String[] args) { + Properties sysProp = System.getProperties(); + System.out.println("java.version :" + sysProp.getProperty("java.version")); + System.out.println("user.languag :" + sysProp.getProperty("user.language")); + sysProp.list(System.out); + } +} diff --git a/source/ch11/QueueEx1.java b/source/ch11/QueueEx1.java new file mode 100644 index 0000000..95bba8a --- /dev/null +++ b/source/ch11/QueueEx1.java @@ -0,0 +1,56 @@ +import java.util.*; + +class QueueEx1 { + static Queue q = new LinkedList(); + static final int MAX_SIZE = 5; // Queue¿¡ ÃÖ´ë 5°³±îÁö¸¸ ÀúÀåµÇµµ·Ï ÇÑ´Ù. + + public static void main(String[] args) { + System.out.println("help¸¦ ÀÔ·ÂÇÏ¸é µµ¿ò¸»À» º¼ ¼ö ÀÖ½À´Ï´Ù."); + + while(true) { + System.out.print(">>"); + try { + // È­¸éÀ¸·ÎºÎÅÍ ¶óÀδÜÀ§·Î ÀԷ¹޴´Ù. + Scanner s = new Scanner(System.in); + String input = s.nextLine().trim(); + + if("".equals(input)) continue; + + if(input.equalsIgnoreCase("q")) { + System.exit(0); + } else if(input.equalsIgnoreCase("help")) { + System.out.println(" help - µµ¿ò¸»À» º¸¿©ÁÝ´Ï´Ù."); + System.out.println(" q ¶Ç´Â Q - ÇÁ·Î±×·¥À» Á¾·áÇÕ´Ï´Ù."); + System.out.println(" history - ÃÖ±Ù¿¡ ÀÔ·ÂÇÑ ¸í·É¾î¸¦ " + MAX_SIZE +"°³ º¸¿©ÁÝ´Ï´Ù."); + } else if(input.equalsIgnoreCase("history")) { + int i=0; + // ÀԷ¹ÞÀº ¸í·É¾î¸¦ ÀúÀåÇÏ°í, + save(input); + + // LinkedListÀÇ ³»¿ëÀ» º¸¿©ÁØ´Ù. + LinkedList tmp = (LinkedList)q; + ListIterator it = tmp.listIterator(); + + while(it.hasNext()) { + System.out.println(++i+"."+it.next()); + } + } else { + save(input); + System.out.println(input); + } // if(input.equalsIgnoreCase("q")) { + } catch(Exception e) { + System.out.println("ÀԷ¿À·ùÀÔ´Ï´Ù."); + } + } // while(true) + } // main() + + public static void save(String input) { + // queue¿¡ ÀúÀåÇÑ´Ù. + if(!"".equals(input)) + q.offer(input); + + // queueÀÇ ÃÖ´ëÅ©±â¸¦ ³ÑÀ¸¸é Á¦ÀÏ Ã³À½ ÀÔ·ÂµÈ °ÍÀ» »èÁ¦ÇÑ´Ù. + if(q.size() > MAX_SIZE) // size()´Â CollectionÀÎÅÍÆäÀ̽º¿¡ Á¤ÀÇ + q.remove(); + } +} // end of class diff --git a/source/ch11/StackEx1.java b/source/ch11/StackEx1.java new file mode 100644 index 0000000..4854633 --- /dev/null +++ b/source/ch11/StackEx1.java @@ -0,0 +1,54 @@ +import java.util.*; + +public class StackEx1 { + public static Stack back = new Stack(); + public static Stack forward = new Stack(); + + public static void main(String[] args) { + goURL("1.³×ÀÌÆ®"); + goURL("2.¾ßÈÄ"); + goURL("3.³×À̹ö"); + goURL("4.´ÙÀ½"); + + printStatus(); + + goBack(); + System.out.println("= µÚ·Î°¡±â ¹öÆ°À» ´©¸¥ ÈÄ ="); + printStatus(); + + goBack(); + System.out.println("= 'µÚ·Î' ¹öÆ°À» ´©¸¥ ÈÄ ="); + printStatus(); + + goForward(); + System.out.println("= '¾ÕÀ¸·Î' ¹öÆ°À» ´©¸¥ ÈÄ ="); + printStatus(); + + goURL("codechobo.com"); + System.out.println("= »õ·Î¿î ÁÖ¼Ò·Î À̵¿ ÈÄ ="); + printStatus(); + } + + public static void printStatus() { + System.out.println("back:"+back); + System.out.println("forward:"+forward); + System.out.println("ÇöÀçÈ­¸éÀº '" + back.peek()+"' ÀÔ´Ï´Ù."); + System.out.println(); + } + + public static void goURL(String url){ + back.push(url); + if(!forward.empty()) + forward.clear(); + } + + public static void goForward(){ + if(!forward.empty()) + back.push(forward.pop()); + } + + public static void goBack(){ + if(!back.empty()) + forward.push(back.pop()); + } +} diff --git a/source/ch11/StackQueueEx.java b/source/ch11/StackQueueEx.java new file mode 100644 index 0000000..0af44b6 --- /dev/null +++ b/source/ch11/StackQueueEx.java @@ -0,0 +1,26 @@ +import java.util.*; + +class StackQueueEx { + public static void main(String[] args) { + Stack st = new Stack(); + Queue q = new LinkedList(); // QueueÀÎÅÍÆäÀ̽ºÀÇ ±¸ÇöüÀÎ LinkedList¸¦ »ç¿ë + + st.push("0"); + st.push("1"); + st.push("2"); + + q.offer("0"); + q.offer("1"); + q.offer("2"); + + System.out.println("= Stack ="); + while(!st.empty()) { + System.out.println(st.pop()); + } + + System.out.println("= Queue ="); + while(!q.isEmpty()) { + System.out.println(q.poll()); + } + } +} diff --git a/source/ch11/TreeMapEx1.java b/source/ch11/TreeMapEx1.java new file mode 100644 index 0000000..64b19e7 --- /dev/null +++ b/source/ch11/TreeMapEx1.java @@ -0,0 +1,70 @@ +import java.util.*; + +class TreeMapEx1 { + public static void main(String[] args) { + String[] data = { "A","K","A","K","D","K","A","K","K","K","Z","D" }; + + TreeMap map = new TreeMap(); + + for(int i=0; i < data.length; i++) { + if(map.containsKey(data[i])) { + Integer value = (Integer)map.get(data[i]); + map.put(data[i], new Integer(value.intValue() + 1)); + } else { + map.put(data[i], new Integer(1)); + } + } + + Iterator it = map.entrySet().iterator(); + + System.out.println("= ±âº»Á¤·Ä ="); + while(it.hasNext()) { + Map.Entry entry = (Map.Entry)it.next(); + int value = ((Integer)entry.getValue()).intValue(); + System.out.println(entry.getKey() + " : " + printBar('#', value) + " " + value ); + } + System.out.println(); + + // mapÀ» ArrayList·Î º¯È¯ÇÑ ´ÙÀ½¿¡ Collectons.sort()·Î Á¤·Ä + Set set = map.entrySet(); + List list = new ArrayList(set); // ArrayList(Collection c) + + // static void sort(List list, Comparator c) + Collections.sort(list, new ValueComparator()); + + it = list.iterator(); + + System.out.println("= °ªÀÇ Å©±â°¡ Å« ¼ø¼­·Î Á¤·Ä ="); + while(it.hasNext()) { + Map.Entry entry = (Map.Entry)it.next(); + int value = ((Integer)entry.getValue()).intValue(); + System.out.println(entry.getKey() + " : " + printBar('#', value) + " " + value ); + } + + } // public static void main(String[] args) + + static class ValueComparator implements Comparator { + public int compare(Object o1, Object o2) { + if(o1 instanceof Map.Entry && o2 instanceof Map.Entry) { + Map.Entry e1 = (Map.Entry)o1; + Map.Entry e2 = (Map.Entry)o2; + + int v1 = ((Integer)e1.getValue()).intValue(); + int v2 = ((Integer)e2.getValue()).intValue(); + + return v2 - v1; + } + return -1; + } + } // static class ValueComparator implements Comparator { + + public static String printBar(char ch, int value) { + char[] bar = new char[value]; + + for(int i=0; i < bar.length; i++) { + bar[i] = ch; + } + + return new String(bar); + } +} diff --git a/source/ch11/TreeSetEx1.java b/source/ch11/TreeSetEx1.java new file mode 100644 index 0000000..f44d32c --- /dev/null +++ b/source/ch11/TreeSetEx1.java @@ -0,0 +1,29 @@ +import java.util.*; + +class TreeSetEx1 { + public static void main(String[] args) { + TreeSet set = new TreeSet(); + + String from = "b"; + String to = "d"; + + set.add("abc"); + set.add("alien"); + set.add("bat"); + set.add("car"); + set.add("Car"); + set.add("disc"); + set.add("dance"); + set.add("dZZZZ"); + set.add("dzzzz"); + set.add("elephant"); + set.add("elevator"); + set.add("fan"); + set.add("flower"); + + System.out.println(set); + System.out.println("range search : from " + from +" to "+ to); + System.out.println("result1 : " + set.subSet(from, to)); + System.out.println("result2 : " + set.subSet(from, to + "zzz")); + } +} diff --git a/source/ch11/TreeSetEx2.java b/source/ch11/TreeSetEx2.java new file mode 100644 index 0000000..4f302cb --- /dev/null +++ b/source/ch11/TreeSetEx2.java @@ -0,0 +1,14 @@ +import java.util.*; + +class TreeSetEx2 { + public static void main(String[] args) { + TreeSet set = new TreeSet(); + int[] score = {80, 95, 50, 35, 45, 65, 10, 100}; + + for(int i=0; i < score.length; i++) + set.add(new Integer(score[i])); + + System.out.println("50º¸´Ù ÀÛÀº °ª :" + set.headSet(new Integer(50))); + System.out.println("50º¸´Ù Å« °ª :" + set.tailSet(new Integer(50))); + } +} diff --git a/source/ch11/TreeSetLotto.java b/source/ch11/TreeSetLotto.java new file mode 100644 index 0000000..b7b216c --- /dev/null +++ b/source/ch11/TreeSetLotto.java @@ -0,0 +1,14 @@ +import java.util.*; + +class TreeSetLotto { + public static void main(String[] args) { + Set set = new TreeSet(); + + for (int i = 0; set.size() < 6 ; i++) { + int num = (int)(Math.random()*45) + 1; + set.add(num); // set.add(new Integer(num)); + } + + System.out.println(set); + } +} diff --git a/source/ch11/VectorEx1.java b/source/ch11/VectorEx1.java new file mode 100644 index 0000000..fec88dd --- /dev/null +++ b/source/ch11/VectorEx1.java @@ -0,0 +1,33 @@ +import java.util.*; + +class VectorEx1 { + public static void main(String[] args) { + Vector v = new Vector(5); // ¿ë·®(capacity)ÀÌ 5ÀÎ Vector¸¦ »ý¼ºÇÑ´Ù. + v.add("1"); + v.add("2"); + v.add("3"); + print(v); + + v.trimToSize(); // ºó °ø°£À» ¾ø¾Ø´Ù.(¿ë·®°ú Å©±â°¡ °°¾ÆÁø´Ù.) + System.out.println("=== After trimToSize() ==="); + print(v); + + v.ensureCapacity(6); + System.out.println("=== After ensureCapacity(6) ==="); + print(v); + + v.setSize(7); + System.out.println("=== After setSize(7) ==="); + print(v); + + v.clear(); + System.out.println("=== After clear() ==="); + print(v); + } + + public static void print(Vector v) { + System.out.println(v); + System.out.println("size :" + v.size()); + System.out.println("capacity :" + v.capacity()); + } +} diff --git a/source/ch12/AnnotationEx1.java b/source/ch12/AnnotationEx1.java new file mode 100644 index 0000000..4ffb19a --- /dev/null +++ b/source/ch12/AnnotationEx1.java @@ -0,0 +1,8 @@ +class Parent { + void parentMethod() { } +} + +class Child extends Parent { + @Override + void parentmethod() { } // Á¶»ó ¸Þ¼­µåÀÇ À̸§À» À߸øÀû¾úÀ½. +} diff --git a/source/ch12/AnnotationEx2.java b/source/ch12/AnnotationEx2.java new file mode 100644 index 0000000..99343d2 --- /dev/null +++ b/source/ch12/AnnotationEx2.java @@ -0,0 +1,24 @@ +class NewClass{ + int newField; + + int getNewField() { + return newField; + } + + @Deprecated + int oldField; + + @Deprecated + int getOldField() { + return oldField; + } +} + +class AnnotationEx2 { + public static void main(String args[]) { + NewClass nc = new NewClass(); + + nc.oldField = 10; //@Depreacted°¡ ºÙÀº ´ë»óÀ» »ç¿ë + System.out.println(nc.getOldField()); //@Depreacted°¡ ºÙÀº ´ë»óÀ» »ç¿ë + } +} diff --git a/source/ch12/AnnotationEx3.java b/source/ch12/AnnotationEx3.java new file mode 100644 index 0000000..89e555a --- /dev/null +++ b/source/ch12/AnnotationEx3.java @@ -0,0 +1,33 @@ +import java.util.ArrayList; + +class NewClass{ + int newField; + + int getNewField() { + return newField; + } + + @Deprecated + int oldField; + + @Deprecated + int getOldField() { + return oldField; + } +} + + +class AnnotationEx3 { + @SuppressWarnings("deprecation") // deprecation°ü·Ã °æ°í¸¦ ¾ïÁ¦ + public static void main(String args[]) { + NewClass nc = new NewClass(); + + nc.oldField = 10; //@Depreacted°¡ ºÙÀº ´ë»óÀ» »ç¿ë + System.out.println(nc.getOldField()); //@Depreacted°¡ ºÙÀº ´ë»óÀ» »ç¿ë + + @SuppressWarnings("unchecked") // Áö³×¸¯½º °ü·Ã °æ°í¸¦ ¾ïÁ¦ + ArrayList list = new ArrayList(); // ŸÀÔÀ» ÁöÁ¤ÇÏÁö ¾ÊÀ½. + list.add(nc); + } +} + diff --git a/source/ch12/AnnotationEx4.java b/source/ch12/AnnotationEx4.java new file mode 100644 index 0000000..048d4a2 --- /dev/null +++ b/source/ch12/AnnotationEx4.java @@ -0,0 +1,30 @@ +import java.util.Arrays; + +class MyArrayList { + T[] arr; + + @SafeVarargs + @SuppressWarnings("varargs") + MyArrayList(T... arr) { + this.arr = arr; + } + + @SafeVarargs +// @SuppressWarnings("unchecked") + public static MyArrayList asList(T... a) { + return new MyArrayList<>(a); + } + + public String toString() { + return Arrays.toString(arr); + } +} + +class AnnotationEx4 { +// @SuppressWarnings("unchecked") + public static void main(String args[]) { + MyArrayList list = MyArrayList.asList("1","2","3"); + + System.out.println(list); + } +} diff --git a/source/ch12/AnnotationEx5.java b/source/ch12/AnnotationEx5.java new file mode 100644 index 0000000..6d2e9bf --- /dev/null +++ b/source/ch12/AnnotationEx5.java @@ -0,0 +1,44 @@ +import java.lang.annotation.*; + +@Deprecated +@SuppressWarnings("1111") // À¯È¿ÇÏÁö ¾ÊÀº ¾Ö³ÊÅ×À̼ÇÀº ¹«½ÃµÈ´Ù. +@TestInfo(testedBy="aaa", testDate=@DateTime(yymmdd="160101", hhmmss="235959")) +class AnnotationEx5 { + public static void main(String args[]) { + // AnnotaionEx5ÀÇ Class°´Ã¼¸¦ ¾ò´Â´Ù. + Class cls = AnnotationEx5.class; + + TestInfo anno = (TestInfo)cls.getAnnotation(TestInfo.class); + System.out.println("anno.testedBy()="+anno.testedBy()); + System.out.println("anno.testDate().yymmdd()="+anno.testDate().yymmdd()); + System.out.println("anno.testDate().hhmmss()="+anno.testDate().hhmmss()); + + for(String str : anno.testTools()) + System.out.println("testTools="+str); + + System.out.println(); + + // AnnotationEx5¿¡ Àû¿ëµÈ ¸ðµç ¾Ö³ÊÅ×À̼ÇÀ» °¡Á®¿Â´Ù. + Annotation[] annoArr = cls.getAnnotations(); + + for(Annotation a : annoArr) + System.out.println(a); + } // mainÀÇ ³¡ +} + +@Retention(RetentionPolicy.RUNTIME) // ½ÇÇà ½Ã¿¡ »ç¿ë°¡´ÉÇϵµ·Ï ÁöÁ¤ +@interface TestInfo { + int count() default 1; + String testedBy(); + String[] testTools() default "JUnit"; + TestType testType() default TestType.FIRST; + DateTime testDate(); +} + +@Retention(RetentionPolicy.RUNTIME) // ½ÇÇà ½Ã¿¡ »ç¿ë°¡´ÉÇϵµ·Ï ÁöÁ¤ +@interface DateTime { + String yymmdd(); + String hhmmss(); +} + +enum TestType { FIRST, FINAL } diff --git a/source/ch12/EnumEx1.java b/source/ch12/EnumEx1.java new file mode 100644 index 0000000..ead1a71 --- /dev/null +++ b/source/ch12/EnumEx1.java @@ -0,0 +1,43 @@ +enum Direction { EAST, SOUTH, WEST, NORTH } + +class EnumEx1 { + public static void main(String[] args) { + Direction d1 = Direction.EAST; + Direction d2 = Direction.valueOf("WEST"); + Direction d3 = Enum.valueOf(Direction.class, "EAST"); + + System.out.println("d1="+d1); + System.out.println("d2="+d2); + System.out.println("d3="+d3); + + System.out.println("d1==d2 ? "+ (d1==d2)); + System.out.println("d1==d3 ? "+ (d1==d3)); + System.out.println("d1.equals(d3) ? "+ d1.equals(d3)); +// System.out.println("d2 > d3 ? "+ (d1 > d3)); // ¿¡·¯ + System.out.println("d1.compareTo(d3) ? "+ (d1.compareTo(d3))); + System.out.println("d1.compareTo(d2) ? "+ (d1.compareTo(d2))); + + switch(d1) { + case EAST: // Direction.EAST¶ó°í ¾µ ¼ö ¾ø´Ù. + System.out.println("The direction is EAST."); + break; + case SOUTH: + System.out.println("The direction is SOUTH."); + break; + case WEST: + System.out.println("The direction is WEST."); + break; + case NORTH: + System.out.println("The direction is NORTH."); + break; + default: + System.out.println("Invalid direction."); +// break; + } + + Direction[] dArr = Direction.values(); + + for(Direction d : dArr) // for(Direction d : Direction.values()) + System.out.printf("%s=%d%n", d.name(), d.ordinal()); + } +} diff --git a/source/ch12/EnumEx2.java b/source/ch12/EnumEx2.java new file mode 100644 index 0000000..2e698cf --- /dev/null +++ b/source/ch12/EnumEx2.java @@ -0,0 +1,53 @@ +enum Direction { + EAST(1, ">"), SOUTH(2,"V"), WEST(3, "<"), NORTH(4,"^"); + + private static final Direction[] DIR_ARR = Direction.values(); + private final int value; + private final String symbol; + + Direction(int value, String symbol) { // private Direction(int value) + this.value = value; + this.symbol = symbol; + } + + public int getValue() { return value; } + public String getSymbol() { return symbol; } + + public static Direction of(int dir) { + if (dir < 1 || dir > 4) { + throw new IllegalArgumentException("Invalid value :" + dir); + } + return DIR_ARR[dir - 1]; + } + + // ¹æÇâÀ» ȸÀü½ÃÅ°´Â ¸Þ¼­µå. numÀÇ °ª¸¸Å­ 90µµ¾¿ ½Ã°è¹æÇâÀ¸·Î ȸÀüÇÑ´Ù. + public Direction rotate(int num) { + num = num % 4; + + if(num < 0) num +=4; // numÀÌ À½¼öÀÏ ¶§´Â ½Ã°è¹Ý´ë ¹æÇâÀ¸·Î ȸÀü + + return DIR_ARR[(value-1+num) % 4]; + } + + public String toString() { + return name()+getSymbol(); + } +} // enum Direction + +class EnumEx2 { + public static void main(String[] args) { + for(Direction d : Direction.values()) + System.out.printf("%s=%d%n", d.name(), d.getValue()); + + Direction d1 = Direction.EAST; + Direction d2 = Direction.of(1); + + System.out.printf("d1=%s, %d%n", d1.name(), d1.getValue()); + System.out.printf("d2=%s, %d%n", d2.name(), d2.getValue()); + + System.out.println(Direction.EAST.rotate(1)); + System.out.println(Direction.EAST.rotate(2)); + System.out.println(Direction.EAST.rotate(-1)); + System.out.println(Direction.EAST.rotate(-2)); + } +} diff --git a/source/ch12/EnumEx3.java b/source/ch12/EnumEx3.java new file mode 100644 index 0000000..59648ab --- /dev/null +++ b/source/ch12/EnumEx3.java @@ -0,0 +1,25 @@ +enum Transportation { + BUS(100) { int fare(int distance) { return distance*BASIC_FARE;}}, + TRAIN(150) { int fare(int distance) { return distance*BASIC_FARE;}}, + SHIP(100) { int fare(int distance) { return distance*BASIC_FARE;}}, + AIRPLANE(300) { int fare(int distance) { return distance*BASIC_FARE;}}; + + protected final int BASIC_FARE; // protected·Î ÇØ¾ß °¢ »ó¼ö¿¡¼­ Á¢±Ù°¡´É + + Transportation(int basicFare) { // private Transportation(int basicFare) { + BASIC_FARE = basicFare; + } + + public int getBasicFare() { return BASIC_FARE; } + + abstract int fare(int distance); // °Å¸®¿¡ µû¸¥ ¿ä±Ý °è»ê +} + +class EnumEx3 { + public static void main(String[] args) { + System.out.println("bus fare=" +Transportation.BUS.fare(100)); + System.out.println("train fare=" +Transportation.TRAIN.fare(100)); + System.out.println("ship fare=" +Transportation.SHIP.fare(100)); + System.out.println("airplane fare="+Transportation.AIRPLANE.fare(100)); + } +} diff --git a/source/ch12/EnumEx4.java b/source/ch12/EnumEx4.java new file mode 100644 index 0000000..c2f6ec9 --- /dev/null +++ b/source/ch12/EnumEx4.java @@ -0,0 +1,63 @@ +abstract class MyEnum> implements Comparable { + static int id = 0; + + int ordinal; + String name = ""; + + public int ordinal() { return ordinal; } + + MyEnum(String name) { + this.name = name; + ordinal = id++; + } + + public int compareTo(T t) { + return ordinal - t.ordinal(); + } +} + +abstract class MyTransportation extends MyEnum { + static final MyTransportation BUS = new MyTransportation("BUS", 100) { + int fare(int distance) { return distance * BASIC_FARE; } + }; + static final MyTransportation TRAIN = new MyTransportation("TRAIN", 150) { + int fare(int distance) { return distance * BASIC_FARE; } + }; + static final MyTransportation SHIP = new MyTransportation("SHIP", 100) { + int fare(int distance) { return distance * BASIC_FARE; } + }; + static final MyTransportation AIRPLANE = + new MyTransportation("AIRPLANE", 300) { + int fare(int distance) { return distance * BASIC_FARE; } + }; + + abstract int fare(int distance); // Ãß»ó ¸Þ¼­µå + + protected final int BASIC_FARE; + + private MyTransportation(String name, int basicFare) { + super(name); + BASIC_FARE = basicFare; + } + + public String name() { return name; } + public String toString() { return name; } +} + +class EnumEx4 { + public static void main(String[] args) { + MyTransportation t1 = MyTransportation.BUS; + MyTransportation t2 = MyTransportation.BUS; + MyTransportation t3 = MyTransportation.TRAIN; + MyTransportation t4 = MyTransportation.SHIP; + MyTransportation t5 = MyTransportation.AIRPLANE; + + System.out.printf("t1=%s, %d%n", t1.name(), t1.ordinal()); + System.out.printf("t2=%s, %d%n", t2.name(), t2.ordinal()); + System.out.printf("t3=%s, %d%n", t3.name(), t3.ordinal()); + System.out.printf("t4=%s, %d%n", t4.name(), t4.ordinal()); + System.out.printf("t5=%s, %d%n", t5.name(), t5.ordinal()); + System.out.println("t1==t2 ? "+(t1==t2)); + System.out.println("t1.compareTo(t3)="+ t1.compareTo(t3)); + } +} diff --git a/source/ch12/FruitBoxEx1.java b/source/ch12/FruitBoxEx1.java new file mode 100644 index 0000000..f564a5c --- /dev/null +++ b/source/ch12/FruitBoxEx1.java @@ -0,0 +1,37 @@ +import java.util.ArrayList; + +class Fruit { public String toString() { return "Fruit";}} +class Apple extends Fruit { public String toString() { return "Apple";}} +class Grape extends Fruit { public String toString() { return "Grape";}} +class Toy { public String toString() { return "Toy" ;}} + +class FruitBoxEx1 { + public static void main(String[] args) { + Box fruitBox = new Box(); + Box appleBox = new Box(); + Box toyBox = new Box(); +// Box grapeBox = new Box(); // ¿¡·¯. ŸÀÔ ºÒÀÏÄ¡ + + fruitBox.add(new Fruit()); + fruitBox.add(new Apple()); // OK. void add(Fruit item) + + appleBox.add(new Apple()); + appleBox.add(new Apple()); +// appleBox.add(new Toy()); // ¿¡·¯. Box¿¡´Â Apple¸¸ ´ãÀ» ¼ö ÀÖÀ½ + + toyBox.add(new Toy()); +// toyBox.add(new Apple()); // ¿¡·¯. Box¿¡´Â AppleÀ» ´ãÀ» ¼ö ¾øÀ½ + + System.out.println(fruitBox); + System.out.println(appleBox); + System.out.println(toyBox); + } // mainÀÇ ³¡ +} + +class Box { + ArrayList list = new ArrayList(); + void add(T item) { list.add(item); } + T get(int i) { return list.get(i); } + int size() { return list.size(); } + public String toString() { return list.toString();} +} diff --git a/source/ch12/FruitBoxEx2.java b/source/ch12/FruitBoxEx2.java new file mode 100644 index 0000000..b4b2542 --- /dev/null +++ b/source/ch12/FruitBoxEx2.java @@ -0,0 +1,41 @@ +import java.util.ArrayList; + +class Fruit implements Eatable { + public String toString() { return "Fruit";} +} +class Apple extends Fruit { public String toString() { return "Apple";}} +class Grape extends Fruit { public String toString() { return "Grape";}} +class Toy { public String toString() { return "Toy" ;}} + +interface Eatable {} + +class FruitBoxEx2 { + public static void main(String[] args) { + FruitBox fruitBox = new FruitBox(); + FruitBox appleBox = new FruitBox(); + FruitBox grapeBox = new FruitBox(); +// FruitBox grapeBox = new FruitBox(); // ¿¡·¯. ŸÀÔ ºÒÀÏÄ¡ +// FruitBox toyBox = new FruitBox(); // ¿¡·¯. + + fruitBox.add(new Fruit()); + fruitBox.add(new Apple()); + fruitBox.add(new Grape()); + appleBox.add(new Apple()); +// appleBox.add(new Grape()); // ¿¡·¯. Grape´Â AppleÀÇ ÀÚ¼ÕÀÌ ¾Æ´Ô + grapeBox.add(new Grape()); + + System.out.println("fruitBox-"+fruitBox); + System.out.println("appleBox-"+appleBox); + System.out.println("grapeBox-"+grapeBox); + } // main +} + +class FruitBox extends Box {} + +class Box { + ArrayList list = new ArrayList(); + void add(T item) { list.add(item); } + T get(int i) { return list.get(i); } + int size() { return list.size(); } + public String toString() { return list.toString();} +} diff --git a/source/ch12/FruitBoxEx3.java b/source/ch12/FruitBoxEx3.java new file mode 100644 index 0000000..c939b73 --- /dev/null +++ b/source/ch12/FruitBoxEx3.java @@ -0,0 +1,49 @@ +import java.util.ArrayList; + +class Fruit { public String toString() { return "Fruit";}} +class Apple extends Fruit { public String toString() { return "Apple";}} +class Grape extends Fruit { public String toString() { return "Grape";}} + +class Juice { + String name; + + Juice(String name) { this.name = name + "Juice"; } + public String toString() { return name; } +} + +class Juicer { + static Juice makeJuice(FruitBox box) { + String tmp = ""; + + for(Fruit f : box.getList()) + tmp += f + " "; + return new Juice(tmp); + } +} + +class FruitBoxEx3 { + public static void main(String[] args) { + FruitBox fruitBox = new FruitBox(); + FruitBox appleBox = new FruitBox(); + + fruitBox.add(new Apple()); + fruitBox.add(new Grape()); + appleBox.add(new Apple()); + appleBox.add(new Apple()); + + System.out.println(Juicer.makeJuice(fruitBox)); + System.out.println(Juicer.makeJuice(appleBox)); + } // main +} + +class FruitBox extends Box {} + +class Box { +//class FruitBox { + ArrayList list = new ArrayList(); + void add(T item) { list.add(item); } + T get(int i) { return list.get(i); } + ArrayList getList() { return list; } + int size() { return list.size(); } + public String toString() { return list.toString();} +} diff --git a/source/ch12/FruitBoxEx4.java b/source/ch12/FruitBoxEx4.java new file mode 100644 index 0000000..b6852f9 --- /dev/null +++ b/source/ch12/FruitBoxEx4.java @@ -0,0 +1,93 @@ +import java.util.*; + +class Fruit { + String name; + int weight; + + Fruit(String name, int weight) { + this.name = name; + this.weight = weight; + } + + public String toString() { return name+"("+weight+")";} + +} + +class Apple extends Fruit { + Apple(String name, int weight) { + super(name, weight); + } +} + +class Grape extends Fruit { + Grape(String name, int weight) { + super(name, weight); + } +} + +class AppleComp implements Comparator { + public int compare(Apple t1, Apple t2) { + return t2.weight - t1.weight; + } +} + +class GrapeComp implements Comparator { + public int compare(Grape t1, Grape t2) { + return t2.weight - t1.weight; + } +} + +class FruitComp implements Comparator { + public int compare(Fruit t1, Fruit t2) { + return t1.weight - t2.weight; + } +} + +class FruitBoxEx4 { + public static void main(String[] args) { + FruitBox appleBox = new FruitBox(); + FruitBox grapeBox = new FruitBox(); + + appleBox.add(new Apple("GreenApple", 300)); + appleBox.add(new Apple("GreenApple", 100)); + appleBox.add(new Apple("GreenApple", 200)); + + grapeBox.add(new Grape("GreenGrape", 400)); + grapeBox.add(new Grape("GreenGrape", 300)); + grapeBox.add(new Grape("GreenGrape", 200)); + + Collections.sort(appleBox.getList(), new AppleComp()); + Collections.sort(grapeBox.getList(), new GrapeComp()); + System.out.println(appleBox); + System.out.println(grapeBox); + System.out.println(); + Collections.sort(appleBox.getList(), new FruitComp()); + Collections.sort(grapeBox.getList(), new FruitComp()); + System.out.println(appleBox); + System.out.println(grapeBox); + } // main +} + +class FruitBox extends Box {} + +class Box { + ArrayList list = new ArrayList(); + + void add(T item) { + list.add(item); + } + + T get(int i) { + return list.get(i); + } + + ArrayList getList() { return list; } + + int size() { + return list.size(); + } + + public String toString() { + return list.toString(); + } +} diff --git a/source/ch13/ForkJoinEx1.java b/source/ch13/ForkJoinEx1.java new file mode 100644 index 0000000..12f47f2 --- /dev/null +++ b/source/ch13/ForkJoinEx1.java @@ -0,0 +1,63 @@ +import java.util.concurrent.*; + +class ForkJoinEx1 { + static final ForkJoinPool pool = new ForkJoinPool(); // ¾²·¹µåÇ®À» »ý¼º + + public static void main(String[] args) { + long from = 1L; + long to = 100_000_000L; + + SumTask task = new SumTask(from, to); + + long start = System.currentTimeMillis(); // ½ÃÀ۽ð£ ÃʱâÈ­ + Long result = pool.invoke(task); + + System.out.println("Elapsed time(4 Core):"+(System.currentTimeMillis()-start)); + System.out.printf("sum of %d~%d=%d%n", from, to, result); + System.out.println(); + + result = 0L; + start = System.currentTimeMillis(); // ½ÃÀ۽ð£ ÃʱâÈ­ + for(long i=from;i<=to;i++) + result += i; + + System.out.println("Elapsed time(1 Core):"+(System.currentTimeMillis()-start)); + System.out.printf("sum of %d~%d=%d%n", from, to, result); + } // mainÀÇ ³¡ +} + +class SumTask extends RecursiveTask { + long from; + long to; + + SumTask(long from, long to) { + this.from = from; + this.to = to; + } + + public Long compute() { + long size = to - from; + + if(size <= 5) // ´õÇÒ ¼ýÀÚ°¡ 5°³ ÀÌÇϸé + return sum(); // ¼ýÀÚÀÇ ÇÕÀ» ¹Ýȯ + + long half = (from+to)/2; + + // ¹üÀ§¸¦ ¹ÝÀ¸·Î ³ª´²¼­ µÎ °³ÀÇ ÀÛ¾÷À» »ý¼º + SumTask leftSum = new SumTask(from, half); + SumTask rightSum = new SumTask(half+1, to); + + leftSum.fork(); + + return rightSum.compute() + leftSum.join(); + } + + long sum() { // from~toÀÇ ¸ðµç ¼ýÀÚ¸¦ ´õÇÑ °á°ú¸¦ ¹Ýȯ + long tmp = 0L; + + for(long i=from;i<=to;i++) + tmp += i; + + return tmp; + } +} diff --git a/source/ch13/ThreadEx1.java b/source/ch13/ThreadEx1.java new file mode 100644 index 0000000..6d9704f --- /dev/null +++ b/source/ch13/ThreadEx1.java @@ -0,0 +1,28 @@ +class ThreadEx1 { + public static void main(String args[]) { + ThreadEx1_1 t1 = new ThreadEx1_1(); + + Runnable r = new ThreadEx1_2(); + Thread t2 = new Thread(r); // »ý¼ºÀÚ Thread(Runnable target) + + t1.start(); + t2.start(); + } +} + +class ThreadEx1_1 extends Thread { + public void run() { + for(int i=0; i < 5; i++) { + System.out.println(getName()); // Á¶»óÀÎ ThreadÀÇ getName()À» È£Ãâ + } + } +} + +class ThreadEx1_2 implements Runnable { + public void run() { + for(int i=0; i < 5; i++) { + // Thread.currentThread() - ÇöÀç ½ÇÇàÁßÀÎ Thread¸¦ ¹ÝȯÇÑ´Ù. + System.out.println(Thread.currentThread().getName()); + } + } +} diff --git a/source/ch13/ThreadEx10.java b/source/ch13/ThreadEx10.java new file mode 100644 index 0000000..5add959 --- /dev/null +++ b/source/ch13/ThreadEx10.java @@ -0,0 +1,38 @@ + class ThreadEx10 implements Runnable { + static boolean autoSave = false; + + public static void main(String[] args) { + Thread t = new Thread(new ThreadEx10()); + t.setDaemon(true); // ÀÌ ºÎºÐÀÌ ¾øÀ¸¸é Á¾·áµÇÁö ¾Ê´Â´Ù. + t.start(); + + for(int i=1; i <= 10; i++) { + try{ + Thread.sleep(1000); + } catch(InterruptedException e) {} + System.out.println(i); + + if(i==5) + autoSave = true; + } + + System.out.println("ÇÁ·Î±×·¥À» Á¾·áÇÕ´Ï´Ù."); + } + + public void run() { + while(true) { + try { + Thread.sleep(3 * 1000); // 3Ãʸ¶´Ù + } catch(InterruptedException e) {} + + // autoSaveÀÇ °ªÀÌ trueÀ̸é autoSave()¸¦ È£ÃâÇÑ´Ù. + if(autoSave) { + autoSave(); + } + } + } + + public void autoSave() { + System.out.println("ÀÛ¾÷ÆÄÀÏÀÌ ÀÚµ¿ÀúÀåµÇ¾ú½À´Ï´Ù."); + } +} diff --git a/source/ch13/ThreadEx11.java b/source/ch13/ThreadEx11.java new file mode 100644 index 0000000..b8930c5 --- /dev/null +++ b/source/ch13/ThreadEx11.java @@ -0,0 +1,50 @@ + import java.util.*; + +class ThreadEx11 { + public static void main(String args[]) throws Exception { + ThreadEx11_1 t1 = new ThreadEx11_1("Thread1"); + ThreadEx11_2 t2 = new ThreadEx11_2("Thread2"); + t1.start(); + t2.start(); + } +} + +class ThreadEx11_1 extends Thread { + ThreadEx11_1(String name) { + super(name); + } + + public void run() { + try { + sleep(5 * 1000); // 5ÃÊ µ¿¾È ±â´Ù¸°´Ù. + } catch(InterruptedException e) {} + } +} + +class ThreadEx11_2 extends Thread { + ThreadEx11_2(String name) { + super(name); + } + + public void run() { + Map map = getAllStackTraces(); + Iterator it = map.keySet().iterator(); + + int x=0; + while(it.hasNext()) { + Object obj = it.next(); + Thread t = (Thread)obj; + StackTraceElement[] ste = (StackTraceElement[])(map.get(obj)); + + System.out.println( "["+ ++x + "] name : " + t.getName() + + ", group : " + t.getThreadGroup().getName() + + ", daemon : " + t.isDaemon()); + + for(int i=0; i < ste.length; i++) { + System.out.println(ste[i]); + } + + System.out.println(); + } + } +} diff --git a/source/ch13/ThreadEx12.java b/source/ch13/ThreadEx12.java new file mode 100644 index 0000000..859a84a --- /dev/null +++ b/source/ch13/ThreadEx12.java @@ -0,0 +1,33 @@ + class ThreadEx12 { + public static void main(String args[]) { + ThreadEx12_1 th1 = new ThreadEx12_1(); + ThreadEx12_2 th2 = new ThreadEx12_2(); + + th1.start(); + th2.start(); + + try { + th1.sleep(2000); + } catch(InterruptedException e) {} + + System.out.print("<
>"); + } // main +} + +class ThreadEx12_1 extends Thread { + public void run() { + for(int i=0; i < 300; i++) { + System.out.print("-"); + } + System.out.print("<>"); + } // run() +} + +class ThreadEx12_2 extends Thread { + public void run() { + for(int i=0; i < 300; i++) { + System.out.print("|"); + } + System.out.print("<>"); + } // run() +} diff --git a/source/ch13/ThreadEx13.java b/source/ch13/ThreadEx13.java new file mode 100644 index 0000000..2e8bad1 --- /dev/null +++ b/source/ch13/ThreadEx13.java @@ -0,0 +1,26 @@ +import javax.swing.JOptionPane; + +class ThreadEx13_1 { + public static void main(String[] args) throws Exception { + ThreadEx13_2 th1 = new ThreadEx13_2(); + th1.start(); + + String input = JOptionPane.showInputDialog("¾Æ¹« °ªÀ̳ª ÀÔ·ÂÇϼ¼¿ä."); + System.out.println("ÀÔ·ÂÇϽŠ°ªÀº " + input + "ÀÔ´Ï´Ù."); + th1.interrupt(); // interrupt()¸¦ È£ÃâÇϸé, interrupted»óÅ°¡ true°¡ µÈ´Ù. + System.out.println("isInterrupted():"+ th1.isInterrupted()); // true + } +} + +class ThreadEx13_2 extends Thread { + public void run() { + int i = 10; + + while(i!=0 && !isInterrupted()) { + System.out.println(i--); + for(long x=0;x<2500000000L;x++); // ½Ã°£ Áö¿¬ + } + + System.out.println("Ä«¿îÆ®°¡ Á¾·áµÇ¾ú½À´Ï´Ù."); + } // main +} diff --git a/source/ch13/ThreadEx14.java b/source/ch13/ThreadEx14.java new file mode 100644 index 0000000..be64900 --- /dev/null +++ b/source/ch13/ThreadEx14.java @@ -0,0 +1,29 @@ +import javax.swing.JOptionPane; + +class ThreadEx14_1 { + public static void main(String[] args) throws Exception { + ThreadEx14_2 th1 = new ThreadEx14_2(); + th1.start(); + + String input = JOptionPane.showInputDialog("¾Æ¹« °ªÀ̳ª ÀÔ·ÂÇϼ¼¿ä."); + System.out.println("ÀÔ·ÂÇϽŠ°ªÀº " + input + "ÀÔ´Ï´Ù."); + th1.interrupt(); // interrupt()¸¦ È£ÃâÇϸé, interrupted»óÅ°¡ true°¡ µÈ´Ù. + System.out.println("isInterrupted():"+ th1.isInterrupted()); + } +} + +class ThreadEx14_2 extends Thread { + public void run() { + int i = 10; + + while(i!=0 && !isInterrupted()) { + System.out.println(i--); + + try { + Thread.sleep(1000); // 1ÃÊ Áö¿¬ + } catch(InterruptedException e) {} + } + + System.out.println("Ä«¿îÆ®°¡ Á¾·áµÇ¾ú½À´Ï´Ù."); + } // main +} diff --git a/source/ch13/ThreadEx15.java b/source/ch13/ThreadEx15.java new file mode 100644 index 0000000..56ad652 --- /dev/null +++ b/source/ch13/ThreadEx15.java @@ -0,0 +1,37 @@ + class ThreadEx15 { + public static void main(String args[]) { + RunImplEx15 r = new RunImplEx15(); + Thread th1 = new Thread(r, "*"); + Thread th2 = new Thread(r, "**"); + Thread th3 = new Thread(r, "***"); + + th1.start(); + th2.start(); + th3.start(); + + try { + Thread.sleep(2000); + th1.suspend(); // ¾²·¹µå th1À» Àá½Ã ÁߴܽÃŲ´Ù. + Thread.sleep(2000); + th2.suspend(); + Thread.sleep(3000); + th1.resume(); // ¾²·¹µå th1ÀÌ ´Ù½Ã µ¿ÀÛÇϵµ·Ï ÇÑ´Ù. + Thread.sleep(3000); + th1.stop(); // ¾²·¹µå th1À» °­Á¦Á¾·á½ÃŲ´Ù. + th2.stop(); + Thread.sleep(2000); + th3.stop(); + } catch (InterruptedException e) {} + } // main +} + +class RunImplEx15 implements Runnable { + public void run() { + while(true) { + System.out.println(Thread.currentThread().getName()); + try { + Thread.sleep(1000); + } catch(InterruptedException e) {} + } + } // run() +} diff --git a/source/ch13/ThreadEx16.java b/source/ch13/ThreadEx16.java new file mode 100644 index 0000000..acc3788 --- /dev/null +++ b/source/ch13/ThreadEx16.java @@ -0,0 +1,49 @@ + class ThreadEx16 { + public static void main(String args[]) { + RunImplEx16 r1 = new RunImplEx16(); + RunImplEx16 r2 = new RunImplEx16(); + RunImplEx16 r3 = new RunImplEx16(); + Thread th1 = new Thread(r1, "*"); + Thread th2 = new Thread(r2, "**"); + Thread th3 = new Thread(r3, "***"); + + th1.start(); + th2.start(); + th3.start(); + + try { + Thread.sleep(2000); + r1.suspend(); // th1.suspend()ÀÌ ¾Æ´Ô¿¡ ÁÖÀÇ + Thread.sleep(2000); + r2.suspend(); + Thread.sleep(3000); + r1.resume(); + Thread.sleep(3000); + r1.stop(); + r2.stop(); + Thread.sleep(2000); + r3.stop(); + } catch (InterruptedException e) {} + } +} + +class RunImplEx16 implements Runnable { + boolean suspended = false; + boolean stopped = false; + + public void run() { + while(!stopped) { + if(!suspended) { + System.out.println(Thread.currentThread().getName()); + try { + Thread.sleep(1000); + } catch(InterruptedException e) {} + } + } + System.out.println(Thread.currentThread().getName() + " - stopped"); + } + + public void suspend() { suspended = true; } + public void resume() { suspended = false; } + public void stop() { stopped = true; } +} diff --git a/source/ch13/ThreadEx17.java b/source/ch13/ThreadEx17.java new file mode 100644 index 0000000..09335b8 --- /dev/null +++ b/source/ch13/ThreadEx17.java @@ -0,0 +1,52 @@ + class ThreadEx17 { + public static void main(String args[]) { + ThreadEx17_1 th1 = new ThreadEx17_1("*"); + ThreadEx17_1 th2 = new ThreadEx17_1("**"); + ThreadEx17_1 th3 = new ThreadEx17_1("***"); + th1.start(); + th2.start(); + th3.start(); + + try { + Thread.sleep(2000); + th1.suspend(); + Thread.sleep(2000); + th2.suspend(); + Thread.sleep(3000); + th1.resume(); + Thread.sleep(3000); + th1.stop(); + th2.stop(); + Thread.sleep(2000); + th3.stop(); + } catch (InterruptedException e) {} + } +} + +class ThreadEx17_1 implements Runnable { + boolean suspended = false; + boolean stopped = false; + + Thread th; + + ThreadEx17_1(String name) { + th = new Thread(this, name); // Thread(Runnable r, String name) + } + + public void run() { + while(!stopped) { + if(!suspended) { + System.out.println(Thread.currentThread().getName()); + try { + Thread.sleep(1000); + } catch(InterruptedException e) {} + } + } + System.out.println(Thread.currentThread().getName() + " - stopped"); + } + + public void suspend() { suspended = true; } + public void resume() { suspended = false; } + public void stop() { stopped = true; } + public void start() { th.start(); } +} diff --git a/source/ch13/ThreadEx18.java b/source/ch13/ThreadEx18.java new file mode 100644 index 0000000..4569bfc --- /dev/null +++ b/source/ch13/ThreadEx18.java @@ -0,0 +1,73 @@ +class ThreadEx18 { + public static void main(String args[]) { + ThreadEx18_1 th1 = new ThreadEx18_1("*"); + ThreadEx18_1 th2 = new ThreadEx18_1("**"); + ThreadEx18_1 th3 = new ThreadEx18_1("***"); + th1.start(); + th2.start(); + th3.start(); + + try { + Thread.sleep(2000); + th1.suspend(); + Thread.sleep(2000); + th2.suspend(); + Thread.sleep(3000); + th1.resume(); + Thread.sleep(3000); + th1.stop(); + th2.stop(); + Thread.sleep(2000); + th3.stop(); + } catch (InterruptedException e) {} + } +} + +class ThreadEx18_1 implements Runnable { + boolean suspended = false; + boolean stopped = false; + + Thread th; + + ThreadEx18_1(String name) { + th = new Thread(this, name); // Thread(Runnable r, String name) + } + + public void run() { + String name =th.getName(); + + while(!stopped) { + if(!suspended) { + System.out.println(name); + try { + Thread.sleep(1000); + } catch(InterruptedException e) { + System.out.println(name + " - interrupted"); + } + } else { + Thread.yield(); + } + } + System.out.println(name + " - stopped"); + } + + public void suspend() { + suspended = true; + th.interrupt(); + System.out.println(th.getName() + " - interrupt() by suspend()"); + } + + public void resume() { + suspended = false; + } + + public void stop() { + stopped = true; + th.interrupt(); + System.out.println(th.getName() + " - interrupt() by stop()"); + } + + public void start() { + th.start(); + } +} diff --git a/source/ch13/ThreadEx19.java b/source/ch13/ThreadEx19.java new file mode 100644 index 0000000..40bc617 --- /dev/null +++ b/source/ch13/ThreadEx19.java @@ -0,0 +1,35 @@ + class ThreadEx19 { + static long startTime = 0; + + public static void main(String args[]) { + ThreadEx19_1 th1 = new ThreadEx19_1(); + ThreadEx19_2 th2 = new ThreadEx19_2(); + + th1.start(); + th2.start(); + startTime = System.currentTimeMillis(); + + try { + th1.join(); // main¾²·¹µå°¡ th1ÀÇ ÀÛ¾÷ÀÌ ³¡³¯ ¶§±îÁö ±â´Ù¸°´Ù. + th2.join(); // main¾²·¹µå°¡ th2ÀÇ ÀÛ¾÷ÀÌ ³¡³¯ ¶§±îÁö ±â´Ù¸°´Ù. + } catch(InterruptedException e) {} + + System.out.print("¼Ò¿ä½Ã°£:" + (System.currentTimeMillis() - ThreadEx19.startTime)); + } // main +} + +class ThreadEx19_1 extends Thread { + public void run() { + for(int i=0; i < 300; i++) { + System.out.print(new String("-")); + } + } // run() +} + +class ThreadEx19_2 extends Thread { + public void run() { + for(int i=0; i < 300; i++) { + System.out.print(new String("|")); + } + } // run() +} diff --git a/source/ch13/ThreadEx2.java b/source/ch13/ThreadEx2.java new file mode 100644 index 0000000..01a4597 --- /dev/null +++ b/source/ch13/ThreadEx2.java @@ -0,0 +1,20 @@ + class ThreadEx2 { + public static void main(String args[]) throws Exception { + ThreadEx2_1 t1 = new ThreadEx2_1(); + t1.start(); + } +} + +class ThreadEx2_1 extends Thread { + public void run() { + throwException(); + } + + public void throwException() { + try { + throw new Exception(); + } catch(Exception e) { + e.printStackTrace(); + } + } +} diff --git a/source/ch13/ThreadEx20.java b/source/ch13/ThreadEx20.java new file mode 100644 index 0000000..2c75ea5 --- /dev/null +++ b/source/ch13/ThreadEx20.java @@ -0,0 +1,53 @@ +class ThreadEx20 { + public static void main(String args[]) { + ThreadEx20_1 gc = new ThreadEx20_1(); + gc.setDaemon(true); + gc.start(); + + int requiredMemory = 0; + + for(int i=0; i < 20; i++) { + requiredMemory = (int)(Math.random() * 10) * 20; + + // ÇÊ¿äÇÑ ¸Þ¸ð¸®°¡ »ç¿ëÇÒ ¼ö ÀÖ´Â ¾çº¸´Ù Å©°Å³ª Àüü ¸Þ¸ð¸®ÀÇ 60%ÀÌ»óÀ» + // »ç¿ëÇßÀ» °æ¿ì gc¸¦ ±ú¿î´Ù. + if(gc.freeMemory() < requiredMemory || gc.freeMemory() < gc.totalMemory() * 0.4) { + gc.interrupt(); // ÀáÀÚ°í ÀÖ´Â ¾²·¹µå t1À» ±ú¿î´Ù. + } + + gc.usedMemory += requiredMemory; + System.out.println("usedMemory:"+gc.usedMemory); + } + } +} + +class ThreadEx20_1 extends Thread { + final static int MAX_MEMORY = 1000; + int usedMemory = 0; + + public void run() { + while(true) { + try { + Thread.sleep(10 * 1000); // 10Ãʸ¦ ±â´Ù¸°´Ù. + } catch(InterruptedException e) { + System.out.println("Awaken by interrupt()."); + } + + gc(); // garbage collectionÀ» ¼öÇàÇÑ´Ù. + System.out.println("Garbage Collected. Free Memory :" + freeMemory()); + } + } + + public void gc() { + usedMemory -= 300; + if(usedMemory < 0) usedMemory = 0; + } + + public int totalMemory() { + return MAX_MEMORY; + } + + public int freeMemory() { + return MAX_MEMORY - usedMemory; + } +} diff --git a/source/ch13/ThreadEx21.java b/source/ch13/ThreadEx21.java new file mode 100644 index 0000000..98e58a1 --- /dev/null +++ b/source/ch13/ThreadEx21.java @@ -0,0 +1,35 @@ +class ThreadEx21 { + public static void main(String args[]) { + Runnable r = new RunnableEx21(); + new Thread(r).start(); // ThreadGroup¿¡ ÀÇÇØ ÂüÁ¶µÇ¹Ç·Î gc´ë»óÀÌ ¾Æ´Ï´Ù. + new Thread(r).start(); // ThreadGroup¿¡ ÀÇÇØ ÂüÁ¶µÇ¹Ç·Î gc´ë»óÀÌ ¾Æ´Ï´Ù. + } +} + +class Account { + private int balance = 1000; + + public int getBalance() { + return balance; + } + + public void withdraw(int money){ + if(balance >= money) { + try { Thread.sleep(1000);} catch(InterruptedException e) {} + balance -= money; + } + } // withdraw +} + +class RunnableEx21 implements Runnable { + Account acc = new Account(); + + public void run() { + while(acc.getBalance() > 0) { + // 100, 200, 300ÁßÀÇ ÇÑ °ªÀ» ÀÓÀ¸·Î ¼±ÅÃÇؼ­ Ãâ±Ý(withdraw) + int money = (int)(Math.random() * 3 + 1) * 100; + acc.withdraw(money); + System.out.println("balance:"+acc.getBalance()); + } + } // run() +} diff --git a/source/ch13/ThreadEx22.java b/source/ch13/ThreadEx22.java new file mode 100644 index 0000000..b9e1aca --- /dev/null +++ b/source/ch13/ThreadEx22.java @@ -0,0 +1,35 @@ +class ThreadEx22 { + public static void main(String args[]) { + Runnable r = new RunnableEx22(); + new Thread(r).start(); + new Thread(r).start(); + } +} + +class Account { + private int balance = 1000; // privateÀ¸·Î ÇØ¾ß µ¿±âÈ­°¡ Àǹ̰¡ ÀÖ´Ù. + + public int getBalance() { + return balance; + } + + public synchronized void withdraw(int money){ // synchronized·Î ¸Þ¼­µå¸¦ µ¿±âÈ­ + if(balance >= money) { + try { Thread.sleep(1000);} catch(InterruptedException e) {} + balance -= money; + } + } // withdraw +} + +class RunnableEx22 implements Runnable { + Account acc = new Account(); + + public void run() { + while(acc.getBalance() > 0) { + // 100, 200, 300ÁßÀÇ ÇÑ °ªÀ» ÀÓÀ¸·Î ¼±ÅÃÇؼ­ Ãâ±Ý(withdraw) + int money = (int)(Math.random() * 3 + 1) * 100; + acc.withdraw(money); + System.out.println("balance:"+acc.getBalance()); + } + } // run() +} diff --git a/source/ch13/ThreadEx3.java b/source/ch13/ThreadEx3.java new file mode 100644 index 0000000..f809cea --- /dev/null +++ b/source/ch13/ThreadEx3.java @@ -0,0 +1,20 @@ +class ThreadEx3 { + public static void main(String args[]) throws Exception { + ThreadEx3_1 t1 = new ThreadEx3_1(); + t1.run(); + } +} + +class ThreadEx3_1 extends Thread { + public void run() { + throwException(); + } + + public void throwException() { + try { + throw new Exception(); + } catch(Exception e) { + e.printStackTrace(); + } + } +} diff --git a/source/ch13/ThreadEx4.java b/source/ch13/ThreadEx4.java new file mode 100644 index 0000000..8987c6e --- /dev/null +++ b/source/ch13/ThreadEx4.java @@ -0,0 +1,15 @@ + class ThreadEx4 { + public static void main(String args[]) { + long startTime = System.currentTimeMillis(); + + for(int i=0; i < 500; i++) + System.out.printf("%s", new String("-")); + + System.out.print("¼Ò¿ä½Ã°£1:" +(System.currentTimeMillis()- startTime)); + + for(int i=0; i < 500; i++) + System.out.printf("%s", new String("|")); + + System.out.print("¼Ò¿ä½Ã°£2:"+(System.currentTimeMillis() - startTime)); + } +} diff --git a/source/ch13/ThreadEx5.java b/source/ch13/ThreadEx5.java new file mode 100644 index 0000000..7159979 --- /dev/null +++ b/source/ch13/ThreadEx5.java @@ -0,0 +1,25 @@ + class ThreadEx5 { + static long startTime = 0; + + public static void main(String args[]) { + ThreadEx5_1 th1 = new ThreadEx5_1(); + th1.start(); + startTime = System.currentTimeMillis(); + + for(int i=0; i < 300; i++) { + System.out.print("-"); + } + + System.out.print("¼Ò¿ä½Ã°£1:" + (System.currentTimeMillis() - ThreadEx5.startTime)); + } +} + +class ThreadEx5_1 extends Thread { + public void run() { + for(int i=0; i < 300; i++) { + System.out.print("|"); + } + + System.out.print("¼Ò¿ä½Ã°£2:" + (System.currentTimeMillis() - ThreadEx5.startTime)); + } +} diff --git a/source/ch13/ThreadEx6.java b/source/ch13/ThreadEx6.java new file mode 100644 index 0000000..4078297 --- /dev/null +++ b/source/ch13/ThreadEx6.java @@ -0,0 +1,16 @@ +import javax.swing.JOptionPane; + +class ThreadEx6 { + public static void main(String[] args) throws Exception + { + String input = JOptionPane.showInputDialog("¾Æ¹« °ªÀ̳ª ÀÔ·ÂÇϼ¼¿ä."); + System.out.println("ÀÔ·ÂÇϽŠ°ªÀº " + input + "ÀÔ´Ï´Ù."); + + for(int i=10; i > 0; i--) { + System.out.println(i); + try { + Thread.sleep(1000); + } catch(Exception e ) {} + } + } +} diff --git a/source/ch13/ThreadEx7.java b/source/ch13/ThreadEx7.java new file mode 100644 index 0000000..c69c815 --- /dev/null +++ b/source/ch13/ThreadEx7.java @@ -0,0 +1,22 @@ +import javax.swing.JOptionPane; + +class ThreadEx7 { + public static void main(String[] args) throws Exception { + ThreadEx7_1 th1 = new ThreadEx7_1(); + th1.start(); + + String input = JOptionPane.showInputDialog("¾Æ¹« °ªÀ̳ª ÀÔ·ÂÇϼ¼¿ä."); + System.out.println("ÀÔ·ÂÇϽŠ°ªÀº " + input + "ÀÔ´Ï´Ù."); + } +} + +class ThreadEx7_1 extends Thread { + public void run() { + for(int i=10; i > 0; i--) { + System.out.println(i); + try { + sleep(1000); + } catch(Exception e ) {} + } + } +} diff --git a/source/ch13/ThreadEx8.java b/source/ch13/ThreadEx8.java new file mode 100644 index 0000000..1e6946c --- /dev/null +++ b/source/ch13/ThreadEx8.java @@ -0,0 +1,31 @@ +class ThreadEx8 { + public static void main(String args[]) { + ThreadEx8_1 th1 = new ThreadEx8_1(); + ThreadEx8_2 th2 = new ThreadEx8_2(); + + th2.setPriority(7); + + System.out.println("Priority of th1(-) : " + th1.getPriority() ); + System.out.println("Priority of th2(|) : " + th2.getPriority() ); + th1.start(); + th2.start(); + } +} + +class ThreadEx8_1 extends Thread { + public void run() { + for(int i=0; i < 300; i++) { + System.out.print("-"); + for(int x=0; x < 10000000; x++); + } + } +} + +class ThreadEx8_2 extends Thread { + public void run() { + for(int i=0; i < 300; i++) { + System.out.print("|"); + for(int x=0; x < 10000000; x++); + } + } +} diff --git a/source/ch13/ThreadEx9.java b/source/ch13/ThreadEx9.java new file mode 100644 index 0000000..67797df --- /dev/null +++ b/source/ch13/ThreadEx9.java @@ -0,0 +1,34 @@ + class ThreadEx9 { + public static void main(String args[]) throws Exception { + ThreadGroup main = Thread.currentThread().getThreadGroup(); + ThreadGroup grp1 = new ThreadGroup("Group1"); + ThreadGroup grp2 = new ThreadGroup("Group2"); + + // ThreadGroup(ThreadGroup parent, String name) + ThreadGroup subGrp1 = new ThreadGroup(grp1,"SubGroup1"); + + grp1.setMaxPriority(3); // ¾²·¹µå ±×·ì grp1ÀÇ ÃÖ´ë¿ì¼±¼øÀ§¸¦ 3À¸·Î º¯°æ. + + Runnable r = new Runnable() { + public void run() { + try { + Thread.sleep(1000); // ¾²·¹µå¸¦ 1ÃÊ°£ ¸ØÃß°Ô ÇÑ´Ù. + } catch(InterruptedException e) {} + } + }; + + // Thread(ThreadGroup tg, Runnable r, String name) + Thread th1 = new Thread(grp1, r, "th1"); + Thread th2 = new Thread(subGrp1, r, "th2"); + Thread th3 = new Thread(grp2, r, "th3"); + + th1.start(); + th2.start(); + th3.start(); + + System.out.println(">>List of ThreadGroup : "+ main.getName() + +", Active ThreadGroup: " + main.activeGroupCount() + +", Active Thread: " + main.activeCount()); + main.list(); + } +} diff --git a/source/ch13/ThreadWaitEx1.java b/source/ch13/ThreadWaitEx1.java new file mode 100644 index 0000000..8f8d777 --- /dev/null +++ b/source/ch13/ThreadWaitEx1.java @@ -0,0 +1,83 @@ +import java.util.ArrayList; + +class ThreadWaitEx1 { + public static void main(String[] args) throws Exception { + Table table = new Table(); // ¿©·¯ ¾²·¹µå°¡ °øÀ¯ÇÏ´Â °´Ã¼ + + new Thread(new Cook(table), "COOK1").start(); + new Thread(new Customer(table, "donut"), "CUST1").start(); + new Thread(new Customer(table, "burger"), "CUST2").start(); + + // 0.1ÃÊ(100 ¹Ð¸® ¼¼ÄÁµå) ÈÄ¿¡ °­Á¦ Á¾·á½ÃŲ´Ù. + Thread.sleep(100); + System.exit(0); + } +} + +class Customer implements Runnable { + private Table table; + private String food; + + Customer(Table table, String food) { + this.table = table; + this.food = food; + } + + public void run() { + while(true) { + try { Thread.sleep(10);} catch(InterruptedException e) {} + String name = Thread.currentThread().getName(); + + if(eatFood()) + System.out.println(name + " ate a " + food); + else + System.out.println(name + " failed to eat. :("); + } // while + } + + boolean eatFood() { return table.remove(food); } +} + +class Cook implements Runnable { + private Table table; + + Cook(Table table) { this.table = table; } + + public void run() { + while(true) { + // ÀÓÀÇÀÇ ¿ä¸®¸¦ Çϳª ¼±ÅÃÇؼ­ table¿¡ Ãß°¡ÇÑ´Ù. + int idx = (int)(Math.random()*table.dishNum()); + table.add(table.dishNames[idx]); + + try { Thread.sleep(1);} catch(InterruptedException e) {} + } // while + } +} + +class Table { + String[] dishNames = { "donut","donut","burger" }; // donutÀÌ ´õ ÀÚÁÖ ³ª¿Â´Ù. + final int MAX_FOOD = 6; // Å×ÀÌºí¿¡ ³õÀ» ¼ö ÀÖ´Â ÃÖ´ë À½½ÄÀÇ °³¼ö + +private ArrayList dishes = new ArrayList<>(); + + public void add(String dish) { + // Å×ÀÌºí¿¡ À½½ÄÀÌ °¡µæáÀ¸¸é, Å×ÀÌºí¿¡ À½½ÄÀ» Ãß°¡ÇÏÁö ¾Ê´Â´Ù. + if(dishes.size() >= MAX_FOOD) + return; + dishes.add(dish); + System.out.println("Dishes:" + dishes.toString()); + } + + public boolean remove(String dishName) { + // ÁöÁ¤µÈ ¿ä¸®¿Í ÀÏÄ¡ÇÏ´Â ¿ä¸®¸¦ Å×ÀÌºí¿¡¼­ Á¦°ÅÇÑ´Ù. + for(int i=0; i dishes = new ArrayList<>(); + + public synchronized void add(String dish) { // synchronized¸¦ Ãß°¡ + if(dishes.size() >= MAX_FOOD) + return; + dishes.add(dish); + System.out.println("Dishes:" + dishes.toString()); + } + + public boolean remove(String dishName) { + synchronized(this) { + while(dishes.size()==0) { + String name = Thread.currentThread().getName(); + System.out.println(name+" is waiting."); + try { Thread.sleep(500);} catch(InterruptedException e) {} + } + + for(int i=0; i dishes = new ArrayList<>(); + + public synchronized void add(String dish) { + while(dishes.size() >= MAX_FOOD) { + String name = Thread.currentThread().getName(); + System.out.println(name+" is waiting."); + try { + wait(); // COOK¾²·¹µå¸¦ ±â´Ù¸®°Ô ÇÑ´Ù. + Thread.sleep(500); + } catch(InterruptedException e) {} + } + dishes.add(dish); + notify(); // ±â´Ù¸®°í ÀÖ´Â CUST¸¦ ±ú¿ì±â À§ÇÔ. + System.out.println("Dishes:" + dishes.toString()); + } + + public void remove(String dishName) { + + synchronized(this) { + String name = Thread.currentThread().getName(); + + while(dishes.size()==0) { + System.out.println(name+" is waiting."); + try { + wait(); // CUST¾²·¹µå¸¦ ±â´Ù¸®°Ô ÇÑ´Ù. + Thread.sleep(500); + } catch(InterruptedException e) {} + } + + while(true) { + for(int i=0; i dishes = new ArrayList<>(); + + private ReentrantLock lock = new ReentrantLock(); + private Condition forCook = lock.newCondition(); + private Condition forCust = lock.newCondition(); + + public void add(String dish) { + lock.lock(); + + try { + while(dishes.size() >= MAX_FOOD) { + String name = Thread.currentThread().getName(); + System.out.println(name+" is waiting."); + try { + forCook.await(); // wait(); COOK¾²·¹µå¸¦ ±â´Ù¸®°Ô ÇÑ´Ù. + Thread.sleep(500); + } catch(InterruptedException e) {} + } + + dishes.add(dish); + forCust.signal(); // notify(); ±â´Ù¸®°í ÀÖ´Â CUST¸¦ ±ú¿ì±â À§ÇÔ. + System.out.println("Dishes:" + dishes.toString()); + } finally { + lock.unlock(); + } + } + + public void remove(String dishName) { + lock.lock(); // synchronized(this) { + String name = Thread.currentThread().getName(); + + try { + while(dishes.size()==0) { + System.out.println(name+" is waiting."); + try { + forCust.await(); // wait(); CUST¾²·¹µå¸¦ ±â´Ù¸®°Ô ÇÑ´Ù. + Thread.sleep(500); + } catch(InterruptedException e) {} + } + + while(true) { + for(int i=0; i strStream = Stream.of(strArr); + + String result = strStream.collect(new ConcatCollector()); + + System.out.println(Arrays.toString(strArr)); + System.out.println("result="+result); + } +} + +class ConcatCollector implements Collector { + @Override + public Supplier supplier() { + return () -> new StringBuilder(); +// return StringBuilder::new; + } + + @Override + public BiConsumer accumulator() { + return (sb, s) -> sb.append(s); +// return StringBuilder::append; + } + + @Override + public Function finisher() { + return sb -> sb.toString(); +// return StringBuilder::toString; + } + + @Override + public BinaryOperator combiner() { + return (sb, sb2)-> { + sb.append(sb2); + return sb; + }; + } + + @Override + public Set characteristics() { + return Collections.emptySet(); + } +} diff --git a/source/ch14/LambdaEx1.java b/source/ch14/LambdaEx1.java new file mode 100644 index 0000000..26621f0 --- /dev/null +++ b/source/ch14/LambdaEx1.java @@ -0,0 +1,35 @@ +@FunctionalInterface +interface MyFunction { + void run(); // public abstract void run(); +} + +class LambdaEx1 { + static void execute(MyFunction f) { // ¸Å°³º¯¼öÀÇ Å¸ÀÔÀÌ MyFunctionÀÎ ¸Þ¼­µå + f.run(); + } + + static MyFunction getMyFunction() { // ¹Ýȯ ŸÀÔÀÌ MyFunctionÀÎ ¸Þ¼­µå + MyFunction f = () -> System.out.println("f3.run()"); + return f; + } + + public static void main(String[] args) { + // ¶÷´Ù½ÄÀ¸·Î MyFunctionÀÇ run()À» ±¸Çö + MyFunction f1 = ()-> System.out.println("f1.run()"); + + MyFunction f2 = new MyFunction() { // À͸íŬ·¡½º·Î run()À» ±¸Çö + public void run() { // publicÀ» ¹Ýµå½Ã ºÙ¿©¾ß ÇÔ + System.out.println("f2.run()"); + } + }; + + MyFunction f3 = getMyFunction(); + + f1.run(); + f2.run(); + f3.run(); + + execute(f1); + execute( ()-> System.out.println("run()") ); + } +} diff --git a/source/ch14/LambdaEx2.java b/source/ch14/LambdaEx2.java new file mode 100644 index 0000000..60f606b --- /dev/null +++ b/source/ch14/LambdaEx2.java @@ -0,0 +1,21 @@ +@FunctionalInterface +interface MyFunction { + void myMethod(); // public abstract void myMethod(); +} + +class LambdaEx2 { + public static void main(String[] args) { + MyFunction f = ()->{}; // MyFunction f = (MyFunction)(()->{}); + Object obj = (MyFunction)(()-> {}); // ObjectŸÀÔÀ¸·Î Çüº¯È¯ÀÌ »ý·«µÊ + String str = ((Object)(MyFunction)(()-> {})).toString(); + + System.out.println(f); + System.out.println(obj); + System.out.println(str); + +// System.out.println(()->{}); // ¿¡·¯. ¶÷´Ù½ÄÀº ObjectŸÀÔÀ¸·Î Çüº¯È¯ ¾ÈµÊ + System.out.println((MyFunction)(()-> {})); +// System.out.println((MyFunction)(()-> {}).toString()); // ¿¡·¯ + System.out.println(((Object)(MyFunction)(()-> {})).toString()); + } +} diff --git a/source/ch14/LambdaEx3.java b/source/ch14/LambdaEx3.java new file mode 100644 index 0000000..151278b --- /dev/null +++ b/source/ch14/LambdaEx3.java @@ -0,0 +1,34 @@ +@FunctionalInterface +interface MyFunction { + void myMethod(); +} + +class Outer { + int val=10; // Outer.this.val + + class Inner { + int val=20; // this.val + + void method(int i) { // void method(final int i) { + int val=30; // final int val=30; +// i = 10; // ¿¡·¯. »ó¼öÀÇ °ªÀ» º¯°æÇÒ ¼ö ¾øÀ½. + + MyFunction f = () -> { + System.out.println(" i :" + i); + System.out.println(" val :" + val); + System.out.println(" this.val :" + ++this.val); + System.out.println("Outer.this.val :" + ++Outer.this.val); + }; + + f.myMethod(); + } + } // InnerŬ·¡½ºÀÇ ³¡ +} // OuterŬ·¡½ºÀÇ ³¡ + +class LambdaEx3 { + public static void main(String args[]) { + Outer outer = new Outer(); + Outer.Inner inner = outer.new Inner(); + inner.method(100); + } +} diff --git a/source/ch14/LambdaEx4.java b/source/ch14/LambdaEx4.java new file mode 100644 index 0000000..a12d6d2 --- /dev/null +++ b/source/ch14/LambdaEx4.java @@ -0,0 +1,30 @@ +import java.util.*; + +class LambdaEx4 { + public static void main(String[] args) { + ArrayList list = new ArrayList<>(); + for(int i=0;i<10;i++) + list.add(i); + + // listÀÇ ¸ðµç ¿ä¼Ò¸¦ Ãâ·Â + list.forEach(i->System.out.print(i+",")); + System.out.println(); + + // list¿¡¼­ 2 ¶Ç´Â 3ÀÇ ¹è¼ö¸¦ Á¦°ÅÇÑ´Ù. + list.removeIf(x-> x%2==0 || x%3==0); + System.out.println(list); + + list.replaceAll(i->i*10); // listÀÇ °¢ ¿ä¼Ò¿¡ 10À» °öÇÑ´Ù. + System.out.println(list); + + Map map = new HashMap<>(); + map.put("1", "1"); + map.put("2", "2"); + map.put("3", "3"); + map.put("4", "4"); + + // mapÀÇ ¸ðµç ¿ä¼Ò¸¦ {k,v}ÀÇ Çü½ÄÀ¸·Î Ãâ·ÂÇÑ´Ù. + map.forEach((k,v)-> System.out.print("{"+k+","+v+"},")); + System.out.println(); + } +} diff --git a/source/ch14/LambdaEx5.java b/source/ch14/LambdaEx5.java new file mode 100644 index 0000000..e2a272d --- /dev/null +++ b/source/ch14/LambdaEx5.java @@ -0,0 +1,43 @@ +import java.util.function.*; +import java.util.*; + +class LambdaEx5 { + public static void main(String[] args) { + Supplier s = ()-> (int)(Math.random()*100)+1; + Consumer c = i -> System.out.print(i+", "); + Predicate p = i -> i%2==0; + Function f = i -> i/10*10; // iÀÇ ÀÏÀÇ ÀÚ¸®¸¦ ¾ø¾Ø´Ù. + + List list = new ArrayList<>(); + makeRandomList(s, list); + System.out.println(list); + printEvenNum(p, c, list); + List newList = doSomething(f, list); + System.out.println(newList); + } + + static List doSomething(Function f, List list) { + List newList = new ArrayList(list.size()); + + for(T i : list) { + newList.add(f.apply(i)); + } + + return newList; + } + + static void printEvenNum(Predicate p, Consumer c, List list) { + System.out.print("["); + for(T i : list) { + if(p.test(i)) + c.accept(i); + } + System.out.println("]"); + } + + static void makeRandomList(Supplier s, List list) { + for(int i=0;i<10;i++) { + list.add(s.get()); + } + } +} diff --git a/source/ch14/LambdaEx6.java b/source/ch14/LambdaEx6.java new file mode 100644 index 0000000..9d4c31d --- /dev/null +++ b/source/ch14/LambdaEx6.java @@ -0,0 +1,44 @@ +import java.util.function.*; +import java.util.*; + +class LambdaEx6 { + public static void main(String[] args) { + IntSupplier s = ()-> (int)(Math.random()*100)+1; + IntConsumer c = i -> System.out.print(i+", "); + IntPredicate p = i -> i%2==0; + IntUnaryOperator op = i -> i/10*10; // iÀÇ ÀÏÀÇ ÀÚ¸®¸¦ ¾ø¾Ø´Ù. + + int[] arr = new int[10]; + + makeRandomList(s, arr); + System.out.println(Arrays.toString(arr)); + printEvenNum(p, c, arr); + int[] newArr = doSomething(op, arr); + System.out.println(Arrays.toString(newArr)); + } + + static void makeRandomList(IntSupplier s, int[] arr) { + for(int i=0;i f = (s) -> Integer.parseInt(s, 16); + Function g = (i) -> Integer.toBinaryString(i); + + Function h = f.andThen(g); + Function h2 = f.compose(g); + + System.out.println(h.apply("FF")); // "FF" ¡æ 255 ¡æ "11111111" + System.out.println(h2.apply(2)); // 2 ¡æ "10" ¡æ 16 + + + Function f2 = x -> x; // Ç×µî ÇÔ¼ö(identity function) + System.out.println(f2.apply("AAA")); // AAA°¡ ±×´ë·Î Ãâ·ÂµÊ + + Predicate p = i -> i < 100; + Predicate q = i -> i < 200; + Predicate r = i -> i%2 == 0; + Predicate notP = p.negate(); // i >= 100 + + Predicate all = notP.and(q).or(r); + System.out.println(all.test(150)); // true + + String str1 = "abc"; + String str2 = "abc"; + + // str1°ú str2°¡ °°ÀºÁö ºñ±³ÇÑ °á°ú¸¦ ¹Ýȯ + Predicate p2 = Predicate.isEqual(str1); + boolean result = p2.test(str2); + System.out.println(result); + } +} diff --git a/source/ch14/OptionalEx1.java b/source/ch14/OptionalEx1.java new file mode 100644 index 0000000..5f85464 --- /dev/null +++ b/source/ch14/OptionalEx1.java @@ -0,0 +1,57 @@ +import java.util.*; +import java.util.stream.*; + +class OptionalEx1 { + public static void main(String[] args) { + Optional optStr = Optional.of("abcde"); + Optional optInt = optStr.map(String::length); + System.out.println("optStr="+optStr.get()); + System.out.println("optInt="+optInt.get()); + + int result1 = Optional.of("123") + .filter(x->x.length() >0) + .map(Integer::parseInt).get(); + + int result2 = Optional.of("") + .filter(x->x.length() >0) + .map(Integer::parseInt).orElse(-1); + + System.out.println("result1="+result1); + System.out.println("result2="+result2); + + Optional.of("456").map(Integer::parseInt) + .ifPresent(x->System.out.printf("result3=%d%n",x)); + + OptionalInt optInt1 = OptionalInt.of(0); // 0À» ÀúÀå + OptionalInt optInt2 = OptionalInt.empty(); // ºó °´Ã¼¸¦ »ý¼º + + System.out.println(optInt1.isPresent()); // true + System.out.println(optInt2.isPresent()); // false + + System.out.println(optInt1.getAsInt()); // 0 +// System.out.println(optInt2.getAsInt()); // NoSuchElementException + System.out.println("optInt1 ="+optInt1); + System.out.println("optInt2="+optInt2); + System.out.println("optInt1.equals(optInt2)?"+optInt1.equals(optInt2)); + + Optional opt = Optional.ofNullable(null); // nullÀ» ÀúÀå + Optional opt2 = Optional.empty(); // ºó °´Ã¼¸¦ »ý¼º + System.out.println("opt ="+opt); + System.out.println("opt2="+opt2); + System.out.println("opt.equals(opt2)?"+opt.equals(opt2)); // true + + int result3 = optStrToInt(Optional.of("123"), 0); + int result4 = optStrToInt(Optional.of(""), 0); + + System.out.println("result3="+result3); + System.out.println("result4="+result4); + } + + static int optStrToInt(Optional optStr, int defaultValue) { + try { + return optStr.map(Integer::parseInt).get(); + } catch (Exception e){ + return defaultValue; + } + } +} \ No newline at end of file diff --git a/source/ch14/StreamEx1.java b/source/ch14/StreamEx1.java new file mode 100644 index 0000000..f07bd91 --- /dev/null +++ b/source/ch14/StreamEx1.java @@ -0,0 +1,45 @@ +import java.util.*; +import java.util.stream.*; + +class StreamEx1 { + public static void main(String[] args) { + Stream studentStream = Stream.of( + new Student("ÀÌÀÚ¹Ù", 3, 300), + new Student("±èÀÚ¹Ù", 1, 200), + new Student("¾ÈÀÚ¹Ù", 2, 100), + new Student("¹ÚÀÚ¹Ù", 2, 150), + new Student("¼ÒÀÚ¹Ù", 1, 200), + new Student("³ªÀÚ¹Ù", 3, 290), + new Student("°¨ÀÚ¹Ù", 3, 180) + ); + + studentStream.sorted(Comparator.comparing(Student::getBan) // ¹Ýº° Á¤·Ä + .thenComparing(Comparator.naturalOrder())) // ±âº» Á¤·Ä + .forEach(System.out::println); + } +} + +class Student implements Comparable { + String name; + int ban; + int totalScore; + + Student(String name, int ban, int totalScore) { + this.name =name; + this.ban =ban; + this.totalScore =totalScore; + } + + public String toString() { + return String.format("[%s, %d, %d]", name, ban, totalScore).toString(); + } + + String getName() { return name;} + int getBan() { return ban;} + int getTotalScore() { return totalScore;} + + // ÃÑÁ¡ ³»¸²Â÷¼øÀ» ±âº» Á¤·Ä·Î ÇÑ´Ù. + public int compareTo(Student s) { + return s.totalScore - this.totalScore; + } +} diff --git a/source/ch14/StreamEx2.java b/source/ch14/StreamEx2.java new file mode 100644 index 0000000..55aa449 --- /dev/null +++ b/source/ch14/StreamEx2.java @@ -0,0 +1,27 @@ +import java.io.*; +import java.util.stream.*; + +class StreamEx2 { + public static void main(String[] args) { + File[] fileArr = { new File("Ex1.java"), new File("Ex1.bak"), + new File("Ex2.java"), new File("Ex1"), new File("Ex1.txt") + }; + + Stream fileStream = Stream.of(fileArr); + + // map()À¸·Î StreamÀ» StreamÀ¸·Î º¯È¯ + Stream filenameStream = fileStream.map(File::getName); + filenameStream.forEach(System.out::println); // ¸ðµç ÆÄÀÏÀÇ À̸§À» Ãâ·Â + + fileStream = Stream.of(fileArr); // ½ºÆ®¸²À» ´Ù½Ã »ý¼º + + fileStream.map(File::getName) // Stream ¡æ Stream + .filter(s -> s.indexOf('.')!=-1) // È®ÀåÀÚ°¡ ¾ø´Â °ÍÀº Á¦¿Ü + .map(s -> s.substring(s.indexOf('.')+1)) // È®ÀåÀÚ¸¸ ÃßÃâ + .map(String::toUpperCase) // ¸ðµÎ ´ë¹®ÀÚ·Î º¯È¯ + .distinct() // Áߺ¹ Á¦°Å + .forEach(System.out::print); // JAVABAKTXT + + System.out.println(); + } +} diff --git a/source/ch14/StreamEx3.java b/source/ch14/StreamEx3.java new file mode 100644 index 0000000..0d13331 --- /dev/null +++ b/source/ch14/StreamEx3.java @@ -0,0 +1,55 @@ +import java.util.*; +import java.util.stream.*; + +class StreamEx3 { + public static void main(String[] args) { + Student[] stuArr = { + new Student("ÀÌÀÚ¹Ù", 3, 300), + new Student("±èÀÚ¹Ù", 1, 200), + new Student("¾ÈÀÚ¹Ù", 2, 100), + new Student("¹ÚÀÚ¹Ù", 2, 150), + new Student("¼ÒÀÚ¹Ù", 1, 200), + new Student("³ªÀÚ¹Ù", 3, 290), + new Student("°¨ÀÚ¹Ù", 3, 180) + }; + + Stream stuStream = Stream.of(stuArr); + + stuStream.sorted(Comparator.comparing(Student::getBan) + .thenComparing(Comparator.naturalOrder())) + .forEach(System.out::println); + + stuStream = Stream.of(stuArr); // ½ºÆ®¸²À» ´Ù½Ã »ý¼ºÇÑ´Ù. + IntStream stuScoreStream= stuStream.mapToInt(Student::getTotalScore); + + IntSummaryStatistics stat = stuScoreStream.summaryStatistics(); + System.out.println("count="+stat.getCount()); + System.out.println("sum="+stat.getSum()); + System.out.printf("average=%.2f%n", stat.getAverage()); + System.out.println("min="+stat.getMin()); + System.out.println("max="+stat.getMax()); + } +} + +class Student implements Comparable { + String name; + int ban; + int totalScore; + Student(String name, int ban, int totalScore) { + this.name = name; + this.ban = ban; + this.totalScore = totalScore; + } + + public String toString() { + return String.format("[%s, %d, %d]", name, ban, totalScore).toString(); + } + + String getName() { return name;} + int getBan() { return ban;} + int getTotalScore() { return totalScore;} + + public int compareTo(Student s) { + return s.totalScore - this.totalScore; + } +} diff --git a/source/ch14/StreamEx4.java b/source/ch14/StreamEx4.java new file mode 100644 index 0000000..f4b2c2d --- /dev/null +++ b/source/ch14/StreamEx4.java @@ -0,0 +1,46 @@ +import java.util.*; +import java.util.stream.*; + +class StreamEx4 { + public static void main(String[] args) { + + Stream strArrStrm = Stream.of( + new String[]{"abc", "def", "jkl"}, + new String[]{"ABC", "GHI", "JKL"} + ); + +// Stream> strStrmStrm = strArrStrm.map(Arrays::stream); + Stream strStrm = strArrStrm.flatMap(Arrays::stream); + + strStrm.map(String::toLowerCase) + .distinct() + .sorted() + .forEach(System.out::println); + System.out.println(); + + String[] lineArr = { + "Believe or not It is true", + "Do or do not There is no try", + }; + + Stream lineStream = Arrays.stream(lineArr); + lineStream.flatMap(line -> Stream.of(line.split(" +"))) + .map(String::toLowerCase) + .distinct() + .sorted() + .forEach(System.out::println); + System.out.println(); + + Stream strStrm1 = Stream.of("AAA", "ABC", "bBb", "Dd"); + Stream strStrm2 = Stream.of("bbb", "aaa", "ccc", "dd"); + + Stream> strStrmStrm = Stream.of(strStrm1, strStrm2); + + Stream strStream = strStrmStrm + .map(s -> s.toArray(String[]::new)) + .flatMap(Arrays::stream); + strStream.map(String::toLowerCase) + .distinct() + .forEach(System.out::println); + } +} diff --git a/source/ch14/StreamEx5.java b/source/ch14/StreamEx5.java new file mode 100644 index 0000000..14fcb4f --- /dev/null +++ b/source/ch14/StreamEx5.java @@ -0,0 +1,37 @@ +import java.util.*; +import java.util.stream.*; + +class StreamEx5 { + public static void main(String[] args) { + String[] strArr = { + "Inheritance", "Java", "Lambda", "stream", + "OptionalDouble", "IntStream", "count", "sum" + }; + + Stream.of(strArr).forEach(System.out::println); + + boolean noEmptyStr = Stream.of(strArr).noneMatch(s->s.length()==0); + Optional sWord = Stream.of(strArr) + .filter(s->s.charAt(0)=='s').findFirst(); + + System.out.println("noEmptyStr="+noEmptyStr); + System.out.println("sWord="+ sWord.get()); + + // StreamÀ» IntStreamÀ¸·Î º¯È¯ + IntStream intStream1 = Stream.of(strArr).mapToInt(String::length); + IntStream intStream2 = Stream.of(strArr).mapToInt(String::length); + IntStream intStream3 = Stream.of(strArr).mapToInt(String::length); + IntStream intStream4 = Stream.of(strArr).mapToInt(String::length); + + int count = intStream1.reduce(0, (a,b) -> a + 1); + int sum = intStream2.reduce(0, (a,b) -> a + b); + + OptionalInt max = intStream3.reduce(Integer::max); + OptionalInt min = intStream4.reduce(Integer::min); + + System.out.println("count="+count); + System.out.println("sum="+sum); + System.out.println("max="+ max.getAsInt()); + System.out.println("min="+ min.getAsInt()); + } +} diff --git a/source/ch14/StreamEx6.java b/source/ch14/StreamEx6.java new file mode 100644 index 0000000..9f862d6 --- /dev/null +++ b/source/ch14/StreamEx6.java @@ -0,0 +1,82 @@ +import java.util.*; +import java.util.stream.*; +import static java.util.stream.Collectors.*; + +class StreamEx6 { + public static void main(String[] args) { + Student[] stuArr = { + new Student("ÀÌÀÚ¹Ù", 3, 300), + new Student("±èÀÚ¹Ù", 1, 200), + new Student("¾ÈÀÚ¹Ù", 2, 100), + new Student("¹ÚÀÚ¹Ù", 2, 150), + new Student("¼ÒÀÚ¹Ù", 1, 200), + new Student("³ªÀÚ¹Ù", 3, 290), + new Student("°¨ÀÚ¹Ù", 3, 180) + }; + + // Çлý À̸§¸¸ »Ì¾Æ¼­ List¿¡ ÀúÀå + List names = Stream.of(stuArr).map(Student::getName) + .collect(Collectors.toList()); + System.out.println(names); + + // ½ºÆ®¸²À» ¹è¿­·Î º¯È¯ + Student[] stuArr2 = Stream.of(stuArr).toArray(Student[]::new); + + for(Student s : stuArr2) + System.out.println(s); + + // ½ºÆ®¸²À» Map·Î º¯È¯. Çлý À̸§ÀÌ key + Map stuMap = Stream.of(stuArr) + .collect(Collectors.toMap(s->s.getName(), p->p)); + for(String name : stuMap.keySet()) + System.out.println(name +"-"+stuMap.get(name)); + + long count = Stream.of(stuArr).collect(counting()); + long totalScore = Stream.of(stuArr) + .collect(summingInt(Student::getTotalScore)); + System.out.println("count="+count); + System.out.println("totalScore="+totalScore); + + totalScore = Stream.of(stuArr) + .collect(reducing(0, Student::getTotalScore, Integer::sum)); + System.out.println("totalScore="+totalScore); + + Optional topStudent = Stream.of(stuArr) + .collect(maxBy(Comparator.comparingInt(Student::getTotalScore))); + System.out.println("topStudent="+topStudent.get()); + + IntSummaryStatistics stat = Stream.of(stuArr) + .collect(summarizingInt(Student::getTotalScore)); + System.out.println(stat); + + String stuNames = Stream.of(stuArr) + .map(Student::getName) + .collect(joining(",", "{", "}")); + System.out.println(stuNames); + } +} + + +class Student implements Comparable { + String name; + int ban; + int totalScore; + + Student(String name, int ban, int totalScore) { + this.name =name; + this.ban =ban; + this.totalScore =totalScore; + } + + public String toString() { + return String.format("[%s, %d, %d]", name, ban, totalScore).toString(); + } + + String getName() { return name;} + int getBan() { return ban;} + int getTotalScore() { return totalScore;} + + public int compareTo(Student s) { + return s.totalScore - this.totalScore; + } +} diff --git a/source/ch14/StreamEx7.java b/source/ch14/StreamEx7.java new file mode 100644 index 0000000..95d8c94 --- /dev/null +++ b/source/ch14/StreamEx7.java @@ -0,0 +1,106 @@ +import java.util.*; +import java.util.function.*; +import java.util.stream.*; +import static java.util.stream.Collectors.*; +import static java.util.Comparator.*; + +class Student { + String name; + boolean isMale; // ¼ºº° + int hak; // Çгâ + int ban; // ¹Ý + int score; + + Student(String name, boolean isMale, int hak, int ban, int score) { + this.name = name; + this.isMale = isMale; + this.hak = hak; + this.ban = ban; + this.score = score; + } + String getName() { return name;} + boolean isMale() { return isMale;} + int getHak() { return hak;} + int getBan() { return ban;} + int getScore() { return score;} + + public String toString() { + return String.format("[%s, %s, %dÇгâ %d¹Ý, %3dÁ¡]", + name, isMale ? "³²":"¿©", hak, ban, score); + } + // groupingBy()¿¡¼­ »ç¿ë + enum Level { HIGH, MID, LOW } // ¼ºÀûÀ» »ó, Áß, ÇÏ ¼¼ ´Ü°è·Î ºÐ·ù +} + +class StreamEx7 { + public static void main(String[] args) { + Student[] stuArr = { + new Student("³ªÀÚ¹Ù", true, 1, 1, 300), + new Student("±èÁö¹Ì", false, 1, 1, 250), + new Student("±èÀÚ¹Ù", true, 1, 1, 200), + new Student("ÀÌÁö¹Ì", false, 1, 2, 150), + new Student("³²ÀÚ¹Ù", true, 1, 2, 100), + new Student("¾ÈÁö¹Ì", false, 1, 2, 50), + new Student("ȲÁö¹Ì", false, 1, 3, 100), + new Student("°­Áö¹Ì", false, 1, 3, 150), + new Student("ÀÌÀÚ¹Ù", true, 1, 3, 200), + + new Student("³ªÀÚ¹Ù", true, 2, 1, 300), + new Student("±èÁö¹Ì", false, 2, 1, 250), + new Student("±èÀÚ¹Ù", true, 2, 1, 200), + new Student("ÀÌÁö¹Ì", false, 2, 2, 150), + new Student("³²ÀÚ¹Ù", true, 2, 2, 100), + new Student("¾ÈÁö¹Ì", false, 2, 2, 50), + new Student("ȲÁö¹Ì", false, 2, 3, 100), + new Student("°­Áö¹Ì", false, 2, 3, 150), + new Student("ÀÌÀÚ¹Ù", true, 2, 3, 200) + }; + + System.out.printf("1. ´Ü¼øºÐÇÒ(¼ºº°·Î ºÐÇÒ)%n"); + Map> stuBySex = Stream.of(stuArr) + .collect(partitioningBy(Student::isMale)); + + List maleStudent = stuBySex.get(true); + List femaleStudent = stuBySex.get(false); + + for(Student s : maleStudent) System.out.println(s); + for(Student s : femaleStudent) System.out.println(s); + + System.out.printf("%n2. ´Ü¼øºÐÇÒ + Åë°è(¼ºº° Çлý¼ö)%n"); + Map stuNumBySex = Stream.of(stuArr) + .collect(partitioningBy(Student::isMale, counting())); + + System.out.println("³²Çлý ¼ö :"+ stuNumBySex.get(true)); + System.out.println("¿©Çлý ¼ö :"+ stuNumBySex.get(false)); + + + System.out.printf("%n3. ´Ü¼øºÐÇÒ + Åë°è(¼ºº° 1µî)%n"); + Map> topScoreBySex = Stream.of(stuArr) + .collect(partitioningBy(Student::isMale, + maxBy(comparingInt(Student::getScore)) + )); + System.out.println("³²Çлý 1µî :"+ topScoreBySex.get(true)); + System.out.println("¿©Çлý 1µî :"+ topScoreBySex.get(false)); + + Map topScoreBySex2 = Stream.of(stuArr) + .collect(partitioningBy(Student::isMale, + collectingAndThen( + maxBy(comparingInt(Student::getScore)), Optional::get + ) + )); + System.out.println("³²Çлý 1µî :"+ topScoreBySex2.get(true)); + System.out.println("¿©Çлý 1µî :"+ topScoreBySex2.get(false)); + + System.out.printf("%n4. ´ÙÁߺÐÇÒ(¼ºº° ºÒÇÕ°ÝÀÚ, 100Á¡ ÀÌÇÏ)%n"); + + Map>> failedStuBySex = + Stream.of(stuArr).collect(partitioningBy(Student::isMale, + partitioningBy(s -> s.getScore() <= 100)) + ); + List failedMaleStu = failedStuBySex.get(true).get(true); + List failedFemaleStu = failedStuBySex.get(false).get(true); + + for(Student s : failedMaleStu) System.out.println(s); + for(Student s : failedFemaleStu) System.out.println(s); + } +} diff --git a/source/ch14/StreamEx8.java b/source/ch14/StreamEx8.java new file mode 100644 index 0000000..b2b7b40 --- /dev/null +++ b/source/ch14/StreamEx8.java @@ -0,0 +1,154 @@ +import java.util.*; +import java.util.function.*; +import java.util.stream.*; +import static java.util.stream.Collectors.*; +import static java.util.Comparator.*; + +class Student { + String name; + boolean isMale; // ¼ºº° + int hak; // Çгâ + int ban; // ¹Ý + int score; + + Student(String name, boolean isMale, int hak, int ban, int score) { + this.name = name; + this.isMale = isMale; + this.hak = hak; + this.ban = ban; + this.score = score; + } + + String getName() { return name;} + boolean isMale() { return isMale;} + int getHak() { return hak;} + int getBan() { return ban;} + int getScore() { return score;} + + public String toString() { + return String.format("[%s, %s, %dÇгâ %d¹Ý, %3dÁ¡]", name, isMale ? "³²":"¿©", hak, ban, score); + } + + enum Level { + HIGH, MID, LOW + } +} + +class StreamEx8 { + public static void main(String[] args) { + Student[] stuArr = { + new Student("³ªÀÚ¹Ù", true, 1, 1, 300), + new Student("±èÁö¹Ì", false, 1, 1, 250), + new Student("±èÀÚ¹Ù", true, 1, 1, 200), + new Student("ÀÌÁö¹Ì", false, 1, 2, 150), + new Student("³²ÀÚ¹Ù", true, 1, 2, 100), + new Student("¾ÈÁö¹Ì", false, 1, 2, 50), + new Student("ȲÁö¹Ì", false, 1, 3, 100), + new Student("°­Áö¹Ì", false, 1, 3, 150), + new Student("ÀÌÀÚ¹Ù", true, 1, 3, 200), + + new Student("³ªÀÚ¹Ù", true, 2, 1, 300), + new Student("±èÁö¹Ì", false, 2, 1, 250), + new Student("±èÀÚ¹Ù", true, 2, 1, 200), + new Student("ÀÌÁö¹Ì", false, 2, 2, 150), + new Student("³²ÀÚ¹Ù", true, 2, 2, 100), + new Student("¾ÈÁö¹Ì", false, 2, 2, 50), + new Student("ȲÁö¹Ì", false, 2, 3, 100), + new Student("°­Áö¹Ì", false, 2, 3, 150), + new Student("ÀÌÀÚ¹Ù", true, 2, 3, 200) + }; + + System.out.printf("1. ´Ü¼ø±×·ìÈ­(¹Ýº°·Î ±×·ìÈ­)%n"); + Map> stuByBan = Stream.of(stuArr) + .collect(groupingBy(Student::getBan)); + + for(List ban : stuByBan.values()) { + for(Student s : ban) { + System.out.println(s); + } + } + + System.out.printf("%n2. ´Ü¼ø±×·ìÈ­(¼ºÀûº°·Î ±×·ìÈ­)%n"); + Map> stuByLevel = Stream.of(stuArr) + .collect(groupingBy(s-> { + if(s.getScore() >= 200) return Student.Level.HIGH; + else if(s.getScore() >= 100) return Student.Level.MID; + else return Student.Level.LOW; + })); + + TreeSet keySet = new TreeSet<>(stuByLevel.keySet()); + + for(Student.Level key : keySet) { + System.out.println("["+key+"]"); + + for(Student s : stuByLevel.get(key)) + System.out.println(s); + System.out.println(); + } + + System.out.printf("%n3. ´Ü¼ø±×·ìÈ­ + Åë°è(¼ºÀûº° Çлý¼ö)%n"); + Map stuCntByLevel = Stream.of(stuArr) + .collect(groupingBy(s-> { + if(s.getScore() >= 200) return Student.Level.HIGH; + else if(s.getScore() >= 100) return Student.Level.MID; + else return Student.Level.LOW; + }, counting())); + + for(Student.Level key : stuCntByLevel.keySet()) + System.out.printf("[%s] - %d¸í, ", key, stuCntByLevel.get(key)); + System.out.println(); +/* + for(List level : stuByLevel.values()) { + System.out.println(); + for(Student s : level) { + System.out.println(s); + } + } +*/ + System.out.printf("%n4. ´ÙÁß±×·ìÈ­(Çг⺰, ¹Ýº°)%n"); + Map>> stuByHakAndBan = + Stream.of(stuArr) + .collect(groupingBy(Student::getHak, + groupingBy(Student::getBan) + )); + + for(Map> hak : stuByHakAndBan.values()) { + for(List ban : hak.values()) { + System.out.println(); + for(Student s : ban) + System.out.println(s); + } + } + + System.out.printf("%n5. ´ÙÁß±×·ìÈ­ + Åë°è(Çг⺰, ¹Ýº° 1µî)%n"); + Map> topStuByHakAndBan = Stream.of(stuArr) + .collect(groupingBy(Student::getHak, + groupingBy(Student::getBan, + collectingAndThen( + maxBy(comparingInt(Student::getScore)), + Optional::get + ) + ) + )); + + for(Map ban : topStuByHakAndBan.values()) + for(Student s : ban.values()) + System.out.println(s); + + System.out.printf("%n6. ´ÙÁß±×·ìÈ­ + Åë°è(Çг⺰, ¹Ýº° ¼ºÀû±×·ì)%n"); + Map> stuByScoreGroup = Stream.of(stuArr) + .collect(groupingBy(s-> s.getHak() + "-" + s.getBan(), + mapping(s-> { + if(s.getScore() >= 200) return Student.Level.HIGH; + else if(s.getScore() >= 100) return Student.Level.MID; + else return Student.Level.LOW; + } , toSet()) + )); + + Set keySet2 = stuByScoreGroup.keySet(); + + for(String key : keySet2) { + System.out.println("["+key+"]" + stuByScoreGroup.get(key)); + } + } // mainÀÇ ³¡ +} diff --git a/source/ch15/BufferedOutputStreamEx1.java b/source/ch15/BufferedOutputStreamEx1.java new file mode 100644 index 0000000..075b380 --- /dev/null +++ b/source/ch15/BufferedOutputStreamEx1.java @@ -0,0 +1,19 @@ + import java.io.*; + +class BufferedOutputStreamEx1 { + public static void main(String args[]) { + try { + FileOutputStream fos = new FileOutputStream("123.txt"); + // BufferedOutputStreamÀÇ ¹öÆÛ Å©±â¸¦ 5·Î ÇÑ´Ù. + BufferedOutputStream bos = new BufferedOutputStream(fos, 5); + // ÆÄÀÏ 123.txt¿¡ 1 ºÎÅÍ 9±îÁö Ãâ·ÂÇÑ´Ù. + for(int i='1'; i <= '9'; i++) { + bos.write(i); + } + + fos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/source/ch15/BufferedReaderEx1.java b/source/ch15/BufferedReaderEx1.java new file mode 100644 index 0000000..db26384 --- /dev/null +++ b/source/ch15/BufferedReaderEx1.java @@ -0,0 +1,19 @@ +import java.io.*; + +class BufferedReaderEx1 { + public static void main(String[] args) { + try { + FileReader fr = new FileReader("BufferedReaderEx1.java"); + BufferedReader br = new BufferedReader(fr); + + String line = ""; + for(int i=1;(line = br.readLine())!=null;i++) { + // ";"¸¦ Æ÷ÇÔÇÑ ¶óÀÎÀ» Ãâ·ÂÇÑ´Ù. + if(line.indexOf(";")!=-1) + System.out.println(i+":"+line); + } + + br.close(); + } catch(IOException e) {} + } // main +} diff --git a/source/ch15/DataInputStreamEx1.java b/source/ch15/DataInputStreamEx1.java new file mode 100644 index 0000000..81605c0 --- /dev/null +++ b/source/ch15/DataInputStreamEx1.java @@ -0,0 +1,17 @@ +import java.io.*; + +class DataInputStreamEx1 { + public static void main(String args[]) { + try { + FileInputStream fis = new FileInputStream("sample.dat"); + DataInputStream dis = new DataInputStream(fis); + + System.out.println(dis.readInt()); + System.out.println(dis.readFloat()); + System.out.println(dis.readBoolean()); + dis.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } // main +} diff --git a/source/ch15/DataInputStreamEx2.java b/source/ch15/DataInputStreamEx2.java new file mode 100644 index 0000000..17352bb --- /dev/null +++ b/source/ch15/DataInputStreamEx2.java @@ -0,0 +1,33 @@ +import java.io.*; + +class DataInputStreamEx2 { + public static void main(String args[]) { + int sum = 0; + int score = 0; + + FileInputStream fis = null; + DataInputStream dis = null; + + try { + fis = new FileInputStream("score.dat"); + dis = new DataInputStream(fis); + + while(true) { + score = dis.readInt(); + System.out.println(score); + sum += score; + } + } catch (EOFException e) { + System.out.println("Á¡¼öÀÇ ÃÑÇÕÀº " + sum +"ÀÔ´Ï´Ù."); + } catch (IOException ie) { + ie.printStackTrace(); + } finally { + try { + if(dis!=null) + dis.close(); + } catch(IOException ie){ + ie.printStackTrace(); + } + } // try + } // main +} diff --git a/source/ch15/DataInputStreamEx3.java b/source/ch15/DataInputStreamEx3.java new file mode 100644 index 0000000..3fd7261 --- /dev/null +++ b/source/ch15/DataInputStreamEx3.java @@ -0,0 +1,23 @@ +import java.io.*; + +class DataInputStreamEx3 { + public static void main(String args[]) { + int sum = 0; + int score = 0; + + try (FileInputStream fis = new FileInputStream("score.dat"); + DataInputStream dis = new DataInputStream(fis)) + { + + while(true) { + score = dis.readInt(); + System.out.println(score); + sum += score; + } + } catch (EOFException e) { + System.out.println("Á¡¼öÀÇ ÃÑÇÕÀº " + sum +"ÀÔ´Ï´Ù."); + } catch (IOException ie) { + ie.printStackTrace(); + } // try + } // main +} diff --git a/source/ch15/DataOutputStreamEx1.java b/source/ch15/DataOutputStreamEx1.java new file mode 100644 index 0000000..691adf6 --- /dev/null +++ b/source/ch15/DataOutputStreamEx1.java @@ -0,0 +1,20 @@ +import java.io.*; + +class DataOutputStreamEx1 { + public static void main(String args[]) { + FileOutputStream fos = null; + DataOutputStream dos = null; + + try { + fos = new FileOutputStream("sample.dat"); + dos = new DataOutputStream(fos); + dos.writeInt(10); + dos.writeFloat(20.0f); + dos.writeBoolean(true); + + dos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } // main +} diff --git a/source/ch15/DataOutputStreamEx2.java b/source/ch15/DataOutputStreamEx2.java new file mode 100644 index 0000000..afe86c8 --- /dev/null +++ b/source/ch15/DataOutputStreamEx2.java @@ -0,0 +1,38 @@ +import java.io.*; +import java.util.Arrays; + +class DataOutputStreamEx2 { + public static void main(String args[]) { + ByteArrayOutputStream bos = null; + DataOutputStream dos = null; + + byte[] result = null; + + try { + bos = new ByteArrayOutputStream(); + dos = new DataOutputStream(bos); + dos.writeInt(10); + dos.writeFloat(20.0f); + dos.writeBoolean(true); + + result = bos.toByteArray(); + + String[] hex = new String[result.length]; + + for(int i=0;i 0) result = 1; + else if(time1 - time2 == 0) result = 0; + else if(time1 - time2 < 0) result = -1; + break; + case 'T' : + if(time1 - time2 > 0) result = -1; + else if(time1 - time2 == 0) result = 0; + else if(time1 - time2 < 0) result = 1; + break; + case 'l' : + if(length1 - length2 > 0) result = 1; + else if(length1 - length2 == 0) result = 0; + else if(length1 - length2 < 0) result = -1; + break; + case 'L' : + if(length1 - length2 > 0) result = -1; + else if(length1 - length2 == 0) result = 0; + else if(length1 - length2 < 0) result = 1; + break; + case 'n' : + result = name1.compareTo(name2); + break; + case 'N' : + result = name2.compareTo(name1); + break; + } + return result; + } // compare + + public boolean equals(Object o) { return false; } // not used. + }; // end of Comparator + + Arrays.sort(files, comp); + + for(int i=0; i < files.length; i++) { + File f = files[i]; + String name = f.getName(); + SimpleDateFormat df =new SimpleDateFormat("yyyy-MM-dd HH:mm"); + String attribute = ""; + String size = ""; + + if(files[i].isDirectory()) { + attribute = "DIR"; + } else { + size = f.length() + ""; + attribute = f.canRead() ? "R" : " "; + attribute += f.canWrite() ? "W" : " "; + attribute += f.isHidden() ? "H" : " "; + } + + System.out.printf("%s %3s %6s %s%n", df.format(new Date(f.lastModified())),attribute,size,name ); + } // for + } // main +} // end of class diff --git a/source/ch15/FileEx6.java b/source/ch15/FileEx6.java new file mode 100644 index 0000000..8bf1f3a --- /dev/null +++ b/source/ch15/FileEx6.java @@ -0,0 +1,64 @@ +import java.io.*; + +class FileEx6 { + static int found = 0; + + public static void main(String args[]) { + if(args.length != 2) { + System.out.println("USAGE : java FileEx6 DIRECTORY KEYWORD"); + System.exit(0); + } + + File dir = new File(args[0]); + String keyword = args[1]; + + if(!dir.exists() || !dir.isDirectory()) { + System.out.println("À¯È¿ÇÏÁö ¾ÊÀº µð·ºÅ丮ÀÔ´Ï´Ù."); + System.exit(0); + } + + try { + findInFiles(dir, keyword); + } catch(IOException e) { + e.printStackTrace(); + } + + System.out.println(); + System.out.println("ÃÑ " + found + "°³ÀÇ ¶óÀο¡¼­ '" + keyword + "'À»/¸¦ ¹ß°ßÇÏ¿´½À´Ï´Ù. "); + } // main + + public static void findInFiles(File dir, String keyword) throws IOException + { + File[] files = dir.listFiles(); + + for(int i=0; i < files.length; i++) { + if(files[i].isDirectory()) { + findInFiles(files[i], keyword); + } else { + String filename = files[i].getName(); + String extension = filename.substring(filename.lastIndexOf(".")+1); + extension = "," + extension + "," ; + + if(",java,txt,bak,".indexOf(extension) == -1) continue; + + filename = dir.getAbsolutePath() + File.separator + filename; + + FileReader fr = new FileReader(files[i]); + BufferedReader br = new BufferedReader(fr); + + String data = ""; + int lineNum = 0; + + while((data=br.readLine())!=null) { + lineNum++; + if(data.indexOf(keyword)!=-1) { + found++; + System.out.println("["+filename+ "("+lineNum+")" + "]" + data); + } + } // while + + br.close(); + } + } // for + } // findInFiles +} // class diff --git a/source/ch15/FileEx7.java b/source/ch15/FileEx7.java new file mode 100644 index 0000000..571de7f --- /dev/null +++ b/source/ch15/FileEx7.java @@ -0,0 +1,26 @@ +import java.io.*; + +class FileEx7 { + public static void main(String[] args) throws Exception { + if(args.length != 1) { + System.out.println("USAGE : java FileEx7 pattern"); + System.exit(0); + } + + String currDir = System.getProperty("user.dir"); + + File dir = new File(currDir); + final String pattern = args[0]; + + // String[] list (FilenameFilter filter) + String[] files = dir.list(new FilenameFilter() { + public boolean accept(File dir, String name) { + return name.indexOf(pattern) != -1; + } + }); + + for(int i=0; i < files.length; i++) { + System.out.println(files[i]); + } + } // end of main +} // end of class diff --git a/source/ch15/FileEx8.java b/source/ch15/FileEx8.java new file mode 100644 index 0000000..e034e57 --- /dev/null +++ b/source/ch15/FileEx8.java @@ -0,0 +1,42 @@ +import java.io.*; + +class FileEx8 { + static int deletedFiles = 0; + + public static void main(String[] args) { + if(args.length != 1) { + System.out.println("USAGE : java FileEx8 Extension"); + System.exit(0); + } + + String currDir = System.getProperty("user.dir"); + + File dir = new File(currDir); + String ext = "." + args[0]; + + delete(dir, ext); + System.out.println(deletedFiles + "°³ÀÇ ÆÄÀÏÀÌ »èÁ¦µÇ¾ú½À´Ï´Ù."); + } // end of main + + public static void delete(File dir, String ext) { + File[] files = dir.listFiles(); + + for(int i=0; i < files.length; i++) { + if(files[i].isDirectory()) { + delete(files[i], ext); + } else { + String filename = files[i].getAbsolutePath(); + + if(filename.endsWith(ext)) { + System.out.print(filename); + if(files[i].delete()) { + System.out.println(" - »èÁ¦ ¼º°ø"); + deletedFiles++; + } else { + System.out.println(" - »èÁ¦ ½ÇÆÐ"); + } + } // if(filename.endsWith(ext)) { + } // if(files[i].isDirectory()) { + } // for(int i=0; i < files.length; i++) { + } // end of delete +} // end of class diff --git a/source/ch15/FileEx9.java b/source/ch15/FileEx9.java new file mode 100644 index 0000000..93c3725 --- /dev/null +++ b/source/ch15/FileEx9.java @@ -0,0 +1,27 @@ +import java.io.*; + +class FileEx9 { + public static void main(String[] args) { + if (args.length != 1) { + System.out.println("Usage: java FileEx9 DIRECTORY"); + System.exit(0); + } + + File dir = new File(args[0]); + + if(!dir.exists() || !dir.isDirectory()) { + System.out.println("À¯È¿ÇÏÁö ¾ÊÀº µð·ºÅ丮ÀÔ´Ï´Ù."); + System.exit(0); + } + + File[] list = dir.listFiles(); + + for (int i = 0; i < list.length; i++) { + String fileName = list[i].getName(); + // ÆÄÀϸí + String newFileName = "0000" + fileName; + newFileName = newFileName.substring(newFileName.length() - 7); + list[i].renameTo(new File(dir, newFileName)); + } + } // end of main +} // end of FileEx9 class diff --git a/source/ch15/FileMerge.java b/source/ch15/FileMerge.java new file mode 100644 index 0000000..4ee4d76 --- /dev/null +++ b/source/ch15/FileMerge.java @@ -0,0 +1,49 @@ +import java.io.*; + +class FileMerge { + public static void main(String[] args) { + if (args.length != 1) { + System.out.println("USAGE : java FileMerge filename"); + System.exit(0); // ÇÁ·Î±×·¥À» Á¾·áÇÑ´Ù. + } + + String mergeFilename = args[0]; + + try { + + File tempFile = File.createTempFile("~mergetemp",".tmp"); + tempFile.deleteOnExit(); + + FileOutputStream fos = new FileOutputStream(tempFile); + BufferedOutputStream bos = new BufferedOutputStream(fos); + + BufferedInputStream bis = null; + + int number = 1; + + File f = new File(mergeFilename + "_." + number); + + while(f.exists()) { + f.setReadOnly(); // ÀÛ¾÷Áß¿¡ ÆÄÀÏÀÇ ³»¿ëÀÌ º¯°æµÇÁö ¾Êµµ·Ï ÇÑ´Ù. + bis = new BufferedInputStream(new FileInputStream(f)); + + int data = 0; + while((data = bis.read()) != -1) { + bos.write(data); + } + + bis.close(); + + f = new File(mergeFilename + "_." + ++number); + } // while + + bos.close(); + + File oldFile = new File(mergeFilename); + + if(oldFile.exists()) oldFile.delete(); + + tempFile.renameTo(oldFile); + } catch (IOException e) {} + } // main +} // class diff --git a/source/ch15/FileReaderEx1.java b/source/ch15/FileReaderEx1.java new file mode 100644 index 0000000..cdfcbdb --- /dev/null +++ b/source/ch15/FileReaderEx1.java @@ -0,0 +1,30 @@ +import java.io.*; + +class FileReaderEx1 { + public static void main(String args[]) { + try { + String fileName = "test.txt"; + FileInputStream fis = new FileInputStream(fileName); + FileReader fr = new FileReader(fileName); + + int data =0; + + // FileInputStreamÀ» ÀÌ¿ëÇؼ­ ÆÄÀϳ»¿ëÀ» Àоî È­¸é¿¡ Ãâ·ÂÇÑ´Ù. + while((data=fis.read())!=-1) { + System.out.print((char)data); + } + System.out.println(); + fis.close(); + + // FileReader¸¦ ÀÌ¿ëÇؼ­ ÆÄÀϳ»¿ëÀ» Àоî È­¸é¿¡ Ãâ·ÂÇÑ´Ù. + while((data=fr.read())!=-1) { + System.out.print((char)data); + } + System.out.println(); + fr.close(); + + } catch (IOException e) { + e.printStackTrace(); + } + } // main +} diff --git a/source/ch15/FileSplit.java b/source/ch15/FileSplit.java new file mode 100644 index 0000000..a16e767 --- /dev/null +++ b/source/ch15/FileSplit.java @@ -0,0 +1,44 @@ +import java.io.*; + +class FileSplit { + public static void main(String[] args) { + if (args.length < 2) { + System.out.println("USAGE : java FileSplit filename SIZE_KB"); + System.exit(0); // ÇÁ·Î±×·¥À» Á¾·áÇÑ´Ù. + } + + final int VOLUME = Integer.parseInt(args[1]) * 1000; + + try { + String filename = args[0]; + + FileInputStream fis = new FileInputStream(filename); + BufferedInputStream bis = new BufferedInputStream(fis); + + FileOutputStream fos = null; + BufferedOutputStream bos = null; + + int data = 0; + int i = 0; + int number = 0; + + while((data = bis.read()) != -1) { + if (i%VOLUME==0) { + if (i!=0) { + bos.close(); + } + + fos = new FileOutputStream(filename + "_."+ ++number); + bos = new BufferedOutputStream(fos); + } + bos.write(data); + i++; + } + + bis.close(); + bos.close(); + } catch (IOException e) { + e.printStackTrace(); + } // end of try-catch + } // end of main +} // end of class FileSplit diff --git a/source/ch15/FileViewer.java b/source/ch15/FileViewer.java new file mode 100644 index 0000000..2ababa0 --- /dev/null +++ b/source/ch15/FileViewer.java @@ -0,0 +1,13 @@ +import java.io.*; + +class FileViewer { + public static void main(String args[]) throws IOException{ + FileInputStream fis = new FileInputStream(args[0]); + int data = 0; + + while((data=fis.read())!=-1) { + char c = (char)data; + System.out.print(c); + } + } +} diff --git a/source/ch15/IOEx1.java b/source/ch15/IOEx1.java new file mode 100644 index 0000000..a474765 --- /dev/null +++ b/source/ch15/IOEx1.java @@ -0,0 +1,26 @@ +import java.io.*; +import java.util.Arrays; + +class IOEx1 { + public static void main(String[] args) { + byte[] inSrc = {0,1,2,3,4,5,6,7,8,9}; + byte[] outSrc = null; + + ByteArrayInputStream input = null; + ByteArrayOutputStream output = null; + + input = new ByteArrayInputStream(inSrc); + output = new ByteArrayOutputStream(); + + int data = 0; + + while((data = input.read())!=-1) { + output.write(data); // void write(int b) + } + + outSrc = output.toByteArray(); // ½ºÆ®¸²ÀÇ ³»¿ëÀ» byte¹è¿­·Î ¹ÝȯÇÑ´Ù. + + System.out.println("Input Source :" + Arrays.toString(inSrc)); + System.out.println("Output Source :" + Arrays.toString(outSrc)); + } +} diff --git a/source/ch15/IOEx2.java b/source/ch15/IOEx2.java new file mode 100644 index 0000000..ebf0a4d --- /dev/null +++ b/source/ch15/IOEx2.java @@ -0,0 +1,27 @@ +import java.io.*; +import java.util.Arrays; + +class IOEx2 { + public static void main(String[] args) { + byte[] inSrc = {0,1,2,3,4,5,6,7,8,9}; + byte[] outSrc = null; + + byte[] temp = new byte[10]; + + ByteArrayInputStream input = null; + ByteArrayOutputStream output = null; + + input = new ByteArrayInputStream(inSrc); + output = new ByteArrayOutputStream(); + + input.read(temp,0,temp.length); // ÀÐ¾î ¿Â µ¥ÀÌÅ͸¦ ¹è¿­ temp¿¡ ´ã´Â´Ù. + output.write(temp,5, 5); // temp[5]ºÎÅÍ 5°³ÀÇ µ¥ÀÌÅ͸¦ writeÇÑ´Ù. + + outSrc = output.toByteArray(); + + System.out.println("Input Source :" + Arrays.toString(inSrc)); + System.out.println("temp :" + Arrays.toString(temp)); + System.out.println("Output Source :" + Arrays.toString(outSrc)); + + } +} diff --git a/source/ch15/IOEx3.java b/source/ch15/IOEx3.java new file mode 100644 index 0000000..b54c411 --- /dev/null +++ b/source/ch15/IOEx3.java @@ -0,0 +1,35 @@ +import java.io.*; +import java.util.Arrays; + +class IOEx3 { + public static void main(String[] args) { + byte[] inSrc = {0,1,2,3,4,5,6,7,8,9}; + byte[] outSrc = null; + + byte[] temp = new byte[4]; // ÀÌÀü ¿¹Á¦¿Í ¹è¿­ÀÇ Å©±â°¡ ´Ù¸£´Ù. + + ByteArrayInputStream input = null; + ByteArrayOutputStream output = null; + + input = new ByteArrayInputStream(inSrc); + output = new ByteArrayOutputStream(); + + System.out.println("Input Source :" + Arrays.toString(inSrc)); + + try { + while(input.available() > 0) { + input.read(temp); + output.write(temp); +// System.out.println("temp :" + Arrays.toString(temp)); + + outSrc = output.toByteArray(); + printArrays(temp, outSrc); + } + } catch(IOException e) {} + } // mainÀÇ ³¡ + + static void printArrays(byte[] temp, byte[] outSrc) { + System.out.println("temp :" +Arrays.toString(temp)); + System.out.println("Output Source :" +Arrays.toString(outSrc)); + } +} diff --git a/source/ch15/IOEx4.java b/source/ch15/IOEx4.java new file mode 100644 index 0000000..94da2da --- /dev/null +++ b/source/ch15/IOEx4.java @@ -0,0 +1,30 @@ +import java.io.*; +import java.util.Arrays; + +class IOEx4 { + public static void main(String[] args) { + byte[] inSrc = {0,1,2,3,4,5,6,7,8,9}; + byte[] outSrc = null; + + byte[] temp = new byte[4]; + + ByteArrayInputStream input = null; + ByteArrayOutputStream output = null; + + input = new ByteArrayInputStream(inSrc); + output = new ByteArrayOutputStream(); + + try { + while(input.available() > 0) { + int len = input.read(temp); // ÀÐ¾î ¿Â µ¥ÀÌÅÍÀÇ °³¼ö¸¦ ¹ÝȯÇÑ´Ù. + output.write(temp, 0, len); // ÀÐ¾î ¿Â ¸¸Å­¸¸ writeÇÑ´Ù. + } + } catch(IOException e) {} + + outSrc = output.toByteArray(); + + System.out.println("Input Source :" + Arrays.toString(inSrc)); + System.out.println("temp :" + Arrays.toString(temp)); + System.out.println("Output Source :" + Arrays.toString(outSrc)); + } +} diff --git a/source/ch15/InputStreamReaderEx.java b/source/ch15/InputStreamReaderEx.java new file mode 100644 index 0000000..182f617 --- /dev/null +++ b/source/ch15/InputStreamReaderEx.java @@ -0,0 +1,23 @@ +import java.io.*; + +class InputStreamReaderEx { + public static void main(String[] args) { + String line = ""; + + try { + InputStreamReader isr = new InputStreamReader(System.in); + BufferedReader br = new BufferedReader(isr); + + System.out.println("»ç¿ëÁßÀÎ OSÀÇ ÀÎÄÚµù :" + isr.getEncoding()); + + do { + System.out.print("¹®ÀåÀ» ÀÔ·ÂÇϼ¼¿ä. ¸¶Ä¡½Ã·Á¸é q¸¦ ÀÔ·ÂÇϼ¼¿ä.>"); + line = br.readLine(); + System.out.println("ÀÔ·ÂÇϽŠ¹®Àå : "+line); + } while(!line.equalsIgnoreCase("q")); + +// br.close(); // System.in°ú °°Àº Ç¥ÁØÀÔÃâ·ÂÀº ´ÝÁö ¾Ê¾Æµµ µÈ´Ù. + System.out.println("ÇÁ·Î±×·¥À» Á¾·áÇÕ´Ï´Ù."); + } catch(IOException e) {} + } // main +} diff --git a/source/ch15/PipedReaderWriter.java b/source/ch15/PipedReaderWriter.java new file mode 100644 index 0000000..12e33d0 --- /dev/null +++ b/source/ch15/PipedReaderWriter.java @@ -0,0 +1,71 @@ +import java.io.*; + +public class PipedReaderWriter { + public static void main(String args[]) { + InputThread inThread = new InputThread("InputThread"); + OutputThread outThread = new OutputThread("OutputThread"); + + //PipedReader¿Í PipedWriter¸¦ ¿¬°áÇÑ´Ù. + inThread.connect(outThread.getOutput()); + + inThread.start(); + outThread.start(); + } // main +} + +class InputThread extends Thread { + PipedReader input = new PipedReader(); + StringWriter sw = new StringWriter(); + + InputThread(String name) { + super(name); // Thread(String name); + } + + public void run() { + try { + int data = 0; + + while((data=input.read()) != -1) { + sw.write(data); + } + System.out.println(getName() + " received : " + sw.toString()); + } catch(IOException e) {} + } // run + + public PipedReader getInput() { + return input; + } + + public void connect(PipedWriter output) { + try { + input.connect(output); + } catch(IOException e) {} + } // connect +} + +class OutputThread extends Thread { + PipedWriter output = new PipedWriter(); + + OutputThread(String name) { + super(name); // Thread(String name); + } + + public void run() { + try { + String msg = "Hello"; + System.out.println(getName() + " sent : " + msg); + output.write(msg); + output.close(); + } catch(IOException e) {} + } // run + + public PipedWriter getOutput() { + return output; + } + + public void connect(PipedReader input) { + try { + output.connect(input); + } catch(IOException e) {} + } // connect +} diff --git a/source/ch15/PrintStreamEx1.java b/source/ch15/PrintStreamEx1.java new file mode 100644 index 0000000..0df1abb --- /dev/null +++ b/source/ch15/PrintStreamEx1.java @@ -0,0 +1,23 @@ +import java.util.Date; + +class PrintStreamEx1 { + public static void main(String[] args) { + int i = 65; + float f = 1234.56789f; + + Date d = new Date(); + + System.out.printf("¹®ÀÚ %cÀÇ ÄÚµå´Â %d%n", i, i); + System.out.printf("%d´Â 8Áø¼ö·Î %o, 16Áø¼ö·Î %x%n", i ,i, i); + System.out.printf("%3d%3d%3d%n", 100, 90, 80); + System.out.println(); + System.out.printf("123456789012345678901234567890%n"); + System.out.printf("%s%-5s%5s%n", "123", "123", "123"); + System.out.println(); + System.out.printf("%-8.1f%8.1f %e%n",f,f,f); + System.out.println(); + System.out.printf("¿À´ÃÀº %tY³â %tm¿ù %tdÀÏ ÀÔ´Ï´Ù.%n", d,d,d ); + System.out.printf("Áö±ÝÀº %tH½Ã %tMºÐ %tSÃÊ ÀÔ´Ï´Ù.%n", d,d,d ); + System.out.printf("Áö±ÝÀº %1$tH½Ã %1$tMºÐ %1$tSÃÊ ÀÔ´Ï´Ù.%n", d ); + } +} diff --git a/source/ch15/RandomAccessFileEx1.java b/source/ch15/RandomAccessFileEx1.java new file mode 100644 index 0000000..3ace121 --- /dev/null +++ b/source/ch15/RandomAccessFileEx1.java @@ -0,0 +1,16 @@ +import java.io.*; + +class RandomAccessFileEx1 { + public static void main(String[] args) { + try { + RandomAccessFile raf = new RandomAccessFile("test.dat", "rw"); + System.out.println("ÆÄÀÏ Æ÷ÀÎÅÍÀÇ À§Ä¡: " + raf.getFilePointer()); + raf.writeInt(100); + System.out.println("ÆÄÀÏ Æ÷ÀÎÅÍÀÇ À§Ä¡: " + raf.getFilePointer()); + raf.writeLong(100L); + System.out.println("ÆÄÀÏ Æ÷ÀÎÅÍÀÇ À§Ä¡: " + raf.getFilePointer()); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/source/ch15/RandomAccessFileEx2.java b/source/ch15/RandomAccessFileEx2.java new file mode 100644 index 0000000..c0025f8 --- /dev/null +++ b/source/ch15/RandomAccessFileEx2.java @@ -0,0 +1,29 @@ +import java.io.*; + +class RandomAccessFileEx2 { + public static void main(String args[]) { +// ¹øÈ£, ±¹¾î, ¿µ¾î, ¼öÇÐ + int[] score = { 1, 100, 90, 90, + 2, 70, 90, 100, + 3, 100, 100, 100, + 4, 70, 60, 80, + 5, 70, 90, 100 + }; + + try { + RandomAccessFile raf = new RandomAccessFile("score2.dat", "rw"); + + for(int i=0; i list = new ArrayList<>(); + list.add(u1); + list.add(u2); + + // °´Ã¼¸¦ Á÷·ÄÈ­ÇÑ´Ù. + out.writeObject(u1); + out.writeObject(u2); + out.writeObject(list); + out.close(); + System.out.println("Á÷·ÄÈ­°¡ Àß ³¡³µ½À´Ï´Ù."); + } catch(IOException e) { + e.printStackTrace(); + } + } // main +} // class diff --git a/source/ch15/SerialEx2.java b/source/ch15/SerialEx2.java new file mode 100644 index 0000000..0141747 --- /dev/null +++ b/source/ch15/SerialEx2.java @@ -0,0 +1,26 @@ +import java.io.*; +import java.util.ArrayList; + +public class SerialEx2 { + public static void main(String[] args) { + try { + String fileName = "UserInfo.ser"; + FileInputStream fis = new FileInputStream(fileName); + BufferedInputStream bis = new BufferedInputStream(fis); + + ObjectInputStream in = new ObjectInputStream(bis); + + // °´Ã¼¸¦ ÀÐÀ» ¶§´Â Ãâ·ÂÇÑ ¼ø¼­¿Í ÀÏÄ¡ÇؾßÇÑ´Ù. + UserInfo u1 = (UserInfo)in.readObject(); + UserInfo u2 = (UserInfo)in.readObject(); + ArrayList list = (ArrayList)in.readObject(); + + System.out.println(u1); + System.out.println(u2); + System.out.println(list); + in.close(); + } catch(Exception e) { + e.printStackTrace(); + } + } // main +} // class diff --git a/source/ch15/StandardIOEx1.java b/source/ch15/StandardIOEx1.java new file mode 100644 index 0000000..f9d38f1 --- /dev/null +++ b/source/ch15/StandardIOEx1.java @@ -0,0 +1,15 @@ +import java.io.*; + +class StandardIOEx1 { + public static void main(String[] args) { + try { + int input = 0; + + while((input=System.in.read())!=-1) { + System.out.println("input :" + input + ", (char)input :" + (char)input); + } + } catch(IOException e) { + e.printStackTrace(); + } + } // main +} diff --git a/source/ch15/StandardIOEx2.java b/source/ch15/StandardIOEx2.java new file mode 100644 index 0000000..64dad15 --- /dev/null +++ b/source/ch15/StandardIOEx2.java @@ -0,0 +1,6 @@ +class StandardIOEx2 { + public static void main(String[] args) { + System.out.println("out : Hello World!"); + System.err.println("err : Hello World!"); + } +} diff --git a/source/ch15/StandardIOEx3.java b/source/ch15/StandardIOEx3.java new file mode 100644 index 0000000..7e25eb6 --- /dev/null +++ b/source/ch15/StandardIOEx3.java @@ -0,0 +1,19 @@ + import java.io.*; + +class StandardIOEx3 { + public static void main(String[] args) { + PrintStream ps = null; + FileOutputStream fos = null; + + try { + fos = new FileOutputStream("test.txt"); + ps = new PrintStream(fos); + System.setOut(ps); // System.outÀÇ Ãâ·Â´ë»óÀ» test.txtÆÄÀÏ·Î º¯°æ + } catch(FileNotFoundException e) { + System.err.println("File not found."); + } + + System.out.println("Hello by System.out"); + System.err.println("Hello by System.err"); + } +} diff --git a/source/ch15/StringReaderWriterEx.java b/source/ch15/StringReaderWriterEx.java new file mode 100644 index 0000000..d86e376 --- /dev/null +++ b/source/ch15/StringReaderWriterEx.java @@ -0,0 +1,21 @@ + import java.io.*; + +class StringReaderWriterEx { + public static void main(String[] args) { + String inputData = "ABCD"; + StringReader input = new StringReader(inputData); + StringWriter output = new StringWriter(); + + int data = 0; + + try { + while((data = input.read())!=-1) { + output.write(data); // void write(int b) + } + } catch(IOException e) {} + + System.out.println("Input Data :" + inputData); + System.out.println("Output Data :" + output.toString()); +// System.out.println("Output Data :" + output.getBuffer().toString()); + } +} diff --git a/source/ch15/UserInfo.java b/source/ch15/UserInfo.java new file mode 100644 index 0000000..76024d0 --- /dev/null +++ b/source/ch15/UserInfo.java @@ -0,0 +1,19 @@ +public class UserInfo implements java.io.Serializable { + String name; + String password; + int age; + + public UserInfo() { + this("Unknown", "1111", 0); + } + + public UserInfo(String name, String password, int age) { + this.name = name; + this.password = password; + this.age = age; + } + + public String toString() { + return "("+ name + "," + password + "," + age + ")"; + } +} diff --git a/source/ch15/UserInfo2.java b/source/ch15/UserInfo2.java new file mode 100644 index 0000000..3d92be4 --- /dev/null +++ b/source/ch15/UserInfo2.java @@ -0,0 +1,46 @@ +import java.io.*; + +class SuperUserInfo { + String name; + String password; + + SuperUserInfo() { + this("Unknown","1111"); + } + + SuperUserInfo(String name, String password) { + this.name = name; + this.password = password; + } +} // class SuperUserInfo + +public class UserInfo2 extends SuperUserInfo implements java.io.Serializable { + int age; + + public UserInfo2() { + this("Unknown", "1111", 0); + } + + public UserInfo2(String name, String password, int age) { + super(name, password); + this.age = age; + } + + public String toString() { + return "("+ name + "," + password + "," + age + ")"; + } + + private void writeObject(ObjectOutputStream out) + throws IOException { + out.writeUTF(name); + out.writeUTF(password); + out.defaultWriteObject(); + } + + private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + name = in.readUTF(); + password = in.readUTF(); + in.defaultReadObject(); + + } +} // class UserInfo2 diff --git a/source/ch16/NetworkEx1.java b/source/ch16/NetworkEx1.java new file mode 100644 index 0000000..ad3119d --- /dev/null +++ b/source/ch16/NetworkEx1.java @@ -0,0 +1,51 @@ +import java.net.*; +import java.util.*; + +class NetworkEx1 { + public static void main(String[] args) + { + InetAddress ip = null; + InetAddress[] ipArr = null; + + try { + ip = InetAddress.getByName("www.naver.com"); + System.out.println("getHostName() :" +ip.getHostName()); + System.out.println("getHostAddress() :"+ip.getHostAddress()); + System.out.println("toString() :" +ip.toString()); + + byte[] ipAddr = ip.getAddress(); + System.out.println("getAddress() :"+Arrays.toString(ipAddr)); + + String result = ""; + for(int i=0; i < ipAddr.length;i++) { + result += (ipAddr[i] < 0) ? ipAddr[i] + 256 : ipAddr[i]; + result += "."; + } + System.out.println("getAddress()+256 :"+result); + System.out.println(); + } catch (UnknownHostException e) { + e.printStackTrace(); + } + + try { + ip = InetAddress.getLocalHost(); + System.out.println("getHostName() :" +ip.getHostName()); + System.out.println("getHostAddress() :"+ip.getHostAddress()); + System.out.println(); + } catch (UnknownHostException e) { + e.printStackTrace(); + } + + + try { + ipArr = InetAddress.getAllByName("www.naver.com"); + + for(int i=0; i < ipArr.length; i++) { + System.out.println("ipArr["+i+"] :" + ipArr[i]); + } + } catch (UnknownHostException e) { + e.printStackTrace(); + } + + } // main +} diff --git a/source/ch16/NetworkEx2.java b/source/ch16/NetworkEx2.java new file mode 100644 index 0000000..8383c1b --- /dev/null +++ b/source/ch16/NetworkEx2.java @@ -0,0 +1,21 @@ +import java.net.*; + +class NetworkEx2 { + public static void main(String args[]) throws Exception { + URL url = new URL("http://www.codechobo.com:80/sample/"+"hello.html?referer=javachobo#index1"); + + System.out.println("url.getAuthority():"+ url.getAuthority()); + System.out.println("url.getContent():"+ url.getContent()); + System.out.println("url.getDefaultPort():"+ url.getDefaultPort()); + System.out.println("url.getPort():"+ url.getPort()); + System.out.println("url.getFile():"+ url.getFile()); + System.out.println("url.getHost():"+ url.getHost()); + System.out.println("url.getPath():"+ url.getPath()); + System.out.println("url.getProtocol():"+ url.getProtocol()); + System.out.println("url.getQuery():"+ url.getQuery()); + System.out.println("url.getRef():"+ url.getRef()); + System.out.println("url.getUserInfo():"+ url.getUserInfo()); + System.out.println("url.toExternalForm():"+ url.toExternalForm()); + System.out.println("url.toURI():"+ url.toURI()); + } +} diff --git a/source/ch16/NetworkEx3.java b/source/ch16/NetworkEx3.java new file mode 100644 index 0000000..abad465 --- /dev/null +++ b/source/ch16/NetworkEx3.java @@ -0,0 +1,37 @@ +import java.net.*; +import java.io.*; + +public class NetworkEx3 { + public static void main(String args[]) { + URL url = null; + String address = "http://www.codechobo.com/sample/hello.html"; + String line = ""; + + try { + url = new URL(address); + URLConnection conn = url.openConnection(); + + System.out.println("conn.toString():"+conn); + System.out.println("getAllowUserInteraction():"+conn.getAllowUserInteraction()); + System.out.println("getConnectTimeout():"+conn.getConnectTimeout()); + System.out.println("getContent():"+conn.getContent()); + System.out.println("getContentEncoding():"+conn.getContentEncoding()); + System.out.println("getContentLength():"+conn.getContentLength()); + System.out.println("getContentType():"+conn.getContentType()); + System.out.println("getDate():"+conn.getDate()); + System.out.println("getDefaultAllowUserInteraction():"+conn.getDefaultAllowUserInteraction()); + System.out.println("getDefaultUseCaches():"+conn.getDefaultUseCaches()); + System.out.println("getDoInput():"+conn.getDoInput()); + System.out.println("getDoOutput():"+conn.getDoOutput()); + System.out.println("getExpiration():"+conn.getExpiration()); + System.out.println("getHeaderFields():"+conn.getHeaderFields()); + System.out.println("getIfModifiedSince():"+conn.getIfModifiedSince()); + System.out.println("getLastModified():"+conn.getLastModified()); + System.out.println("getReadTimeout():"+conn.getReadTimeout()); + System.out.println("getURL():"+conn.getURL()); + System.out.println("getUseCaches():"+conn.getUseCaches()); + } catch(Exception e) { + e.printStackTrace(); + } + } // main +} diff --git a/source/ch16/NetworkEx4.java b/source/ch16/NetworkEx4.java new file mode 100644 index 0000000..c7ad4b7 --- /dev/null +++ b/source/ch16/NetworkEx4.java @@ -0,0 +1,24 @@ +import java.net.*; +import java.io.*; + +public class NetworkEx4 { + public static void main(String args[]) { + URL url = null; + BufferedReader input = null; + String address = "http://www.codechobo.com/sample/hello.html"; + String line = ""; + + try { + url = new URL(address); + + input = new BufferedReader(new InputStreamReader(url.openStream())); + + while((line=input.readLine()) !=null) { + System.out.println(line); + } + input.close(); + } catch(Exception e) { + e.printStackTrace(); + } + } +} diff --git a/source/ch16/NetworkEx5.java b/source/ch16/NetworkEx5.java new file mode 100644 index 0000000..f0aef0f --- /dev/null +++ b/source/ch16/NetworkEx5.java @@ -0,0 +1,27 @@ +import java.net.*; +import java.io.*; + +public class NetworkEx5 { + public static void main(String args[]) { + URL url = null; + InputStream in = null; + FileOutputStream out = null; + String address = "http://www.codechobo.com/book/src/javajungsuk_src.zip"; + + int ch = 0; + + try { + url = new URL(address); + in = url.openStream(); + out = new FileOutputStream("javajungsuk_src.zip"); + + while((ch=in.read()) !=-1) { + out.write(ch); + } + in.close(); + out.close(); + } catch(Exception e) { + e.printStackTrace(); + } + } // main +} diff --git a/source/ch16/TcpIpClient.java b/source/ch16/TcpIpClient.java new file mode 100644 index 0000000..f317061 --- /dev/null +++ b/source/ch16/TcpIpClient.java @@ -0,0 +1,33 @@ +import java.net.*; +import java.io.*; + +public class TcpIpClient { + public static void main(String args[]) { + try { + String serverIp = "127.0.0.1"; + + System.out.println("¼­¹ö¿¡ ¿¬°áÁßÀÔ´Ï´Ù. ¼­¹öIP :" + serverIp); + // ¼ÒÄÏÀ» »ý¼ºÇÏ¿© ¿¬°áÀ» ¿äûÇÑ´Ù. + Socket socket = new Socket(serverIp, 7777); + + // ¼ÒÄÏÀÇ ÀԷ½ºÆ®¸²À» ¾ò´Â´Ù. + InputStream in = socket.getInputStream(); + DataInputStream dis = new DataInputStream(in); + + // ¼ÒÄÏÀ¸·Î ºÎÅÍ ¹ÞÀº µ¥ÀÌÅ͸¦ Ãâ·ÂÇÑ´Ù. + System.out.println("¼­¹ö·ÎºÎÅÍ ¹ÞÀº ¸Þ½ÃÁö :"+dis.readUTF()); + System.out.println("¿¬°áÀ» Á¾·áÇÕ´Ï´Ù."); + + // ½ºÆ®¸²°ú ¼ÒÄÏÀ» ´Ý´Â´Ù. + dis.close(); + socket.close(); + System.out.println("¿¬°áÀÌ Á¾·áµÇ¾ú½À´Ï´Ù."); + } catch(ConnectException ce) { + ce.printStackTrace(); + } catch(IOException ie) { + ie.printStackTrace(); + } catch(Exception e) { + e.printStackTrace(); + } + } // main +} // class diff --git a/source/ch16/TcpIpClient5.java b/source/ch16/TcpIpClient5.java new file mode 100644 index 0000000..5b4cac8 --- /dev/null +++ b/source/ch16/TcpIpClient5.java @@ -0,0 +1,26 @@ +import java.net.*; +import java.io.*; + +public class TcpIpClient5 { + public static void main(String args[]) { + try { + String serverIp = "127.0.0.1"; + + // ¼ÒÄÏÀ» »ý¼ºÇÏ¿© ¿¬°áÀ» ¿äûÇÑ´Ù. + Socket socket = new Socket(serverIp, 7777); + + System.out.println("¼­¹ö¿¡ ¿¬°áµÇ¾ú½À´Ï´Ù."); + Sender sender = new Sender(socket); + Receiver receiver = new Receiver(socket); + + sender.start(); + receiver.start(); + } catch(ConnectException ce) { + ce.printStackTrace(); + } catch(IOException ie) { + ie.printStackTrace(); + } catch(Exception e) { + e.printStackTrace(); + } + } // main +} // class diff --git a/source/ch16/TcpIpMultichatClient.java b/source/ch16/TcpIpMultichatClient.java new file mode 100644 index 0000000..a0bc0e9 --- /dev/null +++ b/source/ch16/TcpIpMultichatClient.java @@ -0,0 +1,72 @@ +import java.net.*; +import java.io.*; +import java.util.Scanner; + +public class TcpIpMultichatClient { + public static void main(String args[]) { + if(args.length!=1) { + System.out.println("USAGE: java TcpIpMultichatClient ´ëÈ­¸í"); + System.exit(0); + } + + try { + String serverIp = "127.0.0.1"; + // ¼ÒÄÏÀ» »ý¼ºÇÏ¿© ¿¬°áÀ» ¿äûÇÑ´Ù. + Socket socket = new Socket(serverIp, 7777); + System.out.println("¼­¹ö¿¡ ¿¬°áµÇ¾ú½À´Ï´Ù."); + Thread sender = new Thread(new ClientSender(socket, args[0])); + Thread receiver = new Thread(new ClientReceiver(socket)); + + sender.start(); + receiver.start(); + } catch(ConnectException ce) { + ce.printStackTrace(); + } catch(Exception e) {} + } // main + + static class ClientSender extends Thread { + Socket socket; + DataOutputStream out; + String name; + + ClientSender(Socket socket, String name) { + this.socket = socket; + try { + out = new DataOutputStream(socket.getOutputStream()); + this.name = name; + } catch(Exception e) {} + } + + public void run() { + Scanner scanner = new Scanner(System.in); + try { + if(out!=null) { + out.writeUTF(name); + } + + while(out!=null) { + out.writeUTF("["+name+"]"+scanner.nextLine()); } + } catch(IOException e) {} + } // run() + } // ClientSender + + static class ClientReceiver extends Thread { + Socket socket; + DataInputStream in; + + ClientReceiver(Socket socket) { + this.socket = socket; + try { + in = new DataInputStream(socket.getInputStream()); + } catch(IOException e) {} + } + + public void run() { + while(in!=null) { + try { + System.out.println(in.readUTF()); + } catch(IOException e) {} + } + } // run + } // ClientReceiver +} // class diff --git a/source/ch16/TcpIpMultichatServer.java b/source/ch16/TcpIpMultichatServer.java new file mode 100644 index 0000000..8b34fa0 --- /dev/null +++ b/source/ch16/TcpIpMultichatServer.java @@ -0,0 +1,81 @@ +import java.net.*; +import java.io.*; +import java.util.*; + +public class TcpIpMultichatServer { + HashMap clients; + + TcpIpMultichatServer() { + clients = new HashMap(); + Collections.synchronizedMap(clients); + } + + public void start() { + ServerSocket serverSocket = null; + Socket socket = null; + + try { + serverSocket = new ServerSocket(7777); + System.out.println("¼­¹ö°¡ ½ÃÀ۵Ǿú½À´Ï´Ù."); + + while(true) { + socket = serverSocket.accept(); + System.out.println("["+socket.getInetAddress()+":"+socket.getPort()+"]"+"¿¡¼­ Á¢¼ÓÇÏ¿´½À´Ï´Ù."); + ServerReceiver thread = new ServerReceiver(socket); + thread.start(); + } + } catch(Exception e) { + e.printStackTrace(); + } + } // start() + + void sendToAll(String msg) { + Iterator it = clients.keySet().iterator(); + + while(it.hasNext()) { + try { + DataOutputStream out = (DataOutputStream)clients.get(it.next()); + out.writeUTF(msg); + } catch(IOException e){} + } // while + } // sendToAll + + public static void main(String args[]) { + new TcpIpMultichatServer().start(); + } + class ServerReceiver extends Thread { + Socket socket; + DataInputStream in; + DataOutputStream out; + + ServerReceiver(Socket socket) { + this.socket = socket; + try { + in = new DataInputStream(socket.getInputStream()); + out = new DataOutputStream(socket.getOutputStream()); + } catch(IOException e) {} + } + + public void run() { + String name = ""; + try { + name = in.readUTF(); + sendToAll("#"+name+"´ÔÀÌ µé¾î¿À¼Ì½À´Ï´Ù."); + + clients.put(name, out); + System.out.println("ÇöÀç ¼­¹öÁ¢¼ÓÀÚ ¼ö´Â "+ clients.size()+"ÀÔ´Ï´Ù."); + + while(in!=null) { + sendToAll(in.readUTF()); + } + } catch(IOException e) { + // ignore + } finally { + sendToAll("#"+name+"´ÔÀÌ ³ª°¡¼Ì½À´Ï´Ù."); + clients.remove(name); + System.out.println("["+socket.getInetAddress() +":"+socket.getPort()+"]"+"¿¡¼­ Á¢¼ÓÀ» Á¾·áÇÏ¿´½À´Ï´Ù."); + System.out.println("ÇöÀç ¼­¹öÁ¢¼ÓÀÚ ¼ö´Â "+ clients.size()+"ÀÔ´Ï´Ù."); + } // try + } // run + } // ReceiverThread +} // class diff --git a/source/ch16/TcpIpServer.java b/source/ch16/TcpIpServer.java new file mode 100644 index 0000000..2b5407e --- /dev/null +++ b/source/ch16/TcpIpServer.java @@ -0,0 +1,49 @@ +import java.net.*; +import java.io.*; +import java.util.Date; +import java.text.SimpleDateFormat; + +public class TcpIpServer { + public static void main(String args[]) { + ServerSocket serverSocket = null; + + try { + // ¼­¹ö¼ÒÄÏÀ» »ý¼ºÇÏ¿© 7777¹ø Æ÷Æ®¿Í °áÇÕ(bind)½ÃŲ´Ù. + serverSocket = new ServerSocket(7777); + System.out.println(getTime()+"¼­¹ö°¡ ÁغñµÇ¾ú½À´Ï´Ù."); + + } catch(IOException e) { + e.printStackTrace(); + } + + while(true) { + try { + System.out.println(getTime()+"¿¬°á¿äûÀ» ±â´Ù¸³´Ï´Ù."); + // ¼­¹ö¼ÒÄÏÀº Ŭ¶óÀ̾ðÆ®ÀÇ ¿¬°á¿äûÀÌ ¿Ã ¶§±îÁö ½ÇÇàÀ» ¸ØÃß°í °è¼Ó ±â´Ù¸°´Ù. + // Ŭ¶óÀ̾ðÆ®ÀÇ ¿¬°á¿äûÀÌ ¿À¸é Ŭ¶óÀ̾ðÆ® ¼ÒÄÏ°ú Åë½ÅÇÒ »õ·Î¿î ¼ÒÄÏÀ» »ý¼ºÇÑ´Ù. + Socket socket = serverSocket.accept(); + System.out.println(getTime()+ socket.getInetAddress() + "·ÎºÎÅÍ ¿¬°á¿äûÀÌ µé¾î¿Ô½À´Ï´Ù."); + + // ¼ÒÄÏÀÇ Ãâ·Â½ºÆ®¸²À» ¾ò´Â´Ù. + OutputStream out = socket.getOutputStream(); + DataOutputStream dos = new DataOutputStream(out); + + // ¿ø°Ý ¼ÒÄÏ(remote socket)¿¡ µ¥ÀÌÅ͸¦ º¸³½´Ù. + dos.writeUTF("[Notice] Test Message1 from Server."); + System.out.println(getTime()+"µ¥ÀÌÅ͸¦ Àü¼ÛÇß½À´Ï´Ù."); + + // ½ºÆ®¸²°ú ¼ÒÄÏÀ» ´Ý¾ÆÁØ´Ù. + dos.close(); + socket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } // while + } // main + + // ÇöÀç½Ã°£À» ¹®ÀÚ¿­·Î ¹ÝȯÇÏ´Â ÇÔ¼ö + static String getTime() { + SimpleDateFormat f = new SimpleDateFormat("[hh:mm:ss]"); + return f.format(new Date()); + } +} // class diff --git a/source/ch16/TcpIpServer2.java b/source/ch16/TcpIpServer2.java new file mode 100644 index 0000000..ef8f4c4 --- /dev/null +++ b/source/ch16/TcpIpServer2.java @@ -0,0 +1,51 @@ +import java.net.*; +import java.io.*; +import java.util.Date; +import java.text.SimpleDateFormat; + +public class TcpIpServer2 { + public static void main(String args[]) { + ServerSocket serverSocket = null; + + try { + // ¼­¹ö¼ÒÄÏÀ» »ý¼ºÇÏ¿© 7777¹ø Æ÷Æ®¿Í °áÇÕ(bind)½ÃŲ´Ù. + serverSocket = new ServerSocket(7777); + System.out.println(getTime()+"¼­¹ö°¡ ÁغñµÇ¾ú½À´Ï´Ù."); + + } catch(IOException e) { + e.printStackTrace(); + } + + while(true) { + try { + // ¼­¹ö¼ÒÄÏ + System.out.println(getTime()+"¿¬°á¿äûÀ» ±â´Ù¸³´Ï´Ù."); + Socket socket = serverSocket.accept(); + System.out.println(getTime()+ socket.getInetAddress() + "·ÎºÎÅÍ ¿¬°á¿äûÀÌ µé¾î¿Ô½À´Ï´Ù."); + + System.out.println("getPort():"+socket.getPort()); + System.out.println("getLocalPort():" +socket.getLocalPort()); + + // ¼ÒÄÏÀÇ Ãâ·Â½ºÆ®¸²À» ¾ò´Â´Ù. + OutputStream out = socket.getOutputStream(); + DataOutputStream dos = new DataOutputStream(out); + + // ¿ø°Ý ¼ÒÄÏ(remote socket)¿¡ µ¥ÀÌÅ͸¦ º¸³½´Ù. + dos.writeUTF("[Notice] Test Message1 from Server."); + System.out.println(getTime()+"µ¥ÀÌÅ͸¦ Àü¼ÛÇß½À´Ï´Ù."); + + // ½ºÆ®¸²°ú ¼ÒÄÏÀ» ´Ý¾ÆÁØ´Ù. + dos.close(); + socket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } // while + } // main + + // ÇöÀç½Ã°£À» ¹®ÀÚ¿­·Î ¹ÝȯÇÏ´Â ÇÔ¼ö + static String getTime() { + SimpleDateFormat f = new SimpleDateFormat("[hh:mm:ss]"); + return f.format(new Date()); + } +} // class diff --git a/source/ch16/TcpIpServer3.java b/source/ch16/TcpIpServer3.java new file mode 100644 index 0000000..b5639df --- /dev/null +++ b/source/ch16/TcpIpServer3.java @@ -0,0 +1,55 @@ +import java.net.*; +import java.io.*; +import java.util.Date; +import java.text.SimpleDateFormat; + +public class TcpIpServer3 { + public static void main(String args[]) { + ServerSocket serverSocket = null; + + try { + // ¼­¹ö¼ÒÄÏÀ» »ý¼ºÇÏ¿© 7777¹ø Æ÷Æ®¿Í °áÇÕ(bind)½ÃŲ´Ù. + serverSocket = new ServerSocket(7777); + System.out.println(getTime()+"¼­¹ö°¡ ÁغñµÇ¾ú½À´Ï´Ù."); + + } catch(IOException e) { + e.printStackTrace(); + } + + while(true) { + try { + // ¼­¹ö¼ÒÄÏ + System.out.println(getTime()+"¿¬°á¿äûÀ» ±â´Ù¸³´Ï´Ù."); + + // ¿äû´ë±â½Ã°£À» 5ÃÊ·Î ¼³Á¤ÇÑ´Ù. + // 5Ãʵ¿¾È Á¢¼Ó¿äûÀÌ ¾øÀ¸¸é SocketTimeoutExceptionÀÌ ¹ß»ýÇÑ´Ù. + serverSocket.setSoTimeout(5*1000); + Socket socket = serverSocket.accept(); + System.out.println(getTime()+ socket.getInetAddress() + "·ÎºÎÅÍ ¿¬°á¿äûÀÌ µé¾î¿Ô½À´Ï´Ù."); + + // ¼ÒÄÏÀÇ Ãâ·Â½ºÆ®¸²À» ¾ò´Â´Ù. + OutputStream out = socket.getOutputStream(); + DataOutputStream dos = new DataOutputStream(out); + + // ¿ø°Ý ¼ÒÄÏ(remote socket)¿¡ µ¥ÀÌÅ͸¦ º¸³½´Ù. + dos.writeUTF("[Notice] Test Message1 from Server."); + System.out.println(getTime()+"µ¥ÀÌÅ͸¦ Àü¼ÛÇß½À´Ï´Ù."); + + // ½ºÆ®¸²°ú ¼ÒÄÏÀ» ´Ý¾ÆÁØ´Ù. + dos.close(); + socket.close(); + } catch (SocketTimeoutException e) { + System.out.println("ÁöÁ¤µÈ ½Ã°£µ¿¾È Á¢¼Ó¿äûÀÌ ¾ø¾î¼­ ¼­¹ö¸¦ Á¾·áÇÕ´Ï´Ù."); + System.exit(0); + } catch (IOException e) { + e.printStackTrace(); + } + } // while + } // main + + // ÇöÀç½Ã°£À» ¹®ÀÚ¿­·Î ¹ÝȯÇÏ´Â ÇÔ¼ö + static String getTime() { + SimpleDateFormat f = new SimpleDateFormat("[hh:mm:ss]"); + return f.format(new Date()); + } +} // class diff --git a/source/ch16/TcpIpServer4.java b/source/ch16/TcpIpServer4.java new file mode 100644 index 0000000..f58c167 --- /dev/null +++ b/source/ch16/TcpIpServer4.java @@ -0,0 +1,67 @@ +import java.net.*; +import java.io.*; +import java.util.Date; +import java.text.SimpleDateFormat; + +public class TcpIpServer4 implements Runnable { + ServerSocket serverSocket; + Thread[] threadArr; + + public static void main(String args[]) { + // 5°³ÀÇ ¾²·¹µå¸¦ »ý¼ºÇÏ´Â ¼­¹ö¸¦ »ý¼ºÇÑ´Ù. + TcpIpServer4 server = new TcpIpServer4(5); + server.start(); + } // main + + public TcpIpServer4(int num) { + try { + // ¼­¹ö¼ÒÄÏÀ» »ý¼ºÇÏ¿© 7777¹ø Æ÷Æ®¿Í °áÇÕ(bind)½ÃŲ´Ù. + serverSocket = new ServerSocket(7777); + System.out.println(getTime()+"¼­¹ö°¡ ÁغñµÇ¾ú½À´Ï´Ù."); + + threadArr = new Thread[num]; + } catch(IOException e) { + e.printStackTrace(); + } + } + + public void start() { + for(int i=0; i < threadArr.length; i++) { + threadArr[i] = new Thread(this); + threadArr[i].start(); + } + } + + public void run() { + while(true) { + try { + System.out.println(getTime()+ "°¡ ¿¬°á¿äûÀ» ±â´Ù¸³´Ï´Ù."); + + Socket socket = serverSocket.accept(); + System.out.println(getTime()+ socket.getInetAddress() + "·ÎºÎÅÍ ¿¬°á¿äûÀÌ µé¾î¿Ô½À´Ï´Ù."); + + // ¼ÒÄÏÀÇ Ãâ·Â½ºÆ®¸²À» ¾ò´Â´Ù. + OutputStream out = socket.getOutputStream(); + DataOutputStream dos = new DataOutputStream(out); + + // ¿ø°Ý ¼ÒÄÏ(remote socket)¿¡ µ¥ÀÌÅ͸¦ º¸³½´Ù. + dos.writeUTF("[Notice] Test Message1 from Server."); + System.out.println(getTime()+"µ¥ÀÌÅ͸¦ Àü¼ÛÇß½À´Ï´Ù."); + + // ½ºÆ®¸²°ú ¼ÒÄÏÀ» ´Ý¾ÆÁØ´Ù. + dos.close(); + socket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } // while + } // run + + // ÇöÀç½Ã°£À» ¹®ÀÚ¿­·Î ¹ÝȯÇÏ´Â ÇÔ¼ö + static String getTime() { + String name = Thread.currentThread().getName(); + SimpleDateFormat f = new SimpleDateFormat("[hh:mm:ss]"); + + return f.format(new Date()) + name ; + } +} // class diff --git a/source/ch16/TcpIpServer5.java b/source/ch16/TcpIpServer5.java new file mode 100644 index 0000000..6ce20eb --- /dev/null +++ b/source/ch16/TcpIpServer5.java @@ -0,0 +1,70 @@ +import java.net.*; +import java.io.*; +import java.util.Scanner; + +public class TcpIpServer5 { + public static void main(String args[]) { + ServerSocket serverSocket = null; + Socket socket = null; + + try { + // ¼­¹ö¼ÒÄÏÀ» »ý¼ºÇÏ¿© 7777¹ø Æ÷Æ®¿Í °áÇÕ(bind)½ÃŲ´Ù. + serverSocket = new ServerSocket(7777); + System.out.println("¼­¹ö°¡ ÁغñµÇ¾ú½À´Ï´Ù."); + + socket = serverSocket.accept(); + + Sender sender = new Sender(socket); + Receiver receiver = new Receiver(socket); + + sender.start(); + receiver.start(); + } catch (Exception e) { + e.printStackTrace(); + } + } // main +} // class + +class Sender extends Thread { + Socket socket; + DataOutputStream out; + String name; + + Sender(Socket socket) { + this.socket = socket; + try { + out = new DataOutputStream(socket.getOutputStream()); + name = "["+socket.getInetAddress()+":"+socket.getPort()+"]"; + } catch(Exception e) {} + } + + public void run() { + Scanner scanner = new Scanner(System.in); + while(out!=null) { + try { + out.writeUTF(name+scanner.nextLine()); + } catch(IOException e) {} + } + } // run() +} + +class Receiver extends Thread { + Socket socket; + DataInputStream in; + + Receiver(Socket socket) { + this.socket = socket; + try { + in = new DataInputStream(socket.getInputStream()); + } catch(IOException e) {} + + } + + public void run() { + while(in!=null) { + try { + System.out.println(in.readUTF()); + } catch(IOException e) {} + } + } // run +} diff --git a/source/ch16/UdpClient.java b/source/ch16/UdpClient.java new file mode 100644 index 0000000..8feb867 --- /dev/null +++ b/source/ch16/UdpClient.java @@ -0,0 +1,30 @@ +import java.net.*; +import java.io.*; + +public class UdpClient { + public void start() throws IOException, UnknownHostException { + DatagramSocket datagramSocket = new DatagramSocket(); + InetAddress serverAddress = InetAddress.getByName("127.0.0.1"); + + // µ¥ÀÌÅÍ°¡ ÀúÀåµÉ °ø°£À¸·Î byte¹è¿­À» »ý¼ºÇÑ´Ù. + byte[] msg = new byte[100]; + + DatagramPacket outPacket = new DatagramPacket(msg, 1, serverAddress, 7777); + DatagramPacket inPacket = new DatagramPacket(msg, msg.length); + + datagramSocket.send(outPacket); // DatagramPacketÀ» Àü¼ÛÇÑ´Ù. + datagramSocket.receive(inPacket); // DatagramPacketÀ» ¼ö½ÅÇÑ´Ù. + + System.out.println("current server time :" + new String(inPacket.getData())); + + datagramSocket.close(); + } // start() + + public static void main(String args[]) { + try { + new UdpClient().start(); + } catch(Exception e) { + e.printStackTrace(); + } + } // main +} diff --git a/source/ch16/UdpServer.java b/source/ch16/UdpServer.java new file mode 100644 index 0000000..b0a3438 --- /dev/null +++ b/source/ch16/UdpServer.java @@ -0,0 +1,44 @@ +import java.net.*; +import java.io.*; +import java.util.Date; +import java.text.SimpleDateFormat; + +public class UdpServer { + public void start() throws IOException { + // Æ÷Æ® 7777¹øÀ» »ç¿ëÇÏ´Â ¼ÒÄÏÀ» »ý¼ºÇÑ´Ù. + DatagramSocket socket = new DatagramSocket(7777); + DatagramPacket inPacket, outPacket; + + byte[] inMsg = new byte[10]; + byte[] outMsg; + + while(true) { + // µ¥ÀÌÅ͸¦ ¼ö½ÅÇϱâ À§ÇÑ ÆÐŶÀ» »ý¼ºÇÑ´Ù. + inPacket = new DatagramPacket(inMsg, inMsg.length); + + // ÆÐŶÀ» ÅëÇØ µ¥ÀÌÅ͸¦ ¼ö½Å(receive)ÇÑ´Ù. + socket.receive(inPacket); + + // ¼ö½ÅÇÑ ÆÐŶÀ¸·Î ºÎÅÍ clientÀÇ IPÁÖ¼Ò¿Í Port¸¦ ¾ò´Â´Ù. + InetAddress address = inPacket.getAddress(); + int port = inPacket.getPort(); + + // ¼­¹öÀÇ ÇöÀç ½Ã°£À» ½ÃºÐÃÊ ÇüÅÂ([hh:mm:ss])·Î ¹ÝȯÇÑ´Ù. + SimpleDateFormat sdf = new SimpleDateFormat("[hh:mm:ss]"); + String time = sdf.format(new Date()); + outMsg = time.getBytes(); // timeÀ» byte¹è¿­·Î º¯È¯ÇÑ´Ù. + + // ÆÐŶÀ» »ý¼ºÇؼ­ client¿¡°Ô Àü¼Û(send)ÇÑ´Ù. + outPacket = new DatagramPacket(outMsg, outMsg.length, address, port); + socket.send(outPacket); + } + } // start() + + public static void main(String args[]) { + try { + new UdpServer().start(); // UDP¼­¹ö¸¦ ½ÇÇà½ÃŲ´Ù. + } catch (IOException e) { + e.printStackTrace(); + } + } // main +} diff --git a/source/ch2/CastingEx1.java b/source/ch2/CastingEx1.java new file mode 100644 index 0000000..6178ae2 --- /dev/null +++ b/source/ch2/CastingEx1.java @@ -0,0 +1,9 @@ +class CastingEx1 { + public static void main(String[] args) { + double d = 85.4; + int score = (int)d; + + System.out.println("score="+score); + System.out.println("d="+d); + } +} diff --git a/source/ch2/CastingEx2.java b/source/ch2/CastingEx2.java new file mode 100644 index 0000000..0cfbd61 --- /dev/null +++ b/source/ch2/CastingEx2.java @@ -0,0 +1,21 @@ +class CastingEx2 { + public static void main(String[] args) { + int i = 10; + byte b = (byte)i; + System.out.printf("[int -> byte] i=%d -> b=%d%n", i, b); + + i = 300; + b = (byte)i; + System.out.printf("[int -> byte] i=%d -> b=%d%n", i, b); + + b = 10; + i = (int)b; + System.out.printf("[byte -> int] b=%d -> i=%d%n", b, i); + + b = -2; + i = (int)b; + System.out.printf("[byte -> int] b=%d -> i=%d%n", b, i); + + System.out.println("i="+Integer.toBinaryString(i)); + } +} diff --git a/source/ch2/CastingEx3.java b/source/ch2/CastingEx3.java new file mode 100644 index 0000000..d392d2d --- /dev/null +++ b/source/ch2/CastingEx3.java @@ -0,0 +1,11 @@ +class CastingEx3 { + public static void main(String[] args) { + float f = 9.1234567f; + double d = 9.1234567; + double d2 = (double)f; + + System.out.printf("f =%20.18f\n", f); + System.out.printf("d =%20.18f\n", d); + System.out.printf("d2=%20.18f\n", d2); + } +} diff --git a/source/ch2/CastingEx4.java b/source/ch2/CastingEx4.java new file mode 100644 index 0000000..e7d3d5f --- /dev/null +++ b/source/ch2/CastingEx4.java @@ -0,0 +1,18 @@ +class CastingEx4 { + public static void main(String[] args) { + int i = 91234567; // 8ÀÚ¸®ÀÇ 10Áø¼ö + float f = (float)i; // int¸¦ float·Î Çüº¯È¯ + int i2 = (int)f; // float¸¦ ´Ù½Ã int·Î Çüº¯È¯ + + double d = (double)i; // int¸¦ double·Î Çüº¯È¯ + int i3 = (int)d; // doubleÀ» ´Ù½Ã int·Î Çüº¯È¯ + + float f2 = 1.666f; + int i4 = (int)f2; + + System.out.printf("i=%d\n", i); + System.out.printf("f=%f i2=%d\n", f, i2); + System.out.printf("d=%f i3=%d\n", d, i3); + System.out.printf("(int)%f=%d\n", f2, i4); + } +} diff --git a/source/ch2/CharToCode.java b/source/ch2/CharToCode.java new file mode 100644 index 0000000..cf6d45c --- /dev/null +++ b/source/ch2/CharToCode.java @@ -0,0 +1,11 @@ +class CharToCode { + public static void main(String[] args) { + char ch = 'A'; // char ch = 65; + int code = (int)ch; // ch¿¡ ÀúÀåµÈ °ªÀ» intŸÀÔÀ¸·Î º¯È¯ÇÏ¿© ÀúÀåÇÑ´Ù. + + System.out.printf("%c=%d(%#X)%n", ch, code, code); + + char hch = '°¡'; // char hch = 0xAC00; + System.out.printf("%c=%d(%#X)%n", hch, (int)hch, (int)hch); + } +} diff --git a/source/ch2/FloatEx1.java b/source/ch2/FloatEx1.java new file mode 100644 index 0000000..13a672a --- /dev/null +++ b/source/ch2/FloatEx1.java @@ -0,0 +1,13 @@ +class FloatEx1 { + public static void main(String[] args) { + float f = 9.12345678901234567890f; + float f2 = 1.2345678901234567890f; + double d = 9.12345678901234567890d; + + System.out.printf(" 123456789012345678901234%n"); + System.out.printf("f : %f%n", f); // ¼Ò¼öÁ¡ ÀÌÇÏ 6°ÀÚ¸®±îÁö Ãâ·Â. + System.out.printf("f : %24.20f%n", f); + System.out.printf("f2 : %24.20f%n", f2); + System.out.printf("d : %24.20f%n", d); + } +} diff --git a/source/ch2/FloatToBinEx.java b/source/ch2/FloatToBinEx.java new file mode 100644 index 0000000..4e001d6 --- /dev/null +++ b/source/ch2/FloatToBinEx.java @@ -0,0 +1,9 @@ +class FloatToBinEx { + public static void main(String args[]) { + float f = -9.1234567f; + int i = Float.floatToIntBits(f); + + System.out.printf("%f%n", f); + System.out.printf("%X%n", i); // 16Áø¼ö·Î Ãâ·Â + } // mainÀÇ ³¡ +} diff --git a/source/ch2/OverflowEx.java b/source/ch2/OverflowEx.java new file mode 100644 index 0000000..bc84538 --- /dev/null +++ b/source/ch2/OverflowEx.java @@ -0,0 +1,17 @@ +class OverflowEx { + public static void main(String[] args) { + short sMin = -32768; + short sMax = 32767; + char cMin = 0; + char cMax = 65535; + + System.out.println("sMin = " + sMin); + System.out.println("sMin-1= " + (short)(sMin-1)); + System.out.println("sMax = " + sMax); + System.out.println("sMax+1= " + (short)(sMax+1)); + System.out.println("cMin = " + (int)cMin); + System.out.println("cMin-1= " + (int)--cMin); + System.out.println("cMax = " + (int)cMax); + System.out.println("cMax+1= " + (int)++cMax); + } +} diff --git a/source/ch2/PrintfEx1.java b/source/ch2/PrintfEx1.java new file mode 100644 index 0000000..f19d9cd --- /dev/null +++ b/source/ch2/PrintfEx1.java @@ -0,0 +1,27 @@ +class PrintfEx1 { + public static void main(String[] args) { + byte b = 1; + short s = 2; + char c = 'A'; + + int finger = 10; + long big = 100_000_000_000L; + long hex = 0xFFFF_FFFF_FFFF_FFFFL ; // long hex = 0xFFFFFFFFFFFFFFFFL; + + int octNum = 010; // 8Áø¼ö 10, 10Áø¼ö·Î´Â 8 + int hexNum = 0x10; // 16Áø¼ö 10, 10Áø¼ö·Î´Â 16 + int binNum = 0b10; // 2Áø¼ö 10, 10Áø¼ö·Î´Â 2 + + System.out.printf("b=%d%n", b); + System.out.printf("s=%d%n", s); + System.out.printf("c=%c, %d %n", c, (int)c); + System.out.printf("finger=[%5d]%n", finger); + System.out.printf("finger=[%-5d]%n", finger); + System.out.printf("finger=[%05d]%n", finger); + System.out.printf("big=%d%n", big); + System.out.printf("hex=%#x%n", hex); // '#'Àº Á¢µÎ»ç(16Áø¼ö 0x, 8Áø¼ö 0) + System.out.printf("octNum=%o, %d%n", octNum, octNum); + System.out.printf("hexNum=%x, %d%n", hexNum, hexNum); + System.out.printf("binNum=%s, %d%n", Integer.toBinaryString(binNum), binNum); + } +} diff --git a/source/ch2/PrintfEx2.java b/source/ch2/PrintfEx2.java new file mode 100644 index 0000000..696a41e --- /dev/null +++ b/source/ch2/PrintfEx2.java @@ -0,0 +1,23 @@ +class PrintfEx2 { + public static void main(String[] args) { + String url = "www.codechobo.com"; + + float f1 = .10f; // 0.10, 1.0e-1 + float f2 = 1e1f; // 10.0, 1.0e1, 1.0e+1 + float f3 = 3.14e3f; + double d = 1.23456789; + + System.out.printf("f1=%f, %e, %g%n", f1, f1, f1); + System.out.printf("f2=%f, %e, %g%n", f2, f2, f2); + System.out.printf("f3=%f, %e, %g%n", f3, f3, f3); + + System.out.printf("d=%f%n", d); + System.out.printf("d=%14.10f%n", d); // Àüü 14ÀÚ¸® Áß ¼Ò¼öÁ¡ 10ÀÚ¸® + + System.out.printf("[12345678901234567890]%n"); + System.out.printf("[%s]%n", url); + System.out.printf("[%20s]%n", url); + System.out.printf("[%-20s]%n", url); // ¿À¸¥ÂÊ Á¤·Ä + System.out.printf("[%.8s]%n", url); // ¿ÞÂÊ¿¡¼­ 8±ÛÀÚ¸¸ Ãâ·Â + } +} diff --git a/source/ch2/ScannerEx.java b/source/ch2/ScannerEx.java new file mode 100644 index 0000000..e57d031 --- /dev/null +++ b/source/ch2/ScannerEx.java @@ -0,0 +1,15 @@ +import java.util.*; // Scanner¸¦ »ç¿ëÇϱâ À§ÇØ Ãß°¡ + +class ScannerEx { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + + System.out.print("µÎÀÚ¸® Á¤¼ö¸¦ Çϳª ÀÔ·ÂÇØÁÖ¼¼¿ä.>"); + + String input = scanner.nextLine(); + int num = Integer.parseInt(input); // ÀԷ¹ÞÀº ¹®ÀÚ¿­À» ¼ýÀÚ·Î º¯È¯ + + System.out.println("ÀԷ³»¿ë :"+input); + System.out.printf("num=%d%n", num); + } +} diff --git a/source/ch2/SpecialCharEx.java b/source/ch2/SpecialCharEx.java new file mode 100644 index 0000000..a5a4702 --- /dev/null +++ b/source/ch2/SpecialCharEx.java @@ -0,0 +1,9 @@ +class SpecialCharEx { + public static void main(String[] args) { + System.out.println('\''); // '''ó·³ ÇÒ ¼ö ¾ø´Ù. + System.out.println("abc\t123\b456"); // \b¿¡ ÀÇÇØ 3ÀÌ Áö¿öÁø´Ù. + System.out.println('\n'); // °³Çà(new line)¹®ÀÚ Ãâ·ÂÇÏ°í °³Çà + System.out.println("\"Hello\""); // Å«µû¿ÈÇ¥¸¦ Ãâ·ÂÇÏ·Á¸é ÀÌ·¸°Ô ÇÑ´Ù. + System.out.println("c:\\"); + } +} diff --git a/source/ch2/StringEx.java b/source/ch2/StringEx.java new file mode 100644 index 0000000..b9e0d93 --- /dev/null +++ b/source/ch2/StringEx.java @@ -0,0 +1,16 @@ +class StringEx { + public static void main(String[] args) { + String name = "Ja" + "va"; + String str = name + 8.0; + + System.out.println(name); + System.out.println(str); + System.out.println(7 + " "); + System.out.println(" " + 7); + System.out.println(7 + ""); + System.out.println("" + 7); + System.out.println("" + ""); + System.out.println(7 + 7 + ""); + System.out.println("" + 7 + 7); + } +} diff --git a/source/ch2/VarEx1.java b/source/ch2/VarEx1.java new file mode 100644 index 0000000..66b4d6d --- /dev/null +++ b/source/ch2/VarEx1.java @@ -0,0 +1,15 @@ +class VarEx1 { + public static void main(String[] args) { + int year = 0; + int age = 14; + + System.out.println(year); + System.out.println(age); + + year = age + 2000; // º¯¼ö ageÀÇ °ª¿¡ 2000À» ´õÇؼ­ º¯¼ö year¿¡ ÀúÀå + age = age + 1; // º¯¼ö age¿¡ ÀúÀåµÈ °ªÀ» 1Áõ°¡½ÃŲ´Ù. + + System.out.println(year); + System.out.println(age); + } +} diff --git a/source/ch2/VarEx2.java b/source/ch2/VarEx2.java new file mode 100644 index 0000000..fe8e57f --- /dev/null +++ b/source/ch2/VarEx2.java @@ -0,0 +1,15 @@ +class VarEx2 { + public static void main(String[] args) { + int x = 10; + int y = 20; + int tmp = 0; + + System.out.println("x:"+ x + " y:" + y); + + tmp = x; + x = y; + y = tmp; + + System.out.println("x:"+ x + " y:" + y); + } +} diff --git a/source/ch3/OperatorEx1.java b/source/ch3/OperatorEx1.java new file mode 100644 index 0000000..4508dc8 --- /dev/null +++ b/source/ch3/OperatorEx1.java @@ -0,0 +1,11 @@ +class OperatorEx1 { + public static void main(String args[]) { + int i=5; + i++; // i=i+1;°ú °°Àº ÀǹÌÀÌ´Ù. ++i;·Î ¹Ù²ã ½áµµ °á°ú´Â °°´Ù. + System.out.println(i); + + i=5; // °á°ú¸¦ ºñ±³Çϱâ À§ÇØ i°ªÀ» ´Ù½Ã 5·Î º¯°æ. + ++i; + System.out.println(i); + } +} diff --git a/source/ch3/OperatorEx10.java b/source/ch3/OperatorEx10.java new file mode 100644 index 0000000..a7289d0 --- /dev/null +++ b/source/ch3/OperatorEx10.java @@ -0,0 +1,11 @@ +class OperatorEx10 { + public static void main(String args[]) { + int a = 1000000; + + int result1 = a * a / a; // 1000000 * 1000000 / 1000000 + int result2 = a / a * a; // 1000000 / 1000000 * 1000000 + + System.out.printf("%d * %d / %d = %d\n", a, a, a, result1); + System.out.printf("%d / %d * %d = %d\n", a, a, a, result2); + } +} diff --git a/source/ch3/OperatorEx11.java b/source/ch3/OperatorEx11.java new file mode 100644 index 0000000..c65ec85 --- /dev/null +++ b/source/ch3/OperatorEx11.java @@ -0,0 +1,16 @@ +class OperatorEx11 { + public static void main(String args[]) { + char a = 'a'; + char d = 'd'; + + char zero = '0'; + char two = '2'; + + System.out.printf("'%c' - '%c' = %d\n", d, a, d - a); // 'd' - 'a' = 3 + System.out.printf("'%c' - '%c' = %d\n", two, zero, two - zero); + System.out.printf("'%c'=%d\n", a, (int)a); + System.out.printf("'%c'=%d\n", d, (int)d); + System.out.printf("'%c'=%d\n", zero, (int)zero); + System.out.printf("'%c'=%d\n", two, (int)two); + } +} diff --git a/source/ch3/OperatorEx12.java b/source/ch3/OperatorEx12.java new file mode 100644 index 0000000..3de2f9d --- /dev/null +++ b/source/ch3/OperatorEx12.java @@ -0,0 +1,17 @@ +class OperatorEx12 { + public static void main(String[] args) { + char c1 = 'a'; // c1¿¡´Â ¹®ÀÚ 'a'ÀÇ Äڵ尪ÀÎ 97ÀÌ ÀúÀåµÈ´Ù. + char c2 = c1; // c1¿¡ ÀúÀåµÇ¾î ÀÖ´Â °ªÀÌ c2¿¡ ÀúÀåµÈ´Ù. + char c3 =' '; // c3¸¦ °ø¹éÀ¸·Î ÃʱâÈ­ ÇÑ´Ù. + + int i = c1 + 1; // 'a'+1 ¡æ 97+1 ¡æ 98 + + c3 = (char)(c1 + 1); + c2++; + c2++; + + System.out.println("i=" + i); + System.out.println("c2=" + c2); + System.out.println("c3=" + c3); + } +} diff --git a/source/ch3/OperatorEx13.java b/source/ch3/OperatorEx13.java new file mode 100644 index 0000000..92f5cab --- /dev/null +++ b/source/ch3/OperatorEx13.java @@ -0,0 +1,10 @@ +class OperatorEx13 { + public static void main(String[] args) { + char c1 = 'a'; + +// char c2 = c1+1; // ¶óÀÎ 5 : ÄÄÆÄÀÏ ¿¡·¯¹ß»ý!!! + char c2 = 'a'+1; // ¶óÀÎ 6 : ÄÄÆÄÀÏ ¿¡·¯¾øÀ½ + + System.out.println(c2); + } +} diff --git a/source/ch3/OperatorEx14.java b/source/ch3/OperatorEx14.java new file mode 100644 index 0000000..964593e --- /dev/null +++ b/source/ch3/OperatorEx14.java @@ -0,0 +1,23 @@ +class OperatorEx14 { + public static void main(String[] args) { + char c = 'a'; + for(int i=0; i<26; i++) { // ºí·°{} ¾ÈÀÇ ¹®ÀåÀ» 26¹øÀ» ¹Ýº¹ÇÑ´Ù. + System.out.print(c++); //'a'ºÎÅÍ 26°³ÀÇ ¹®ÀÚ¸¦ Ãâ·ÂÇÑ´Ù. + } + + System.out.println(); // ÁٹٲÞÀ» ÇÑ´Ù. + + c = 'A'; + for(int i=0; i<26; i++) { // ºí·°{} ¾ÈÀÇ ¹®ÀåÀ» 26¹øÀ» ¹Ýº¹ÇÑ´Ù. + System.out.print(c++); //'A'ºÎÅÍ 26°³ÀÇ ¹®ÀÚ¸¦ Ãâ·ÂÇÑ´Ù. + } + + System.out.println(); + + c='0'; + for(int i=0; i<10; i++) { // ºí·°{} ¾ÈÀÇ ¹®ÀåÀ» 10¹øÀ» ¹Ýº¹ÇÑ´Ù. + System.out.print(c++); //'0'ºÎÅÍ 10°³ÀÇ ¹®ÀÚ¸¦ Ãâ·ÂÇÑ´Ù. + } + System.out.println(); + } +} diff --git a/source/ch3/OperatorEx15.java b/source/ch3/OperatorEx15.java new file mode 100644 index 0000000..ca7d33a --- /dev/null +++ b/source/ch3/OperatorEx15.java @@ -0,0 +1,8 @@ +class OperatorEx15 { + public static void main(String[] args) { + char lowerCase = 'a'; + char upperCase = (char)(lowerCase - 32); + + System.out.println(upperCase); + } +} diff --git a/source/ch3/OperatorEx16.java b/source/ch3/OperatorEx16.java new file mode 100644 index 0000000..ec85686 --- /dev/null +++ b/source/ch3/OperatorEx16.java @@ -0,0 +1,8 @@ +class OperatorEx16 { + public static void main(String[] args) { + float pi = 3.141592f; + float shortPi = (int)(pi * 1000) / 1000f; + + System.out.println(shortPi); + } +} diff --git a/source/ch3/OperatorEx17.java b/source/ch3/OperatorEx17.java new file mode 100644 index 0000000..3a6bdcd --- /dev/null +++ b/source/ch3/OperatorEx17.java @@ -0,0 +1,8 @@ +class OperatorEx17 { + public static void main(String args[]) { + double pi = 3.141592; + double shortPi = (int)(pi * 1000 + 0.5) / 1000.0; + + System.out.println(shortPi); + } +} diff --git a/source/ch3/OperatorEx18.java b/source/ch3/OperatorEx18.java new file mode 100644 index 0000000..0eb7b63 --- /dev/null +++ b/source/ch3/OperatorEx18.java @@ -0,0 +1,8 @@ +class OperatorEx18 { + public static void main(String args[]) { + double pi = 3.141592; + double shortPi = Math.round(pi * 1000) / 1000.0; + + System.out.println(shortPi); + } +} diff --git a/source/ch3/OperatorEx19.java b/source/ch3/OperatorEx19.java new file mode 100644 index 0000000..944af93 --- /dev/null +++ b/source/ch3/OperatorEx19.java @@ -0,0 +1,9 @@ +class OperatorEx19 { + public static void main(String args[]) { + int x = 10; + int y = 8; + + System.out.printf("%dÀ» %d·Î ³ª´©¸é, \n", x, y); + System.out.printf("¸òÀº %dÀÌ°í, ³ª¸ÓÁö´Â %dÀÔ´Ï´Ù.\n", x / y, x % y); + } +} diff --git a/source/ch3/OperatorEx2.java b/source/ch3/OperatorEx2.java new file mode 100644 index 0000000..1606c37 --- /dev/null +++ b/source/ch3/OperatorEx2.java @@ -0,0 +1,14 @@ +class OperatorEx2 { + public static void main(String args[]) { + int i=5, j=0; + + j = i++; + System.out.println("j=i++; ½ÇÇà ÈÄ, i=" + i +", j="+ j); + + i=5; // °á°ú¸¦ ºñ±³Çϱâ À§ÇØ, i¿Í jÀÇ °ªÀ» ´Ù½Ã 5¿Í 0À¸·Î º¯°æ + j=0; + + j = ++i; + System.out.println("j=++i; ½ÇÇà ÈÄ, i=" + i +", j="+ j); + } +} diff --git a/source/ch3/OperatorEx20.java b/source/ch3/OperatorEx20.java new file mode 100644 index 0000000..4f0a589 --- /dev/null +++ b/source/ch3/OperatorEx20.java @@ -0,0 +1,8 @@ + +class OperatorEx20 { + public static void main(String[] args) { + System.out.println(-10%8); + System.out.println(10%-8); + System.out.println(-10%-8); + } +} diff --git a/source/ch3/OperatorEx21.java b/source/ch3/OperatorEx21.java new file mode 100644 index 0000000..8b59b5c --- /dev/null +++ b/source/ch3/OperatorEx21.java @@ -0,0 +1,10 @@ +class OperatorEx21 { + public static void main(String args[]) { + System.out.printf("10 == 10.0f \t %b\n", 10==10.0f); + System.out.printf("'0'== 0 \t %b\n", '0'== 0); + System.out.printf("'\\0'== 0 \t %b\n", '\0'== 0); + System.out.printf("'A'== 65 \t %b\n", 'A'== 65); + System.out.printf("'A' > 'B' \t %b\n", 'A' > 'B'); + System.out.printf("'A'+1 != 'B' \t %b\n", 'A'+1 != 'B'); + } +} diff --git a/source/ch3/OperatorEx22.java b/source/ch3/OperatorEx22.java new file mode 100644 index 0000000..f58b53e --- /dev/null +++ b/source/ch3/OperatorEx22.java @@ -0,0 +1,17 @@ +class OperatorEx22 { + public static void main(String args[]) { + float f = 0.1f; + double d = 0.1; + double d2 = (double)f; + + System.out.printf("10.0==10.0f %b\n", 10.0==10.0f); + System.out.printf("0.1==0.1f %b\n", 0.1==0.1f); + System.out.printf("f =%19.17f\n", f); + System.out.printf("d =%19.17f\n", d); + System.out.printf("d2=%19.17f\n", d2); + System.out.printf("d==f %b\n", d==f); + System.out.printf("d==d2 %b\n", d==d2); + System.out.printf("d2==f %b\n", d2==f); + System.out.printf("(float)d==f %b\n", (float)d==f); + } +} diff --git a/source/ch3/OperatorEx23.java b/source/ch3/OperatorEx23.java new file mode 100644 index 0000000..594e74f --- /dev/null +++ b/source/ch3/OperatorEx23.java @@ -0,0 +1,14 @@ +class OperatorEx23 { + public static void main(String[] args) { + String str1 = "abc"; + String str2 = new String("abc"); + + System.out.printf("\"abc\"==\"abc\" ? %b%n", "abc"=="abc"); + System.out.printf(" str1==\"abc\" ? %b%n", str1=="abc"); + System.out.printf(" str2==\"abc\" ? %b%n", str2=="abc"); + System.out.printf("str1.equals(\"abc\") ? %b%n", str1.equals("abc")); + System.out.printf("str2.equals(\"abc\") ? %b%n", str2.equals("abc")); + System.out.printf("str2.equals(\"ABC\") ? %b%n", str2.equals("ABC")); + System.out.printf("str2.equalsIgnoreCase(\"ABC\") ? %b%n", str2.equalsIgnoreCase("ABC")); + } +} diff --git a/source/ch3/OperatorEx24.java b/source/ch3/OperatorEx24.java new file mode 100644 index 0000000..f8097e2 --- /dev/null +++ b/source/ch3/OperatorEx24.java @@ -0,0 +1,25 @@ +class OperatorEx24 { + public static void main(String args[]) { + int x = 0; + char ch = ' '; + + x = 15; + System.out.printf("x=%2d, 10 < x && x < 20 =%b\n", x, 10 < x && x < 20); + + x = 6; + System.out.printf("x=%2d, x%%2==0 || x%%3==0 && x%%6!=0 =%b\n", x, x%2==0||x%3==0&&x%6!=0); + System.out.printf("x=%2d, (x%%2==0 || x%%3==0) && x%%6!=0 =%b\n", x,(x%2==0||x%3==0)&&x%6!=0); + + ch='1'; + System.out.printf("ch='%c', '0' <= ch && ch <= '9' =%b\n", ch, '0' <= ch && ch <='9'); + + ch='a'; + System.out.printf("ch='%c', 'a' <= ch && ch <= 'z' =%b\n", ch, 'a' <= ch && ch <='z'); + + ch='A'; + System.out.printf("ch='%c', 'A' <= ch && ch <= 'Z' =%b\n", ch, 'A' <= ch && ch <='Z'); + + ch='q'; + System.out.printf("ch='%c', ch=='q' || ch=='Q' =%b\n", ch, ch=='q' || ch=='Q'); + } +} diff --git a/source/ch3/OperatorEx25.java b/source/ch3/OperatorEx25.java new file mode 100644 index 0000000..72ee7b7 --- /dev/null +++ b/source/ch3/OperatorEx25.java @@ -0,0 +1,21 @@ +import java.util.*; // ScannerŬ·¡½º¸¦ »ç¿ëÇϱâ À§ÇØ Ãß°¡ + +class OperatorEx25 { + public static void main(String args[]) { + Scanner scanner = new Scanner(System.in); + char ch = ' '; + + System.out.printf("¹®ÀÚ¸¦ Çϳª ÀÔ·ÂÇϼ¼¿ä.>"); + + String input = scanner.nextLine(); + ch = input.charAt(0); + + if('0'<= ch && ch <= '9') { + System.out.printf("ÀÔ·ÂÇϽŠ¹®ÀÚ´Â ¼ýÀÚÀÔ´Ï´Ù.\n"); + } + + if(('a'<= ch && ch <= 'z') || ('A'<= ch && ch <= 'Z')) { + System.out.printf("ÀÔ·ÂÇϽŠ¹®ÀÚ´Â ¿µ¹®ÀÚÀÔ´Ï´Ù.\n"); + } + } // main +} diff --git a/source/ch3/OperatorEx26.java b/source/ch3/OperatorEx26.java new file mode 100644 index 0000000..9a7a527 --- /dev/null +++ b/source/ch3/OperatorEx26.java @@ -0,0 +1,12 @@ +class OperatorEx26 { + public static void main(String[] args) { + int a = 5; + int b = 0; + + System.out.printf("a=%d, b=%d%n", a, b); + System.out.printf("a!=0 || ++b!=0 = %b%n", a!=0 || ++b!=0); + System.out.printf("a=%d, b=%d\n", a, b); + System.out.printf("a==0 && ++b!=0 = %b%n", a==0 && ++b!=0); + System.out.printf("a=%d, b=%d%n", a, b); + } // mainÀÇ ³¡ +} diff --git a/source/ch3/OperatorEx27.java b/source/ch3/OperatorEx27.java new file mode 100644 index 0000000..62bd77a --- /dev/null +++ b/source/ch3/OperatorEx27.java @@ -0,0 +1,17 @@ +class OperatorEx27 { + public static void main(String[] args) { + boolean b = true; + char ch = 'C'; + + System.out.printf("b=%b\n", b); + System.out.printf("!b=%b\n", !b); + System.out.printf("!!b=%b\n", !!b); + System.out.printf("!!!b=%b\n", !!!b); + System.out.println(); + + System.out.printf("ch=%c\n", ch); + System.out.printf("ch < 'a' || ch > 'z'=%b\n", ch < 'a' || ch > 'z'); + System.out.printf("!('a'<=ch && ch<='z')=%b\n", !('a'<= ch && ch<='z')); + System.out.printf(" 'a'<=ch && ch<='z' =%b\n", 'a'<=ch && ch<='z'); + } // mainÀÇ ³¡ +} diff --git a/source/ch3/OperatorEx28.java b/source/ch3/OperatorEx28.java new file mode 100644 index 0000000..40e3b25 --- /dev/null +++ b/source/ch3/OperatorEx28.java @@ -0,0 +1,21 @@ +class OperatorEx28 { + public static void main(String[] args) { + int x = 0xAB; + int y = 0xF; + + System.out.printf("x = %#X \t\t%s%n", x, toBinaryString(x)); + System.out.printf("y = %#X \t\t%s%n", x, toBinaryString(y)); + System.out.printf("%#X | %#X = %#X \t%s%n", x, y, x | y, toBinaryString(x | y)); + System.out.printf("%#X & %#X = %#X \t%s%n", x, y, x & y, toBinaryString(x & y)); + System.out.printf("%#X ^ %#X = %#X \t%s%n", x, y, x ^ y, toBinaryString(x ^ y)); + System.out.printf("%#X ^ %#X ^ %#X = %#X %s%n", x, y, y, x ^ y ^ y, toBinaryString(x ^ y ^ y)); + } // mainÀÇ ³¡ + + // 10Áø Á¤¼ö¸¦ 2Áø¼ö·Î º¯È¯ÇÏ´Â ¸Þ¼­µå + static String toBinaryString(int x) { + String zero = "00000000000000000000000000000000"; + String tmp = zero + Integer.toBinaryString(x); + + return tmp.substring(tmp.length()-32); + } +} diff --git a/source/ch3/OperatorEx29.java b/source/ch3/OperatorEx29.java new file mode 100644 index 0000000..66491ea --- /dev/null +++ b/source/ch3/OperatorEx29.java @@ -0,0 +1,22 @@ +class OperatorEx29 { + public static void main(String[] args) { + byte p = 10; + byte n = -10; + + System.out.printf(" p =%d \t%s%n", p, toBinaryString(p)); + System.out.printf("~p =%d \t%s%n", ~p, toBinaryString(~p)); + System.out.printf("~p+1=%d \t%s%n", ~p+1, toBinaryString(~p+1)); + System.out.printf("~~p =%d \t%s%n", ~~p, toBinaryString(~~p)); + System.out.println(); + System.out.printf(" n =%d%n", n); + System.out.printf("~(n-1)=%d%n", ~(n-1)); + } // mainÀÇ ³¡ + + // 10Áø Á¤¼ö¸¦ 2Áø¼ö·Î º¯È¯ÇÏ´Â ¸Þ¼­µå + static String toBinaryString(int x) { + String zero = "00000000000000000000000000000000"; + String tmp = zero + Integer.toBinaryString(x); + + return tmp.substring(tmp.length()-32); + } +} diff --git a/source/ch3/OperatorEx3.java b/source/ch3/OperatorEx3.java new file mode 100644 index 0000000..3ff1e2f --- /dev/null +++ b/source/ch3/OperatorEx3.java @@ -0,0 +1,9 @@ +class OperatorEx3 { + public static void main(String args[]) { + int i=5, j=5; + + System.out.println(i++); + System.out.println(++j); + System.out.println("i = " + i + ", j = " +j); + } +} diff --git a/source/ch3/OperatorEx30.java b/source/ch3/OperatorEx30.java new file mode 100644 index 0000000..c1a60f0 --- /dev/null +++ b/source/ch3/OperatorEx30.java @@ -0,0 +1,36 @@ +class OperatorEx30 { + public static void main(String[] args) { + int dec = 8; + + System.out.printf("%d >> %d = %4d \t%s%n", dec, 0, dec >> 0, toBinaryString(dec >> 0)); + System.out.printf("%d >> %d = %4d \t%s%n", dec, 1, dec >> 1, toBinaryString(dec >> 1)); + System.out.printf("%d >> %d = %4d \t%s%n", dec, 2, dec >> 2, toBinaryString(dec >> 2)); + + System.out.printf("%d << %d = %4d \t%s%n", dec, 0, dec << 0, toBinaryString(dec << 0)); + System.out.printf("%d << %d = %4d \t%s%n", dec, 1, dec << 1, toBinaryString(dec << 1)); + System.out.printf("%d << %d = %4d \t%s%n", dec, 2, dec << 2, toBinaryString(dec << 2)); + System.out.println(); + + dec = -8; + System.out.printf("%d >> %d = %4d \t%s%n", dec, 0, dec >> 0, toBinaryString(dec >> 0)); + System.out.printf("%d >> %d = %4d \t%s%n", dec, 1, dec >> 1, toBinaryString(dec >> 1)); + System.out.printf("%d >> %d = %4d \t%s%n", dec, 2, dec >> 2, toBinaryString(dec >> 2)); + + System.out.printf("%d << %d = %4d \t%s%n", dec, 0, dec << 0, toBinaryString(dec << 0)); + System.out.printf("%d << %d = %4d \t%s%n", dec, 1, dec << 1, toBinaryString(dec << 1)); + System.out.printf("%d << %d = %4d \t%s%n", dec, 2, dec << 2, toBinaryString(dec << 2)); + System.out.println(); + + dec = 8; + System.out.printf("%d >> %2d = %4d \t%s%n", dec, 0, dec >> 0, toBinaryString(dec << 2)); + System.out.printf("%d >> %2d = %4d \t%s%n", dec, 32, dec >> 32, toBinaryString(dec << 2)); + } // mainÀÇ ³¡ + + // 10Áø Á¤¼ö¸¦ 2Áø¼ö·Î º¯È¯ÇÏ´Â ¸Þ¼­µå + static String toBinaryString(int x) { + String zero = "00000000000000000000000000000000"; + String tmp = zero + Integer.toBinaryString(x); + + return tmp.substring(tmp.length()-32); + } +} diff --git a/source/ch3/OperatorEx31.java b/source/ch3/OperatorEx31.java new file mode 100644 index 0000000..c542b35 --- /dev/null +++ b/source/ch3/OperatorEx31.java @@ -0,0 +1,19 @@ +class OperatorEx31 { + public static void main(String[] args) { + int dec = 1234; + int hex = 0xABCD; + int mask = 0xF; + + System.out.printf("hex=%X%n", hex); + System.out.printf("%X%n", hex & mask); + + hex = hex >> 4; + System.out.printf("%X%n", hex & mask); + + hex = hex >> 4; + System.out.printf("%X%n", hex & mask); + + hex = hex >> 4; + System.out.printf("%X%n", hex & mask); + } // mainÀÇ ³¡ +} diff --git a/source/ch3/OperatorEx32.java b/source/ch3/OperatorEx32.java new file mode 100644 index 0000000..7372c72 --- /dev/null +++ b/source/ch3/OperatorEx32.java @@ -0,0 +1,23 @@ +class OperatorEx32 { + public static void main(String args[]) { + int x, y, z; + int absX, absY, absZ; + char signX, signY, signZ; + + x = 10; + y = -5; + z = 0; + + absX = x >= 0 ? x : -x; // xÀÇ °ªÀÌ À½¼öÀ̸é, ¾ç¼ö·Î ¸¸µç´Ù. + absY = y >= 0 ? y : -y; + absZ = z >= 0 ? z : -z; + + signX = x > 0 ? '+' : ( x==0 ? ' ' : '-'); // Á¶°Ç ¿¬»êÀÚ¸¦ Áßø + signY = y > 0 ? '+' : ( y==0 ? ' ' : '-'); + signZ = z > 0 ? '+' : ( z==0 ? ' ' : '-'); + + System.out.printf("x=%c%d\n", signX, absX); + System.out.printf("y=%c%d\n", signY, absY); + System.out.printf("z=%c%d\n", signZ, absZ); + } +} diff --git a/source/ch3/OperatorEx4.java b/source/ch3/OperatorEx4.java new file mode 100644 index 0000000..b065cd3 --- /dev/null +++ b/source/ch3/OperatorEx4.java @@ -0,0 +1,11 @@ +class OperatorEx4 { + public static void main(String[] args) { + int i = -10; + i = +i; + System.out.println(i); + + i=-10; + i = -i; + System.out.println(i); + } +} diff --git a/source/ch3/OperatorEx5.java b/source/ch3/OperatorEx5.java new file mode 100644 index 0000000..c3e0607 --- /dev/null +++ b/source/ch3/OperatorEx5.java @@ -0,0 +1,12 @@ +class OperatorEx5 { + public static void main(String args[]) { + int a = 10; + int b = 4; + + 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 / %f = %f\n", a, (float)b, a / (float)b); + } +} diff --git a/source/ch3/OperatorEx6.java b/source/ch3/OperatorEx6.java new file mode 100644 index 0000000..9f39366 --- /dev/null +++ b/source/ch3/OperatorEx6.java @@ -0,0 +1,9 @@ +class OperatorEx6 { + public static void main(String[] args) { + byte a = 10; + byte b = 20; + byte c = a + b; + + System.out.println(c); + } +} diff --git a/source/ch3/OperatorEx7.java b/source/ch3/OperatorEx7.java new file mode 100644 index 0000000..f447a6e --- /dev/null +++ b/source/ch3/OperatorEx7.java @@ -0,0 +1,9 @@ +class OperatorEx7 { + public static void main(String[] args) { + byte a = 10; + byte b = 30; + byte c = (byte)(a * b); + + System.out.println(c); + } +} diff --git a/source/ch3/OperatorEx8.java b/source/ch3/OperatorEx8.java new file mode 100644 index 0000000..0626bee --- /dev/null +++ b/source/ch3/OperatorEx8.java @@ -0,0 +1,10 @@ +class OperatorEx8 { + public static void main(String args[]) { + int a = 1000000; // 1,000,000 1¹é¸¸ + int b = 2000000; // 2,000,000 2¹é¸¸ + + long c = a * b; // a * b = 2,000,000,000,000 ? + + System.out.println(c); + } +} diff --git a/source/ch3/OperatorEx9.java b/source/ch3/OperatorEx9.java new file mode 100644 index 0000000..400bada --- /dev/null +++ b/source/ch3/OperatorEx9.java @@ -0,0 +1,9 @@ +class OperatorEx9 { + public static void main(String args[]) { + long a = 1000000 * 1000000; + long b = 1000000 * 1000000L; + + System.out.println("a="+a); + System.out.println("b="+b); + } +} diff --git a/source/ch4/FlowEx1.java b/source/ch4/FlowEx1.java new file mode 100644 index 0000000..e456525 --- /dev/null +++ b/source/ch4/FlowEx1.java @@ -0,0 +1,21 @@ +class FlowEx1 { + public static void main(String[] args) { + int x= 0; + + System.out.printf("x=%d À϶§, ÂüÀÎ °ÍÀº%n", x); + + if(x==0) System.out.println("x==0"); + if(x!=0) System.out.println("x!=0"); + if(!(x==0)) System.out.println("!(x==0)"); + if(!(x!=0)) System.out.println("!(x!=0)"); + System.out.println(); + + x = 1; + System.out.printf("x=%d À϶§, ÂüÀÎ °ÍÀº%n", x); + + if(x==0) System.out.println("x==0"); + if(x!=0) System.out.println("x!=0"); + if(!(x==0)) System.out.println("!(x==0)"); + if(!(x!=0)) System.out.println("!(x!=0)"); + } +} diff --git a/source/ch4/FlowEx10.java b/source/ch4/FlowEx10.java new file mode 100644 index 0000000..6e9221f --- /dev/null +++ b/source/ch4/FlowEx10.java @@ -0,0 +1,31 @@ +import java.util.*; + +class FlowEx10 { + public static void main(String[] args) { + int score = 0; + char grade = ' '; + + System.out.print("´ç½ÅÀÇ Á¡¼ö¸¦ ÀÔ·ÂÇϼ¼¿ä.(1~100)>"); + + Scanner scanner = new Scanner(System.in); + String tmp = scanner.nextLine(); // È­¸éÀ» ÅëÇØ ÀԷ¹ÞÀº ³»¿ëÀ» tmp¿¡ ÀúÀå + score = Integer.parseInt(tmp); // ÀԷ¹ÞÀº ¹®ÀÚ¿­(tmp)¸¦ ¼ýÀÚ·Î º¯È¯ + + switch(score/10) { + case 10: + case 9 : + grade = 'A'; + break; + case 8 : + grade = 'B'; + break; + case 7 : + grade = 'C'; + break; + default : + grade = 'F'; + } // end of switch + + System.out.println("´ç½ÅÀÇ ÇÐÁ¡Àº "+ grade +"ÀÔ´Ï´Ù."); + } // mainÀÇ ³¡ +} diff --git a/source/ch4/FlowEx11.java b/source/ch4/FlowEx11.java new file mode 100644 index 0000000..5672d38 --- /dev/null +++ b/source/ch4/FlowEx11.java @@ -0,0 +1,40 @@ +import java.util.*; + +class FlowEx11 { + public static void main(String[] args) { + char gender; + String regNo = ""; + System.out.print("´ç½ÅÀÇ ÁֹιøÈ£¸¦ ÀÔ·ÂÇϼ¼¿ä.(011231-1111222)>"); + + Scanner scanner = new Scanner(System.in); + regNo = scanner.nextLine(); + + gender = regNo.charAt(7); // ÀԷ¹ÞÀº ¹øÈ£ÀÇ 8¹ø° ¹®ÀÚ¸¦ gender¿¡ ÀúÀå + + switch(gender) { + case '1': + case '3': + switch(gender) { + case '1': + System.out.println("´ç½ÅÀº 2000³â ÀÌÀü¿¡ Ãâ»ýÇÑ ³²ÀÚÀÔ´Ï´Ù."); + break; + case '3': + System.out.println("´ç½ÅÀº 2000³â ÀÌÈÄ¿¡ Ãâ»ýÇÑ ³²ÀÚÀÔ´Ï´Ù."); + } + break; // ÀÌ break¹®À» »©¸ÔÁö ¾Êµµ·Ï ÁÖÀÇ + case '2': + case '4': + switch(gender) { + case '2': + System.out.println("´ç½ÅÀº 2000³â ÀÌÀü¿¡ Ãâ»ýÇÑ ¿©ÀÚÀÔ´Ï´Ù."); + break; + case '4': + System.out.println("´ç½ÅÀº 2000³â ÀÌÈÄ¿¡ Ãâ»ýÇÑ ¿©ÀÚÀÔ´Ï´Ù."); + break; + } + break; + default: + System.out.println("À¯È¿ÇÏÁö ¾ÊÀº Áֹεî·Ï¹øÈ£ÀÔ´Ï´Ù.");; + } + } // mainÀÇ ³¡ +} diff --git a/source/ch4/FlowEx12.java b/source/ch4/FlowEx12.java new file mode 100644 index 0000000..e4bd6ca --- /dev/null +++ b/source/ch4/FlowEx12.java @@ -0,0 +1,11 @@ +class FlowEx12 { + public static void main(String[] args) { + for(int i=1;i<=5;i++) + System.out.println(i); // iÀÇ °ªÀ» Ãâ·ÂÇÑ´Ù. + + for(int i=1;i<=5;i++) + System.out.print(i); // println()´ë½Å print()¸¦ ¾²¸é °¡·Î·Î Ãâ·ÂµÈ´Ù. + + System.out.println(); + } +} diff --git a/source/ch4/FlowEx13.java b/source/ch4/FlowEx13.java new file mode 100644 index 0000000..da55d1e --- /dev/null +++ b/source/ch4/FlowEx13.java @@ -0,0 +1,10 @@ +class FlowEx13 { + public static void main(String[] args) { + int sum = 0; // Çհ踦 ÀúÀåÇϱâ À§ÇÑ º¯¼ö. + + for(int i=1; i <= 10; i++) { + sum += i ; // sum = sum + i; + System.out.printf("1ºÎÅÍ %2d ±îÁöÀÇ ÇÕ: %2d%n", i, sum); + } + } // mainÀÇ ³¡ +} diff --git a/source/ch4/FlowEx14.java b/source/ch4/FlowEx14.java new file mode 100644 index 0000000..13af0e2 --- /dev/null +++ b/source/ch4/FlowEx14.java @@ -0,0 +1,6 @@ +class FlowEx14 { + public static void main(String[] args) { + for(int i=1,j=10;i<=10;i++,j--) + System.out.printf("%d \t %d%n", i, j); + } +} diff --git a/source/ch4/FlowEx15.java b/source/ch4/FlowEx15.java new file mode 100644 index 0000000..996c464 --- /dev/null +++ b/source/ch4/FlowEx15.java @@ -0,0 +1,10 @@ +class FlowEx15 { + public static void main(String[] args) { + System.out.println("i \t 2*i \t 2*i-1 \t i*i \t 11-i \t i%3 \t i/3"); + System.out.println("----------------------------------------------------"); + + for(int i=1;i<=10;i++) { + System.out.printf("%d \t %d \t %d \t %d \t %d \t %d \t %d%n", i, 2*i, 2*i-1, i*i, 11-i, i%3, i/3); + } + } +} diff --git a/source/ch4/FlowEx16.java b/source/ch4/FlowEx16.java new file mode 100644 index 0000000..c60d287 --- /dev/null +++ b/source/ch4/FlowEx16.java @@ -0,0 +1,10 @@ +class FlowEx16 { + public static void main(String[] args) { + for(int i=1;i<=5;i++) { + for(int j=1;j<=10;j++) { + System.out.print("*"); + } + System.out.println(); + } + } // mainÀÇ ³¡ +} diff --git a/source/ch4/FlowEx17.java b/source/ch4/FlowEx17.java new file mode 100644 index 0000000..1eca170 --- /dev/null +++ b/source/ch4/FlowEx17.java @@ -0,0 +1,20 @@ +import java.util.*; + +class FlowEx17 { + public static void main(String[] args) { + int num = 0; + + System.out.print("*À» Ãâ·ÂÇÒ ¶óÀÎÀÇ ¼ö¸¦ ÀÔ·ÂÇϼ¼¿ä.>"); + + Scanner scanner = new Scanner(System.in); + String tmp = scanner.nextLine(); // È­¸éÀ» ÅëÇØ ÀԷ¹ÞÀº ³»¿ëÀ» tmp¿¡ ÀúÀå + num = Integer.parseInt(tmp); // ÀԷ¹ÞÀº ¹®ÀÚ¿­(tmp)À» ¼ýÀÚ·Î º¯È¯ + + for(int i=0;i"); + + Scanner scanner = new Scanner(System.in); + String tmp = scanner.nextLine(); // È­¸éÀ» ÅëÇØ ÀԷ¹ÞÀº ³»¿ëÀ» tmp¿¡ ÀúÀå + input = Integer.parseInt(tmp); // ÀԷ¹ÞÀº ¹®ÀÚ¿­(tmp)À» ¼ýÀÚ·Î º¯È¯ + + if(input==0) { + System.out.println("ÀÔ·ÂÇϽŠ¼ýÀÚ´Â 0ÀÔ´Ï´Ù."); + } + + if(input!=0) + System.out.println("ÀÔ·ÂÇϽŠ¼ýÀÚ´Â 0ÀÌ ¾Æ´Õ´Ï´Ù."); + System.out.println("ÀÔ·ÂÇϽŠ¼ýÀÚ´Â "+ input +"ÀÔ´Ï´Ù."); + } // mainÀÇ ³¡ +} diff --git a/source/ch4/FlowEx20.java b/source/ch4/FlowEx20.java new file mode 100644 index 0000000..5260783 --- /dev/null +++ b/source/ch4/FlowEx20.java @@ -0,0 +1,10 @@ +class FlowEx20 { + public static void main(String[] args) { + for(int i=1;i<=5;i++) { + for(int j=1;j<=5;j++) { + System.out.printf("[%d,%d]", i, j); + } + System.out.println(); + } + } // mainÀÇ ³¡ +} diff --git a/source/ch4/FlowEx21.java b/source/ch4/FlowEx21.java new file mode 100644 index 0000000..9085cd7 --- /dev/null +++ b/source/ch4/FlowEx21.java @@ -0,0 +1,14 @@ +class FlowEx21 { + public static void main(String[] args) { + for(int i=1;i<=5;i++) { + for(int j=1;j<=5;j++) { + if(i==j) { + System.out.printf("[%d,%d]", i, j); + } else { + System.out.printf("%5c", ' '); + } + } + System.out.println(); + } + } // mainÀÇ ³¡ +} diff --git a/source/ch4/FlowEx22.java b/source/ch4/FlowEx22.java new file mode 100644 index 0000000..b41b2a7 --- /dev/null +++ b/source/ch4/FlowEx22.java @@ -0,0 +1,18 @@ +class FlowEx22 { + public static void main(String[] args) { + int[] arr = {10,20,30,40,50}; + int sum = 0; + + for(int i=0;i"); + Scanner scanner = new Scanner(System.in); + String tmp = scanner.nextLine(); // È­¸éÀ» ÅëÇØ ÀԷ¹ÞÀº ³»¿ëÀ» tmp¿¡ ÀúÀå + num = Integer.parseInt(tmp); // ÀԷ¹ÞÀº ¹®ÀÚ¿­(tmp)À» ¼ýÀÚ·Î º¯È¯ + + while(num!=0) { + // numÀ» 10À¸·Î ³ª´« ³ª¸ÓÁö¸¦ sum¿¡ ´õÇÔ + sum += num%10; // sum = sum + num%10; + System.out.printf("sum=%3d num=%d%n", sum, num); + + num /= 10; // num = num / 10; numÀ» 10À¸·Î ³ª´« °ªÀ» ´Ù½Ã num¿¡ ÀúÀå + } + + System.out.println("°¢ ÀÚ¸®¼öÀÇ ÇÕ:"+ sum); + } +} diff --git a/source/ch4/FlowEx26.java b/source/ch4/FlowEx26.java new file mode 100644 index 0000000..d559aba --- /dev/null +++ b/source/ch4/FlowEx26.java @@ -0,0 +1,10 @@ +class FlowEx26 { + public static void main(String[] args) { + int sum = 0; + int i = 0; + + while((sum += ++i) <= 100) { // i¸¦ 1¾¿ Áõ°¡½ÃÄѼ­ sum¿¡ °è¼Ó ´õÇسª°£´Ù. + System.out.printf("%d - %d%n", i, sum); + } + } // mainÀÇ ³¡ +} diff --git a/source/ch4/FlowEx27.java b/source/ch4/FlowEx27.java new file mode 100644 index 0000000..931fc0a --- /dev/null +++ b/source/ch4/FlowEx27.java @@ -0,0 +1,27 @@ +import java.util.*; + +class FlowEx27 { + public static void main(String[] args) { + int num; + int sum = 0; + boolean flag = true; // while¹®ÀÇ Á¶°Ç½ÄÀ¸·Î »ç¿ëµÉ º¯¼ö + + System.out.println("Çհ踦 ±¸ÇÒ ¼ýÀÚ¸¦ ÀÔ·ÂÇϼ¼¿ä.(²ø³»·Á¸é 0À» ÀÔ·Â)"); + + while(flag) { // flagÀÇ °ªÀÌ trueÀ̹ǷΠÁ¶°Ç½ÄÀº ÂüÀÌ µÈ´Ù. + System.out.print(">>"); + + Scanner scanner = new Scanner(System.in); + String tmp = scanner.nextLine(); + num = Integer.parseInt(tmp); + + if(num!=0) { + sum += num; // numÀÌ 0ÀÌ ¾Æ´Ï¸é, sum¿¡ ´õÇÑ´Ù. + } else { + flag = false; // numÀÌ 0À̸é, flagÀÇ °ªÀ» false·Î º¯°æ. + } + } // while¹®ÀÇ ³¡ + + System.out.println("ÇÕ°è:"+ sum); + } +} diff --git a/source/ch4/FlowEx28.java b/source/ch4/FlowEx28.java new file mode 100644 index 0000000..e95f721 --- /dev/null +++ b/source/ch4/FlowEx28.java @@ -0,0 +1,26 @@ +import java.util.*; + +class FlowEx28 { + public static void main(String[] args) { + int input = 0; + int answer = 0; + + answer = (int)(Math.random() * 100) + 1; // 1~100»çÀÌÀÇ ÀÓÀÇÀÇ ¼ö¸¦ ÀúÀå + Scanner scanner = new Scanner(System.in); + + do { + System.out.print("1°ú 100»çÀÌÀÇ Á¤¼ö¸¦ ÀÔ·ÂÇϼ¼¿ä.>"); + + String tmp = scanner.nextLine(); + input = Integer.parseInt(tmp); + + if(input > answer) { + System.out.println("´õ ÀÛÀº ¼ö·Î ´Ù½Ã ½ÃµµÇغ¸¼¼¿ä."); + } else if(input < answer) { + System.out.println("´õ Å« ¼ö·Î ´Ù½Ã ½ÃµµÇغ¸¼¼¿ä."); + } + } while(input!=answer); + + System.out.println("Á¤´äÀÔ´Ï´Ù."); + } +} diff --git a/source/ch4/FlowEx29.java b/source/ch4/FlowEx29.java new file mode 100644 index 0000000..15aa83d --- /dev/null +++ b/source/ch4/FlowEx29.java @@ -0,0 +1,16 @@ +class FlowEx29 { + public static void main(String[] args) { + for(int i=1;i<=100;i++) { + System.out.printf("i=%d ", i); + + int tmp = i; + + do { + if(tmp%10%3==0 && tmp%10!=0) // tmp%10ÀÌ 3ÀÇ ¹è¼öÀÎÁö È®ÀÎ(0 Á¦¿Ü) + System.out.print("¦"); + } while((tmp/=10)!=0); // tmp /= 10Àº tmp = tmp / 10°ú µ¿ÀÏ + + System.out.println(); + } + } // main +} diff --git a/source/ch4/FlowEx3.java b/source/ch4/FlowEx3.java new file mode 100644 index 0000000..4508090 --- /dev/null +++ b/source/ch4/FlowEx3.java @@ -0,0 +1,19 @@ +import java.util.*; // ScannerŬ·¡½º¸¦ »ç¿ëÇϱâ À§ÇØ Ãß°¡ + +class FlowEx3 { + public static void main(String[] args) { + int input; + + System.out.print("¼ýÀÚ¸¦ Çϳª ÀÔ·ÂÇϼ¼¿ä.>"); + + Scanner scanner = new Scanner(System.in); + String tmp = scanner.nextLine(); // È­¸éÀ» ÅëÇØ ÀԷ¹ÞÀº ³»¿ëÀ» tmp¿¡ ÀúÀå + input = Integer.parseInt(tmp); // ÀԷ¹ÞÀº ¹®ÀÚ¿­(tmp)À» ¼ýÀÚ·Î º¯È¯ + + if(input==0) { + System.out.println("ÀÔ·ÂÇϽŠ¼ýÀÚ´Â 0ÀÔ´Ï´Ù."); + } else { // input!=0ÀÎ °æ¿ì + System.out.println("ÀÔ·ÂÇϽŠ¼ýÀÚ´Â 0ÀÌ ¾Æ´Õ´Ï´Ù."); + } + } // mainÀÇ ³¡ +} diff --git a/source/ch4/FlowEx30.java b/source/ch4/FlowEx30.java new file mode 100644 index 0000000..de226e7 --- /dev/null +++ b/source/ch4/FlowEx30.java @@ -0,0 +1,16 @@ +class FlowEx30 { + public static void main(String[] args) { + int sum = 0; + int i = 0; + + while(true) { + if(sum > 100) + break; + ++i; + sum += i; + } // end of while + + System.out.println("i=" + i); + System.out.println("sum=" + sum); + } +} diff --git a/source/ch4/FlowEx31.java b/source/ch4/FlowEx31.java new file mode 100644 index 0000000..637e43d --- /dev/null +++ b/source/ch4/FlowEx31.java @@ -0,0 +1,9 @@ +class FlowEx31 { + public static void main(String[] args) { + for(int i=0;i <= 10;i++) { + if (i%3==0) + continue; + System.out.println(i); + } + } +} diff --git a/source/ch4/FlowEx32.java b/source/ch4/FlowEx32.java new file mode 100644 index 0000000..ce8afc7 --- /dev/null +++ b/source/ch4/FlowEx32.java @@ -0,0 +1,30 @@ +import java.util.*; + +class FlowEx32 { + public static void main(String[] args) { + int menu = 0; + int num = 0; + + Scanner scanner = new Scanner(System.in); + + while(true) { + System.out.println("(1) square"); + System.out.println("(2) square root"); + System.out.println("(3) log"); + System.out.print("¿øÇÏ´Â ¸Þ´º(1~3)¸¦ ¼±ÅÃÇϼ¼¿ä.(Á¾·á:0)>"); + + String tmp = scanner.nextLine(); // È­¸é¿¡¼­ ÀԷ¹ÞÀº ³»¿ëÀ» tmp¿¡ ÀúÀå + menu = Integer.parseInt(tmp); // ÀԷ¹ÞÀº ¹®ÀÚ¿­(tmp)À» ¼ýÀÚ·Î º¯È¯ + + if(menu==0) { + System.out.println("ÇÁ·Î±×·¥À» Á¾·áÇÕ´Ï´Ù."); + break; + } else if (!(1 <= menu && menu <= 3)) { + System.out.println("¸Þ´º¸¦ À߸ø ¼±ÅÃÇϼ̽À´Ï´Ù.(Á¾·á´Â 0)"); + continue; + } + + System.out.println("¼±ÅÃÇϽŠ¸Þ´º´Â "+ menu +"¹øÀÔ´Ï´Ù."); + } + } // mainÀÇ ³¡ +} diff --git a/source/ch4/FlowEx33.java b/source/ch4/FlowEx33.java new file mode 100644 index 0000000..6c4ebc8 --- /dev/null +++ b/source/ch4/FlowEx33.java @@ -0,0 +1,18 @@ +class FlowEx33 { + public static void main(String[] args) + { + // for¹®¿¡ Loop1À̶ó´Â À̸§À» ºÙ¿´´Ù. + Loop1 : for(int i=2;i <=9;i++) { + for(int j=1;j <=9;j++) { + if(j==5) + break Loop1; +// break; +// continue Loop1; +// continue; + System.out.println(i+"*"+ j +"="+ i*j); + } // end of for i + System.out.println(); + } // end of Loop1 + + } +} diff --git a/source/ch4/FlowEx34.java b/source/ch4/FlowEx34.java new file mode 100644 index 0000000..310afb3 --- /dev/null +++ b/source/ch4/FlowEx34.java @@ -0,0 +1,52 @@ +import java.util.*; + +class FlowEx34 { + public static void main(String[] args) { + int menu = 0; + int num = 0; + + Scanner scanner = new Scanner(System.in); + + outer: + while(true) { + System.out.println("(1) square"); + System.out.println("(2) square root"); + System.out.println("(3) log"); + System.out.print("¿øÇÏ´Â ¸Þ´º(1~3)¸¦ ¼±ÅÃÇϼ¼¿ä.(Á¾·á:0)>"); + + String tmp = scanner.nextLine(); // È­¸é¿¡¼­ ÀԷ¹ÞÀº ³»¿ëÀ» tmp¿¡ ÀúÀå + menu = Integer.parseInt(tmp); // ÀԷ¹ÞÀº ¹®ÀÚ¿­(tmp)À» ¼ýÀÚ·Î º¯È¯ + + if(menu==0) { + System.out.println("ÇÁ·Î±×·¥À» Á¾·áÇÕ´Ï´Ù."); + break; + } else if (!(1<= menu && menu <= 3)) { + System.out.println("¸Þ´º¸¦ À߸ø ¼±ÅÃÇϼ̽À´Ï´Ù.(Á¾·á´Â 0)"); + continue; + } + + for(;;) { + System.out.print("°è»êÇÒ °ªÀ» ÀÔ·ÂÇϼ¼¿ä.(°è»ê Á¾·á:0, Àüü Á¾·á:99)>"); + tmp = scanner.nextLine(); // È­¸é¿¡¼­ ÀԷ¹ÞÀº ³»¿ëÀ» tmp¿¡ ÀúÀå + num = Integer.parseInt(tmp); // ÀԷ¹ÞÀº ¹®ÀÚ¿­(tmp)À» ¼ýÀÚ·Î º¯È¯ + + if(num==0) + break; // °è»ê Á¾·á. for¹®À» ¹þ¾î³­´Ù. + if(num==99) + break outer; // Àüü Á¾·á. for¹®°ú while¹®À» ¸ðµÎ ¹þ¾î³­´Ù. + + switch(menu) { + case 1: + System.out.println("result="+ num*num); + break; + case 2: + System.out.println("result="+ Math.sqrt(num)); + break; + case 3: + System.out.println("result="+ Math.log(num)); + break; + } + } // for(;;) + } // whileÀÇ ³¡ + } // mainÀÇ ³¡ +} diff --git a/source/ch4/FlowEx4.java b/source/ch4/FlowEx4.java new file mode 100644 index 0000000..778a638 --- /dev/null +++ b/source/ch4/FlowEx4.java @@ -0,0 +1,25 @@ +import java.util.*; + +class FlowEx4 { + public static void main(String[] args) { + int score = 0; // Á¡¼ö¸¦ ÀúÀåÇϱâ À§ÇÑ º¯¼ö + char grade =' '; // ÇÐÁ¡À» ÀúÀåÇϱâ À§ÇÑ º¯¼ö. °ø¹éÀ¸·Î ÃʱâÈ­ÇÑ´Ù. + + System.out.print("Á¡¼ö¸¦ ÀÔ·ÂÇϼ¼¿ä.>"); + Scanner scanner = new Scanner(System.in); + String tmp = scanner.nextLine(); // È­¸éÀ» ÅëÇØ ÀԷ¹ÞÀº ³»¿ëÀ» tmp¿¡ ÀúÀå + score = Integer.parseInt(tmp); // ÀԷ¹ÞÀº ¹®ÀÚ¿­(tmp)À» ¼ýÀÚ·Î º¯È¯ + + if (score >= 90) { // score°¡ 90Á¡ º¸´Ù °°°Å³ª Å©¸é AÇÐÁ¡ + grade = 'A'; + } else if (score >=80) { // score°¡ 80Á¡ º¸´Ù °°°Å³ª Å©¸é BÇÐÁ¡ + grade = 'B'; + } else if (score >=70) { // score°¡ 70Á¡ º¸´Ù °°°Å³ª Å©¸é CÇÐÁ¡ + grade = 'C'; + } else { // ³ª¸ÓÁö´Â DÇÐÁ¡ + grade = 'D'; + } + + System.out.println("´ç½ÅÀÇ ÇÐÁ¡Àº "+ grade +"ÀÔ´Ï´Ù."); + } +} diff --git a/source/ch4/FlowEx5.java b/source/ch4/FlowEx5.java new file mode 100644 index 0000000..5765b10 --- /dev/null +++ b/source/ch4/FlowEx5.java @@ -0,0 +1,37 @@ +import java.util.*; + +class FlowEx5 { + public static void main(String[] args) { + int score = 0; + char grade = ' '; + char opt = '0'; + + System.out.print("Á¡¼ö¸¦ ÀÔ·ÂÇØÁÖ¼¼¿ä.>"); + + Scanner scanner = new Scanner(System.in); + String tmp = scanner.nextLine(); // È­¸éÀ» ÅëÇØ ÀԷ¹ÞÀº ³»¿ëÀ» tmp¿¡ ÀúÀå + score = Integer.parseInt(tmp); // ÀԷ¹ÞÀº ¹®ÀÚ¿­(tmp)À» ¼ýÀÚ·Î º¯È¯ + + System.out.printf("´ç½ÅÀÇ Á¡¼ö´Â %dÀÔ´Ï´Ù.", score); + + if (score >= 90) { // score°¡ 90Á¡ º¸´Ù °°°Å³ª Å©¸é AÇÐÁ¡(grade) + grade = 'A'; + if (score >= 98) { // 90Á¡ ÀÌ»ó Áß¿¡¼­µµ 98Á¡ ÀÌ»óÀº A+ + opt = '+'; + } else if (score < 94) { // 90Á¡ ÀÌ»ó 94Á¡ ¹Ì¸¸Àº A- + opt = '-'; + } + } else if (score >= 80){ // score°¡ 80Á¡ º¸´Ù °°°Å³ª Å©¸é BÇÐÁ¡(grade) + grade = 'B'; + if (score >= 88) { + opt = '+'; + } else if (score < 84) { + opt = '-'; + } + } else { // ³ª¸ÓÁö´Â CÇÐÁ¡(grade) + grade = 'C'; + } + + System.out.printf("´ç½ÅÀÇ ÇÐÁ¡Àº %c%cÀÔ´Ï´Ù.%n", grade, opt); + } +} diff --git a/source/ch4/FlowEx6.java b/source/ch4/FlowEx6.java new file mode 100644 index 0000000..be88139 --- /dev/null +++ b/source/ch4/FlowEx6.java @@ -0,0 +1,30 @@ +import java.util.*; + +class FlowEx6 { + public static void main(String[] args) { + int month = 0; + + System.out.print("ÇöÀç ¿ùÀ» ÀÔ·ÂÇϼ¼¿ä.>"); + + Scanner scanner = new Scanner(System.in); + String tmp = scanner.nextLine(); // È­¸éÀ» ÅëÇØ ÀԷ¹ÞÀº ³»¿ëÀ» tmp¿¡ ÀúÀå + month = Integer.parseInt(tmp); // ÀԷ¹ÞÀº ¹®ÀÚ¿­(tmp)À» ¼ýÀÚ·Î º¯È¯ + + switch(month) { + case 3: + case 4: + case 5: + System.out.println("ÇöÀçÀÇ °èÀýÀº º½ÀÔ´Ï´Ù."); + break; + case 6: case 7: case 8: + System.out.println("ÇöÀçÀÇ °èÀýÀº ¿©¸§ÀÔ´Ï´Ù."); + break; + case 9: case 10: case 11: + System.out.println("ÇöÀçÀÇ °èÀýÀº °¡À»ÀÔ´Ï´Ù."); + break; + default: + // case 12: case 1: case 2: + System.out.println("ÇöÀçÀÇ °èÀýÀº °Ü¿ïÀÔ´Ï´Ù."); + } + } // mainÀÇ ³¡ +} diff --git a/source/ch4/FlowEx7.java b/source/ch4/FlowEx7.java new file mode 100644 index 0000000..cdfff06 --- /dev/null +++ b/source/ch4/FlowEx7.java @@ -0,0 +1,30 @@ +import java.util.*; + +class FlowEx7 { + public static void main(String[] args) { + int user, com; + + System.out.print("°¡À§(1),¹ÙÀ§(2), º¸(3) Áß Çϳª¸¦ ÀÔ·ÂÇϼ¼¿ä.>"); + + Scanner scanner = new Scanner(System.in); + String tmp = scanner.nextLine(); // È­¸éÀ» ÅëÇØ ÀԷ¹ÞÀº ³»¿ëÀ» tmp¿¡ ÀúÀå + user = Integer.parseInt(tmp); // ÀԷ¹ÞÀº ¹®ÀÚ¿­(tmp)¸¦ ¼ýÀÚ·Î º¯È¯ + + com = (int)(Math.random() * 3) + 1; // 1,2,3Áß Çϳª°¡ com¿¡ ÀúÀåµÊ + + System.out.println("´ç½ÅÀº "+ user +"ÀÔ´Ï´Ù."); + System.out.println("ÄÄÀº "+ com +"ÀÔ´Ï´Ù."); + + switch(user-com) { + case 2: case -1: + System.out.println("´ç½ÅÀÌ Á³½À´Ï´Ù."); + break; + case 1: case -2: + System.out.println("´ç½ÅÀÌ ÀÌ°å½À´Ï´Ù."); + break; + case 0: + System.out.println("ºñ°å½À´Ï´Ù."); + // break; // ¸¶Áö¸· ¹®ÀåÀ̹ǷΠbreak¸¦ »ç¿ëÇÒ ÇÊ¿ä°¡ ¾ø´Ù. + } + } // mainÀÇ ³¡ +} diff --git a/source/ch4/FlowEx8.java b/source/ch4/FlowEx8.java new file mode 100644 index 0000000..62fac16 --- /dev/null +++ b/source/ch4/FlowEx8.java @@ -0,0 +1,28 @@ +import java.util.*; + +class FlowEx8 { + public static void main(String[] args) { + char gender; + String regNo = ""; + + System.out.print("´ç½ÅÀÇ ÁֹιøÈ£¸¦ ÀÔ·ÂÇϼ¼¿ä.(011231-1111222)>"); + + Scanner scanner = new Scanner(System.in); + regNo = scanner.nextLine(); + + gender = regNo.charAt(7); // ÀԷ¹ÞÀº ¹øÈ£ÀÇ 8¹ø° ¹®ÀÚ¸¦ gender¿¡ ÀúÀå + + switch(gender) { + case '1': + case '3': + System.out.println("´ç½ÅÀº ³²ÀÚÀÔ´Ï´Ù."); + break; + case '2': + case '4': + System.out.println("´ç½ÅÀº ¿©ÀÚÀÔ´Ï´Ù."); + break; + default: + System.out.println("À¯È¿ÇÏÁö ¾ÊÀº Áֹεî·Ï¹øÈ£ÀÔ´Ï´Ù.");; + } + } // mainÀÇ ³¡ +} diff --git a/source/ch4/FlowEx9.java b/source/ch4/FlowEx9.java new file mode 100644 index 0000000..e8ca55e --- /dev/null +++ b/source/ch4/FlowEx9.java @@ -0,0 +1,36 @@ +import java.util.*; + +class FlowEx9 { + public static void main(String[] args) { + int score = 0; + char grade = ' '; + + System.out.print("´ç½ÅÀÇ Á¡¼ö¸¦ ÀÔ·ÂÇϼ¼¿ä.(1~100)>"); + + Scanner scanner = new Scanner(System.in); + String tmp = scanner.nextLine(); // È­¸éÀ» ÅëÇØ ÀԷ¹ÞÀº ³»¿ëÀ» tmp¿¡ ÀúÀå + score = Integer.parseInt(tmp); // ÀԷ¹ÞÀº ¹®ÀÚ¿­(tmp)¸¦ ¼ýÀÚ·Î º¯È¯ + + switch(score) { + case 100: case 99: case 98: case 97: case 96: + case 95: case 94: case 93: case 92: case 91: + case 90 : + grade = 'A'; + break; + case 89: case 88: case 87: case 86: + case 85: case 84: case 83: case 82: case 81: + case 80 : + grade = 'B'; + break; + case 79: case 78: case 77: case 76: + case 75: case 74: case 73: case 72: case 71: + case 70 : + grade = 'C'; + break; + default : + grade = 'F'; + } // end of switch + + System.out.println("´ç½ÅÀÇ ÇÐÁ¡Àº "+ grade +"ÀÔ´Ï´Ù."); + } // mainÀÇ ³¡ +} diff --git a/source/ch5/ArrayEx1.java b/source/ch5/ArrayEx1.java new file mode 100644 index 0000000..6e5cb80 --- /dev/null +++ b/source/ch5/ArrayEx1.java @@ -0,0 +1,22 @@ +class ArrayEx1 { + public static void main(String[] args) { + int[] score = new int[5]; + int k = 1; + + score[0] = 50; + score[1] = 60; + score[k+1] = 70; // score[2] = 70 + score[3] = 80; + score[4] = 90; + + int tmp = score[k+2] + score[4]; // int tmp = score[3] + score[4] + + // for¹®À¸·Î ¹è¿­ÀÇ ¸ðµç ¿ä¼Ò¸¦ Ãâ·ÂÇÑ´Ù. + for(int i=0; i < 5; i++) { + System.out.printf("score[%d]:%d%n",i, score[i]); + } + + System.out.printf("tmp:%d%n", tmp); + System.out.printf("score[%d]:%d%n",7,score[7]); //indexÀÇ ¹üÀ§¸¦ ¹þ¾î³­ °ª + } // main +} diff --git a/source/ch5/ArrayEx10.java b/source/ch5/ArrayEx10.java new file mode 100644 index 0000000..32b6e8a --- /dev/null +++ b/source/ch5/ArrayEx10.java @@ -0,0 +1,29 @@ +class ArrayEx10 { + public static void main(String[] args) { + int[] numArr = new int[10]; + + for (int i=0; i < numArr.length ; i++ ) { + System.out.print(numArr[i] = (int)(Math.random() * 10)); + } + System.out.println(); + + for (int i=0; i < numArr.length-1 ; i++ ) { + boolean changed = false; // ÀÚ¸®¹Ù²ÞÀÌ ¹ß»ýÇß´ÂÁö¸¦ üũÇÑ´Ù. + + for (int j=0; j < numArr.length-1-i ;j++) { + if(numArr[j] > numArr[j+1]) { // ¿·ÀÇ °ªÀÌ ÀÛÀ¸¸é ¼­·Î ¹Ù²Û´Ù. + int temp = numArr[j]; + numArr[j] = numArr[j+1]; + numArr[j+1] = temp; + changed = true; // ÀÚ¸®¹Ù²ÞÀÌ ¹ß»ýÇßÀ¸´Ï changed¸¦ true·Î. + } + } // end for j + + if (!changed) break; // ÀÚ¸®¹Ù²ÞÀÌ ¾øÀ¸¸é ¹Ýº¹¹®À» ¹þ¾î³­´Ù. + + for(int k=0; k='0' && hex[i] <='9') { + result +=binary[hex[i]-'0']; // '8'-'0'ÀÇ °á°ú´Â 8ÀÌ´Ù. + } else { // A~FÀ̸é + result +=binary[hex[i]-'A'+10]; // 'C'-'A'ÀÇ °á°ú´Â 2 + } + } + + System.out.println("hex:"+ new String(hex)); // String(char[] value) + System.out.println("binary:"+result); + } +} diff --git a/source/ch5/ArrayEx14.java b/source/ch5/ArrayEx14.java new file mode 100644 index 0000000..3b12d95 --- /dev/null +++ b/source/ch5/ArrayEx14.java @@ -0,0 +1,14 @@ +class ArrayEx14 { + public static void main(String[] args) { + String src = "ABCDE"; + + for(int i=0; i < src.length(); i++) { + char ch = src.charAt(i); // srcÀÇ i¹ø° ¹®ÀÚ¸¦ ch¿¡ ÀúÀå + System.out.println("src.charAt("+i+"):"+ ch); + } + + char[] chArr = src.toCharArray(); // StringÀ» char[]·Î º¯È¯ + + System.out.println(chArr); // char¹è¿­(char[])À» Ãâ·Â + } +} diff --git a/source/ch5/ArrayEx15.java b/source/ch5/ArrayEx15.java new file mode 100644 index 0000000..59a7b62 --- /dev/null +++ b/source/ch5/ArrayEx15.java @@ -0,0 +1,19 @@ +class ArrayEx15 { + public static void main(String[] args) { + String source = "SOSHELP"; + String[] morse = {".-", "-...", "-.-.","-..", "." + ,"..-.", "--.", "....","..",".---" + , "-.-", ".-..", "--", "-.", "---" + , ".--.", "--.-",".-.","...","-" + , "..-", "...-", ".--", "-..-","-.--" + , "--.." }; + + String result=""; + + for (int i=0; i < source.length() ; i++ ) { + result+=morse[source.charAt(i)-'A']; + } + System.out.println("source:"+ source); + System.out.println("morse:"+result); + } +} diff --git a/source/ch5/ArrayEx16.java b/source/ch5/ArrayEx16.java new file mode 100644 index 0000000..5d8d943 --- /dev/null +++ b/source/ch5/ArrayEx16.java @@ -0,0 +1,9 @@ +class ArrayEx16 { + public static void main(String[] args) { + System.out.println("¸Å°³º¯¼öÀÇ °³¼ö:"+args.length); + + for(int i=0;i< args.length;i++) { + System.out.println("args[" + i + "] = \""+ args[i] + "\""); + } + } +} diff --git a/source/ch5/ArrayEx17.java b/source/ch5/ArrayEx17.java new file mode 100644 index 0000000..b21cbe1 --- /dev/null +++ b/source/ch5/ArrayEx17.java @@ -0,0 +1,33 @@ +class ArrayEx17 { + public static void main(String[] args) { + if (args.length !=3) { + System.out.println("usage: java ArrayEx15 NUM1 OP NUM2"); + System.exit(0); + } + + int num1 = Integer.parseInt(args[0]); // ¹®ÀÚ¿­À» ¼ýÀÚ·Î º¯È¯ÇÑ´Ù. + char op = args[1].charAt(0); // ¹®ÀÚ¿­À» ¹®ÀÚ(char)·Î º¯È¯ÇÑ´Ù. + int num2 = Integer.parseInt(args[2]); + + int result = 0; + + switch(op) { // switch¹®ÀÇ ¼ö½ÄÀ¸·Î charŸÀÔÀÇ º¯¼öµµ °¡´ÉÇÏ´Ù. + case '+': + result = num1 + num2; + break; + case '-': + result = num1 - num2; + break; + case 'x': + result = num1 * num2; + break; + case '/': + result = num1 / num2; + break; + default : + System.out.println("Áö¿øµÇÁö ¾Ê´Â ¿¬»êÀÔ´Ï´Ù."); + } + + System.out.println("°á°ú:"+result); + } +} diff --git a/source/ch5/ArrayEx18.java b/source/ch5/ArrayEx18.java new file mode 100644 index 0000000..666297e --- /dev/null +++ b/source/ch5/ArrayEx18.java @@ -0,0 +1,25 @@ +class ArrayEx18 { + public static void main(String[] args) { + int[][] score = { + { 100, 100, 100} + , { 20, 20, 20} + , { 30, 30, 30} + , { 40, 40, 40} + }; + int sum = 0; + + for(int i=0;i < score.length;i++) { + for(int j=0;j < score[i].length;j++) { + System.out.printf("score[%d][%d]=%d%n", i, j, score[i][j]); + } + } + + for (int[] tmp : score) { + for (int i : tmp) { + sum += i; + } + } + + System.out.println("sum="+sum); + } +} diff --git a/source/ch5/ArrayEx19.java b/source/ch5/ArrayEx19.java new file mode 100644 index 0000000..e9c2a89 --- /dev/null +++ b/source/ch5/ArrayEx19.java @@ -0,0 +1,39 @@ +class ArrayEx19 { + public static void main(String[] args) { + int[][] score = { + { 100, 100, 100} + , { 20, 20, 20} + , { 30, 30, 30} + , { 40, 40, 40} + , { 50, 50, 50} + }; + // °ú¸ñº° ÃÑÁ¡ + int korTotal = 0; + int engTotal = 0; + int mathTotal = 0; + + System.out.println("¹øÈ£ ±¹¾î ¿µ¾î ¼öÇÐ ÃÑÁ¡ Æò±Õ "); + System.out.println("============================="); + + for(int i=0;i < score.length;i++) { + int sum = 0; // °³Àκ° ÃÑÁ¡ + float avg = 0.0f; // °³Àκ° Æò±Õ + + korTotal += score[i][0]; + engTotal += score[i][1]; + mathTotal += score[i][2]; + System.out.printf("%3d", i+1); + + for(int j=0;j < score[i].length;j++) { + sum += score[i][j]; + System.out.printf("%5d", score[i][j]); + } + + avg = sum/(float)score[i].length; // Æò±Õ°è»ê + System.out.printf("%5d %5.1f%n", sum, avg); + } + + System.out.println("============================="); + System.out.printf("ÃÑÁ¡:%3d %4d %4d%n", korTotal, engTotal, mathTotal); + } +} diff --git a/source/ch5/ArrayEx2.java b/source/ch5/ArrayEx2.java new file mode 100644 index 0000000..5467092 --- /dev/null +++ b/source/ch5/ArrayEx2.java @@ -0,0 +1,30 @@ +import java.util.*; // Arrays.toString()À» »ç¿ëÇϱâ À§ÇØ Ãß°¡ + +class ArrayEx2 { + public static void main(String[] args) { + int[] iArr1 = new int[10]; + int[] iArr2 = new int[10]; +// int[] iArr3 = new int[]{100, 95, 80, 70, 60}; + int[] iArr3 = {100, 95, 80, 70, 60}; + char[] chArr = {'a', 'b', 'c', 'd'}; + + for (int i=0; i < iArr1.length ; i++ ) { + iArr1[i] = i + 1; // 1~10ÀÇ ¼ýÀÚ¸¦ ¼ø¼­´ë·Î ¹è¿­¿¡ ³Ö´Â´Ù. + } + + for (int i=0; i < iArr2.length ; i++ ) { + iArr2[i] = (int)(Math.random()*10) + 1; // 1~10ÀÇ °ªÀ» ¹è¿­¿¡ ÀúÀå + } + + // ¹è¿­¿¡ ÀúÀåµÈ °ªµéÀ» Ãâ·ÂÇÑ´Ù. + for(int i=0; i < iArr1.length;i++) { + System.out.print(iArr1[i]+","); + } + System.out.println(); + System.out.println(Arrays.toString(iArr2)); + System.out.println(Arrays.toString(iArr3)); + System.out.println(Arrays.toString(chArr)); + System.out.println(iArr3); + System.out.println(chArr); + } +} diff --git a/source/ch5/ArrayEx3.java b/source/ch5/ArrayEx3.java new file mode 100644 index 0000000..23f7f2a --- /dev/null +++ b/source/ch5/ArrayEx3.java @@ -0,0 +1,25 @@ +class ArrayEx3{ + public static void main(String[] args) { + int[] arr = new int[5]; + + // ¹è¿­ arr¿¡ 1~5¸¦ ÀúÀåÇÑ´Ù. + for(int i=0; i < arr.length;i++) + arr[i] = i + 1; + + System.out.println("º¯°æÀü - arr.length:"+arr.length); + for(int i=0; i < arr.length;i++) + System.out.println("arr["+i+"]:"+arr[i]); + + int[] tmp = new int[arr.length*2]; + + // ¹è¿­ arr¿¡ ÀúÀåµÈ °ªµéÀ» ¹è¿­ tmp¿¡ º¹»çÇÑ´Ù. + for(int i=0; i < arr.length;i++) + tmp[i] = arr[i]; + + arr = tmp; // tmp¿¡ ÀúÀåµÈ °ªÀ» arr¿¡ ÀúÀåÇÑ´Ù. + + System.out.println("º¯°æÈÄ - arr.length:"+arr.length); + for(int i=0; i < arr.length;i++) + System.out.println("arr["+i+"]:"+arr[i]); + } +} diff --git a/source/ch5/ArrayEx4.java b/source/ch5/ArrayEx4.java new file mode 100644 index 0000000..5e3dda9 --- /dev/null +++ b/source/ch5/ArrayEx4.java @@ -0,0 +1,22 @@ +class ArrayEx4 { + public static void main(String[] args) { + char[] abc = { 'A', 'B', 'C', 'D'}; + char[] num = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; + System.out.println(abc); + System.out.println(num); + + // ¹è¿­ abc¿Í numÀ» ºÙ¿©¼­ ÇϳªÀÇ ¹è¿­(result)·Î ¸¸µç´Ù. + char[] result = new char[abc.length+num.length]; + System.arraycopy(abc, 0, result, 0, abc.length); + System.arraycopy(num, 0, result, abc.length, num.length); + System.out.println(result); + + // ¹è¿­ abcÀ» ¹è¿­ numÀÇ Ã¹ ¹ø° À§Ä¡ºÎÅÍ ¹è¿­ abcÀÇ ±æÀ̸¸Å­ º¹»ç + System.arraycopy(abc, 0, num, 0, abc.length); + System.out.println(num); + + // numberÀÇ À妽º6 À§Ä¡¿¡ 3°³¸¦ º¹»ç + System.arraycopy(abc, 0, num, 6, 3); + System.out.println(num); + } +} diff --git a/source/ch5/ArrayEx5.java b/source/ch5/ArrayEx5.java new file mode 100644 index 0000000..36f9008 --- /dev/null +++ b/source/ch5/ArrayEx5.java @@ -0,0 +1,17 @@ +class ArrayEx5 { + public static void main(String[] args) { + int sum =0; // ÃÑÁ¡À» ÀúÀåÇϱâ À§ÇÑ º¯¼ö + float average = 0f; // Æò±ÕÀ» ÀúÀåÇϱâ À§ÇÑ º¯¼ö + + int[] score = {100, 88, 100, 100, 90}; + + for (int i=0; i < score.length ; i++ ) { + sum += score[i]; + } + + average = sum / (float)score.length ; // °è»ê°á°ú¸¦ float·Î ¾ò±â À§ÇÔ. + + System.out.println("ÃÑÁ¡ : " + sum); + System.out.println("Æò±Õ : " + average); + } +} diff --git a/source/ch5/ArrayEx6.java b/source/ch5/ArrayEx6.java new file mode 100644 index 0000000..ad0061d --- /dev/null +++ b/source/ch5/ArrayEx6.java @@ -0,0 +1,19 @@ +class ArrayEx6 { + public static void main(String[] args) { + int[] score = { 79, 88, 91, 33, 100, 55, 95}; + + int max = score[0]; // ¹è¿­ÀÇ Ã¹ ¹ø° °ªÀ¸·Î ÃÖ´ë°ªÀ» ÃʱâÈ­ ÇÑ´Ù. + int min = score[0]; // ¹è¿­ÀÇ Ã¹ ¹ø° °ªÀ¸·Î ÃÖ¼Ò°ªÀ» ÃʱâÈ­ ÇÑ´Ù. + + for(int i=1; i < score.length;i++) { + if(score[i] > max) { + max = score[i]; + } else if(score[i] < min) { + min = score[i]; + } + } // end of for + + System.out.println("ÃÖ´ë°ª :" + max); + System.out.println("ÃÖ¼Ò°ª :" + min); + } // end of main +} // end of class diff --git a/source/ch5/ArrayEx7.java b/source/ch5/ArrayEx7.java new file mode 100644 index 0000000..804e489 --- /dev/null +++ b/source/ch5/ArrayEx7.java @@ -0,0 +1,22 @@ +class ArrayEx7 { + public static void main(String[] args) { + int[] numArr = new int[10]; + + for (int i=0; i < numArr.length ; i++ ) { + numArr[i] = i; // ¹è¿­À» 0~9ÀÇ ¼ýÀÚ·Î ÃʱâÈ­ÇÑ´Ù. + System.out.print(numArr[i]); + } + System.out.println(); + + for (int i=0; i < 100; i++ ) { + int n = (int)(Math.random() * 10); // 0~9ÁßÀÇ ÇÑ °ªÀ» ÀÓÀÇ·Î ¾ò´Â´Ù. + + int tmp = numArr[0]; + numArr[0] = numArr[n]; + numArr[n] = tmp; + } + + for (int i=0; i < numArr.length ; i++ ) + System.out.print(numArr[i]); + } // mainÀÇ ³¡ +} diff --git a/source/ch5/ArrayEx8.java b/source/ch5/ArrayEx8.java new file mode 100644 index 0000000..cd95d9d --- /dev/null +++ b/source/ch5/ArrayEx8.java @@ -0,0 +1,26 @@ +class ArrayEx8 { + public static void main(String[] args) { + // 45°³ÀÇ Á¤¼ö°ªÀ» ÀúÀåÇϱâ À§ÇÑ ¹è¿­ »ý¼º. + int[] ball = new int[45]; + + // ¹è¿­ÀÇ °¢ ¿ä¼Ò¿¡ 1~45ÀÇ °ªÀ» ÀúÀåÇÑ´Ù. + for(int i=0; i < ball.length; i++) + ball[i] = i+1; // ball[0]¿¡ 1ÀÌ ÀúÀåµÈ´Ù. + + int temp = 0; // µÎ °ªÀ» ¹Ù²Ù´Âµ¥ »ç¿ëÇÒ Àӽú¯¼ö + int j = 0; // ÀÓÀÇÀÇ °ªÀ» ¾ò¾î¼­ ÀúÀåÇÒ º¯¼ö + + // ¹è¿­ÀÇ i¹ø° ¿ä¼Ò¿Í ÀÓÀÇÀÇ ¿ä¼Ò¿¡ ÀúÀåµÈ °ªÀ» ¼­·Î ¹Ù²ã¼­ °ªÀ» ¼¯´Â´Ù. + // 0¹ø° ºÎÅÍ 5¹ø° ¿ä¼Ò±îÁö ¸ðµÎ 6°³¸¸ ¹Ù²Û´Ù. + for(int i=0; i < 6; i++) { + j = (int)(Math.random() * 45); // 0~44¹üÀ§ÀÇ ÀÓÀÇÀÇ °ªÀ» ¾ò´Â´Ù. + temp = ball[i]; + ball[i] = ball[j]; + ball[j] = temp; + } + + // ¹è¿­ ballÀÇ ¾Õ¿¡¼­ ºÎÅÍ 6°³ÀÇ ¿ä¼Ò¸¦ Ãâ·ÂÇÑ´Ù. + for(int i=0; i < 6; i++) + System.out.printf("ball[%d]=%d%n", i, ball[i]); + } +} diff --git a/source/ch5/ArrayEx9.java b/source/ch5/ArrayEx9.java new file mode 100644 index 0000000..43656a4 --- /dev/null +++ b/source/ch5/ArrayEx9.java @@ -0,0 +1,15 @@ +import java.util.*; // Arrays.toString()À» »ç¿ëÇϱâ À§ÇØ Ãß°¡ + +class ArrayEx9 { + public static void main(String[] args) { + int[] code = { -4, -1, 3, 6, 11 }; // ºÒ¿¬¼ÓÀûÀÎ °ªµé·Î ±¸¼ºµÈ ¹è¿­ + int[] arr = new int[10]; + + for (int i=0; i < arr.length ; i++ ) { + int tmp = (int)(Math.random() * code.length); + arr[i] = code[tmp]; + } + + System.out.println(Arrays.toString(arr)); + } // mainÀÇ ³¡ +} diff --git a/source/ch5/MultiArrEx1.java b/source/ch5/MultiArrEx1.java new file mode 100644 index 0000000..c145f99 --- /dev/null +++ b/source/ch5/MultiArrEx1.java @@ -0,0 +1,55 @@ +import java.util.*; + +class MultiArrEx1 { + public static void main(String[] args) { + final int SIZE = 10; + int x = 0, y = 0; + + char[][] board = new char[SIZE][SIZE]; + byte[][] shipBoard = { + // 1 2 3 4 5 6 7 8 9 + { 0, 0, 0, 0, 0, 0, 1, 0, 0 }, // 1 + { 1, 1, 1, 1, 0, 0, 1, 0, 0 }, // 2 + { 0, 0, 0, 0, 0, 0, 1, 0, 0 }, // 3 + { 0, 0, 0, 0, 0, 0, 1, 0, 0 }, // 4 + { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, // 5 + { 1, 1, 0, 1, 0, 0, 0, 0, 0 }, // 6 + { 0, 0, 0, 1, 0, 0, 0, 0, 0 }, // 7 + { 0, 0, 0, 1, 0, 0, 0, 0, 0 }, // 8 + { 0, 0, 0, 0, 0, 1, 1, 1, 0 }, // 9 + }; + + // 0Çà¿¡ Çà¹øÈ£¸¦, 0¿­¿¡ ¿­¹øÈ£¸¦ ÀúÀåÇÑ´Ù. + for(int i=1;i"); + String input = scanner.nextLine(); // È­¸éÀԷ¹ÞÀº ³»¿ëÀ» tmp¿¡ ÀúÀå + + if(input.length()==2) { // µÎ ±ÛÀÚ¸¦ ÀÔ·ÂÇÑ °æ¿ì + x = input.charAt(0) - '0'; // ¹®ÀÚ¸¦ ¼ýÀÚ·Î º¯È¯ + y = input.charAt(1) - '0'; + + if(x==0 && y==0) // x¿Í y°¡ ¸ðµÎ 0ÀÎ °æ¿ì Á¾·á + break; + } + + if(input.length()!=2 || x <= 0 || x >= SIZE || y <= 0 || y >= SIZE){ + System.out.println("À߸øµÈ ÀÔ·ÂÀÔ´Ï´Ù. ´Ù½Ã ÀÔ·ÂÇØÁÖ¼¼¿ä."); + continue; + } + + // shipBoard[x-1][y-1]ÀÇ °ªÀÌ 1À̸é, 'O'À» board[x][y]¿¡ ÀúÀåÇÑ´Ù. + board[x][y] = shipBoard[x-1][y-1]==1 ? 'O' : 'X'; + + // ¹è¿­ boardÀÇ ³»¿ëÀ» È­¸é¿¡ Ãâ·ÂÇÑ´Ù. + for(int i=0;i", SIZE*SIZE); + String tmp = scanner.nextLine(); // È­¸é¿¡¼­ ÀԷ¹ÞÀº ³»¿ëÀ» tmp¿¡ ÀúÀå + num = Integer.parseInt(tmp); // ÀԷ¹ÞÀº ¹®ÀÚ¿­(tmp)¸¦ ¼ýÀÚ·Î º¯È¯ + + // ÀԷ¹ÞÀº ¼ýÀÚ¿Í °°Àº ¼ýÀÚ°¡ ÀúÀåµÈ ¿ä¼Ò¸¦ ã¾Æ¼­ 0À» ÀúÀå + outer: + for(int i=0;i20) return -1; // ¸Å°³º¯¼öÀÇ À¯È¿¼º °Ë»ç. + if(n<=1) + return 1; + return n * factorial(n-1); + } + + public static void main(String args[]) { + int n = 21; + long result = 0; + + for(int i = 1; i <= n; i++) { + result = factorial(i); + + if(result==-1) { + System.out.printf("À¯È¿ÇÏÁö ¾ÊÀº °ªÀÔ´Ï´Ù.(0 arr[j+1]) { + int tmp = arr[j]; + arr[j] = arr[j+1]; + arr[j+1] = tmp; + } + } // sortArr(int[] arr) +} diff --git a/source/ch6/ReferenceReturnEx.java b/source/ch6/ReferenceReturnEx.java new file mode 100644 index 0000000..6e52f2a --- /dev/null +++ b/source/ch6/ReferenceReturnEx.java @@ -0,0 +1,20 @@ +class Data { int x; } + +class ReferenceReturnEx { + public static void main(String[] args) + { + Data d = new Data(); + d.x = 10; + + Data d2 = copy(d); + System.out.println("d.x ="+d.x); + System.out.println("d2.x="+d2.x); + } + + static Data copy(Data d) { + Data tmp = new Data(); + tmp.x = d.x; + + return tmp; + } +} diff --git a/source/ch6/ReturnTest.java b/source/ch6/ReturnTest.java new file mode 100644 index 0000000..c14e000 --- /dev/null +++ b/source/ch6/ReturnTest.java @@ -0,0 +1,20 @@ +class ReturnTest { + public static void main(String[] args) { + ReturnTest r = new ReturnTest(); + + int result = r.add(3,5); + System.out.println(result); + + int[] result2 = {0}; // ¹è¿­À» »ý¼ºÇÏ°í result2[0]ÀÇ °ªÀ» 0À¸·Î ÃʱâÈ­ + r.add(3,5,result2); // ¹è¿­À» add¸Þ¼­µåÀÇ ¸Å°³º¯¼ö·Î Àü´Þ + System.out.println(result2[0]); + } + + int add(int a, int b) { + return a + b; + } + + void add(int a, int b, int[] result) { + result[0] = a + b; // ¸Å°³º¯¼ö·Î ³Ñ°Ü¹ÞÀº ¹è¿­¿¡ ¿¬»ê°á°ú¸¦ ÀúÀå + } +} diff --git a/source/ch6/StaticBlockTest.java b/source/ch6/StaticBlockTest.java new file mode 100644 index 0000000..8d69cfb --- /dev/null +++ b/source/ch6/StaticBlockTest.java @@ -0,0 +1,16 @@ +class StaticBlockTest +{ + static int[] arr = new int[10]; + + static { + for(int i=0;i 0; k--) + for(int n=0; n < Card.NUM_MAX ; n++) + cardArr[i++] = new Card(k, n+1); + } + + Card pick(int index) { // ÁöÁ¤µÈ À§Ä¡(index)¿¡ ÀÖ´Â Ä«µå Çϳª¸¦ ²¨³»¼­ ¹Ýȯ + return cardArr[index]; + } + + Card pick() { // Deck¿¡¼­ Ä«µå Çϳª¸¦ ¼±ÅÃÇÑ´Ù. + int index = (int)(Math.random() * CARD_NUM); + return pick(index); + } + + void shuffle() { // Ä«µåÀÇ ¼ø¼­¸¦ ¼¯´Â´Ù. + for(int i=0; i < cardArr.length; i++) { + int r = (int)(Math.random() * CARD_NUM); + + Card temp = cardArr[i]; + cardArr[i] = cardArr[r]; + cardArr[r] = temp; + } + } +} // DeckŬ·¡½ºÀÇ ³¡ + +// CardŬ·¡½º +class Card { + static final int KIND_MAX = 4; // Ä«µå ¹«´ÌÀÇ ¼ö + static final int NUM_MAX = 13; // ¹«´Ìº° Ä«µå ¼ö + + static final int SPADE = 4; + static final int DIAMOND = 3; + static final int HEART = 2; + static final int CLOVER = 1; + + int kind; + int number; + + Card() { + this(SPADE, 1); + } + + Card(int kind, int number) { + this.kind = kind; + this.number = number; + } + + public String toString() { + String[] kinds = {"", "CLOVER", "HEART", "DIAMOND", "SPADE"}; + String numbers = "0123456789XJQK"; // ¼ýÀÚ 10Àº X·Î Ç¥Çö + + return "kind : " + kinds[this.kind] + + ", number : " + numbers.charAt(this.number); + } // toString()ÀÇ ³¡ +} // CardŬ·¡½ºÀÇ ³¡ diff --git a/source/ch7/DefaultMethodTest.java b/source/ch7/DefaultMethodTest.java new file mode 100644 index 0000000..db20543 --- /dev/null +++ b/source/ch7/DefaultMethodTest.java @@ -0,0 +1,45 @@ +class DefaultMethodTest { + public static void main(String[] args) { + Child c = new Child(); + c.method1(); + c.method2(); + MyInterface.staticMethod(); + MyInterface2.staticMethod(); + } +} + +class Child extends Parent implements MyInterface, MyInterface2 { + public void method1() { + System.out.println("method1() in Child"); // ¿À¹ö¶óÀ̵ù + } +} + +class Parent { + public void method2() { + System.out.println("method2() in Parent"); + } +} + +interface MyInterface { + default void method1() { + System.out.println("method1() in MyInterface"); + } + + default void method2() { + System.out.println("method2() in MyInterface"); + } + + static void staticMethod() { + System.out.println("staticMethod() in MyInterface"); + } +} + +interface MyInterface2 { + default void method1() { + System.out.println("method1() in MyInterface2"); + } + + static void staticMethod() { + System.out.println("staticMethod() in MyInterface2"); + } +} diff --git a/source/ch7/DrawShape.java b/source/ch7/DrawShape.java new file mode 100644 index 0000000..a37edd7 --- /dev/null +++ b/source/ch7/DrawShape.java @@ -0,0 +1,69 @@ +class DrawShape { + public static void main(String[] args) { + Point[] p = { new Point(100, 100), + new Point(140, 50), + new Point(200, 100) + }; + + Triangle t = new Triangle(p); + Circle c = new Circle(new Point(150, 150), 50); + + t.draw(); // »ï°¢ÇüÀ» ±×¸°´Ù. + c.draw(); // ¿øÀ» ±×¸°´Ù. + } +} + +class Shape { + String color = "black"; + void draw() { + System.out.printf("[color=%s]%n", color); + } +} + +class Point { + int x; + int y; + + Point(int x, int y) { + this.x = x; + this.y = y; + } + + Point() { + this(0,0); + } + + String getXY() { + return "("+x+","+y+")"; // x¿Í yÀÇ °ªÀ» ¹®ÀÚ¿­·Î ¹Ýȯ + } +} + +class Circle extends Shape { + Point center; // ¿øÀÇ ¿øÁ¡ÁÂÇ¥ + int r; // ¹ÝÁö¸§ + + Circle() { + this(new Point(0, 0), 100); // Circle(Point center, int r)¸¦ È£Ãâ + } + + Circle(Point center, int r) { + this.center = center; + this.r = r; + } + + void draw() { // ¿øÀ» ±×¸®´Â ´ë½Å¿¡ ¿øÀÇ Á¤º¸¸¦ Ãâ·ÂÇϵµ·Ï Çß´Ù. + System.out.printf("[center=(%d, %d), r=%d, color=%s]%n", center.x, center.y, r, color); + } +} + +class Triangle extends Shape { + Point[] p = new Point[3]; + + Triangle(Point[] p) { + this.p = p; + } + + void draw() { + System.out.printf("[p1=%s, p2=%s, p3=%s, color=%s]%n", p[0].getXY(), p[1].getXY(), p[2].getXY(), color); + } +} diff --git a/source/ch7/FighterTest.java b/source/ch7/FighterTest.java new file mode 100644 index 0000000..c31ad46 --- /dev/null +++ b/source/ch7/FighterTest.java @@ -0,0 +1,36 @@ +class FighterTest { + public static void main(String[] args) { + Fighter f = new Fighter(); + + if (f instanceof Unit) { + System.out.println("f´Â UnitŬ·¡½ºÀÇ ÀÚ¼ÕÀÔ´Ï´Ù."); + } + if (f instanceof Fightable) { + System.out.println("f´Â FightableÀÎÅÍÆäÀ̽º¸¦ ±¸ÇöÇß½À´Ï´Ù."); + } + if (f instanceof Movable) { + System.out.println("f´Â MovableÀÎÅÍÆäÀ̽º¸¦ ±¸ÇöÇß½À´Ï´Ù."); + } + if (f instanceof Attackable) { + System.out.println("f´Â AttackableÀÎÅÍÆäÀ̽º¸¦ ±¸ÇöÇß½À´Ï´Ù."); + } + if (f instanceof Object) { + System.out.println("f´Â ObjectŬ·¡½ºÀÇ ÀÚ¼ÕÀÔ´Ï´Ù."); + } + } +} + +class Fighter extends Unit implements Fightable { + public void move(int x, int y) { /* ³»¿ë »ý·« */ } + public void attack(Unit u) { /* ³»¿ë »ý·« */ } +} + +class Unit { + int currentHP; // À¯´ÖÀÇ Ã¼·Â + int x; // À¯´ÖÀÇ À§Ä¡(xÁÂÇ¥) + int y; // À¯´ÖÀÇ À§Ä¡(yÁÂÇ¥) +} + +interface Fightable extends Movable, Attackable { } +interface Movable { void move(int x, int y); } +interface Attackable { void attack(Unit u); } diff --git a/source/ch7/FinalCardTest.java b/source/ch7/FinalCardTest.java new file mode 100644 index 0000000..9235f0e --- /dev/null +++ b/source/ch7/FinalCardTest.java @@ -0,0 +1,29 @@ +class Card { + final int NUMBER; // »ó¼öÁö¸¸ ¼±¾ð°ú ÇÔ²² ÃʱâÈ­ ÇÏÁö ¾Ê°í + final String KIND; // »ý¼ºÀÚ¿¡¼­ ´Ü Çѹø¸¸ ÃʱâÈ­ÇÒ ¼ö ÀÖ´Ù. + static int width = 100; + static int height = 250; + + Card(String kind, int num) { + KIND = kind; + NUMBER = num; + } + + Card() { + this("HEART", 1); + } + + public String toString() { + return KIND +" "+ NUMBER; + } +} + +class FinalCardTest { + public static void main(String args[]) { + Card c = new Card("HEART", 10); +// c.NUMBER = 5; + System.out.println(c.KIND); + System.out.println(c.NUMBER); + System.out.println(c); // System.out.println(c.toString()); + } +} diff --git a/source/ch7/ImportTest.java b/source/ch7/ImportTest.java new file mode 100644 index 0000000..a524a08 --- /dev/null +++ b/source/ch7/ImportTest.java @@ -0,0 +1,16 @@ +import java.text.SimpleDateFormat; +import java.util.Date; + +class ImportTest +{ + public static void main(String[] args) + { + Date today = new Date(); + + SimpleDateFormat date = new SimpleDateFormat("yyyy/MM/dd"); + SimpleDateFormat time = new SimpleDateFormat("hh:mm:ss a"); + + System.out.println("¿À´Ã ³¯Â¥´Â " + date.format(today)); + System.out.println("ÇöÀç ½Ã°£Àº " + time.format(today)); + } +} diff --git a/source/ch7/InnerEx1.java b/source/ch7/InnerEx1.java new file mode 100644 index 0000000..a9b5f36 --- /dev/null +++ b/source/ch7/InnerEx1.java @@ -0,0 +1,25 @@ +class InnerEx1 { + class InstanceInner { + int iv = 100; +// static int cv = 100; // ¿¡·¯! staticº¯¼ö¸¦ ¼±¾ðÇÒ ¼ö ¾ø´Ù. + final static int CONST = 100; // final staticÀº »ó¼öÀ̹ǷΠÇã¿ëÇÑ´Ù. + } + + static class StaticInner { + int iv = 200; + static int cv = 200; // staticŬ·¡½º¸¸ static¸â¹ö¸¦ Á¤ÀÇÇÒ ¼ö ÀÖ´Ù. + } + + void myMethod() { + class LocalInner { + int iv = 300; +// static int cv = 300; // ¿¡·¯! staticº¯¼ö¸¦ ¼±¾ðÇÒ ¼ö ¾ø´Ù. + final static int CONST = 300; // final staticÀº »ó¼öÀ̹ǷΠÇã¿ë + } + } + + public static void main(String args[]) { + System.out.println(InstanceInner.CONST); + System.out.println(StaticInner.cv); + } +} diff --git a/source/ch7/InnerEx2.java b/source/ch7/InnerEx2.java new file mode 100644 index 0000000..737ceff --- /dev/null +++ b/source/ch7/InnerEx2.java @@ -0,0 +1,33 @@ +class InnerEx2 { + class InstanceInner {} + static class StaticInner {} + + // ÀνºÅϽº¸â¹ö °£¿¡´Â ¼­·Î Á÷Á¢ Á¢±ÙÀÌ °¡´ÉÇÏ´Ù. + InstanceInner iv = new InstanceInner(); + // static ¸â¹ö °£¿¡´Â ¼­·Î Á÷Á¢ Á¢±ÙÀÌ °¡´ÉÇÏ´Ù. + static StaticInner cv = new StaticInner(); + + static void staticMethod() { + // static¸â¹ö´Â ÀνºÅϽº¸â¹ö¿¡ Á÷Á¢ Á¢±ÙÇÒ ¼ö ¾ø´Ù. +// InstanceInner obj1 = new InstanceInner(); + StaticInner obj2 = new StaticInner(); + + // ±»ÀÌ Á¢±ÙÇÏ·Á¸é ¾Æ·¡¿Í °°ÀÌ °´Ã¼¸¦ »ý¼ºÇØ¾ß ÇÑ´Ù. + // ÀνºÅϽºÅ¬·¡½º´Â ¿ÜºÎ Ŭ·¡½º¸¦ ¸ÕÀú »ý¼ºÇؾ߸¸ »ý¼ºÇÒ ¼ö ÀÖ´Ù. + InnerEx2 outer = new InnerEx2(); + InstanceInner obj1 = outer.new InstanceInner(); + } + + void instanceMethod() { + // ÀνºÅϽº¸Þ¼­µå¿¡¼­´Â ÀνºÅϽº¸â¹ö¿Í static¸â¹ö ¸ðµÎ Á¢±Ù °¡´ÉÇÏ´Ù. + InstanceInner obj1 = new InstanceInner(); + StaticInner obj2 = new StaticInner(); + // ¸Þ¼­µå ³»¿¡ Áö¿ªÀûÀ¸·Î ¼±¾ðµÈ ³»ºÎ Ŭ·¡½º´Â ¿ÜºÎ¿¡¼­ Á¢±ÙÇÒ ¼ö ¾ø´Ù. +// LocalInner lv = new LocalInner(); + } + + void myMethod() { + class LocalInner {} + LocalInner lv = new LocalInner(); + } +} diff --git a/source/ch7/InnerEx3.java b/source/ch7/InnerEx3.java new file mode 100644 index 0000000..8e1106e --- /dev/null +++ b/source/ch7/InnerEx3.java @@ -0,0 +1,28 @@ +class InnerEx3 { + private int outerIv = 0; + static int outerCv = 0; + + class InstanceInner { + int iiv = outerIv; // ¿ÜºÎ Ŭ·¡½ºÀÇ private¸â¹öµµ Á¢±Ù°¡´ÉÇÏ´Ù. + int iiv2 = outerCv; + } + + static class StaticInner { +// ½ºÅÂƽ Ŭ·¡½º´Â ¿ÜºÎ Ŭ·¡½ºÀÇ ÀνºÅϽº¸â¹ö¿¡ Á¢±ÙÇÒ ¼ö ¾ø´Ù. +// int siv = outerIv; + static int scv = outerCv; + } + + void myMethod() { + int lv = 0; + final int LV = 0; // JDK1.8ºÎÅÍ final »ý·« °¡´É + + class LocalInner { + int liv = outerIv; + int liv2 = outerCv; +// ¿ÜºÎ Ŭ·¡½ºÀÇ Áö¿ªº¯¼ö´Â finalÀÌ ºÙÀº º¯¼ö(»ó¼ö)¸¸ Á¢±Ù°¡´ÉÇÏ´Ù. +// int liv3 = lv; // ¿¡·¯!!!(JDK1.8ºÎÅÍ ¿¡·¯ ¾Æ´Ô) + int liv4 = LV; // OK + } + } +} diff --git a/source/ch7/InnerEx4.java b/source/ch7/InnerEx4.java new file mode 100644 index 0000000..9b12ec7 --- /dev/null +++ b/source/ch7/InnerEx4.java @@ -0,0 +1,31 @@ +class Outer { + class InstanceInner { + int iv=100; + } + static class StaticInner { + int iv=200; + static int cv=300; + } + + void myMethod() { + class LocalInner { + int iv=400; + } + } +} + +class InnerEx4 { + public static void main(String[] args) { + // ÀνºÅϽºÅ¬·¡½ºÀÇ ÀνºÅϽº¸¦ »ý¼ºÇÏ·Á¸é + // ¿ÜºÎ Ŭ·¡½ºÀÇ ÀνºÅϽº¸¦ ¸ÕÀú »ý¼ºÇØ¾ß ÇÑ´Ù. + Outer oc = new Outer(); + Outer.InstanceInner ii = oc.new InstanceInner(); + + System.out.println("ii.iv : "+ ii.iv); + System.out.println("Outer.StaticInner.cv : " + Outer.StaticInner.cv); + + // ½ºÅÂƽ ³»ºÎ Ŭ·¡½ºÀÇ ÀνºÅϽº´Â ¿ÜºÎ Ŭ·¡½º¸¦ ¸ÕÀú »ý¼ºÇÏÁö ¾Ê¾Æµµ µÈ´Ù. + Outer.StaticInner si = new Outer.StaticInner(); + System.out.println("si.iv : "+ si.iv); + } +} diff --git a/source/ch7/InnerEx5.java b/source/ch7/InnerEx5.java new file mode 100644 index 0000000..2c557aa --- /dev/null +++ b/source/ch7/InnerEx5.java @@ -0,0 +1,22 @@ +class Outer { + int value=10; // Outer.this.value + + class Inner { + int value=20; // this.value + + void method1() { + int value=30; + System.out.println(" value :" + value); + System.out.println(" this.value :" + this.value); + System.out.println("Outer.this.value :" + Outer.this.value); + } + } // InnerŬ·¡½ºÀÇ ³¡ +} // OuterŬ·¡½ºÀÇ ³¡ + +class InnerEx5 { + public static void main(String args[]) { + Outer outer = new Outer(); + Outer.Inner inner = outer.new Inner(); + inner.method1(); + } +} // InnerEx5 ³¡ diff --git a/source/ch7/InnerEx6.java b/source/ch7/InnerEx6.java new file mode 100644 index 0000000..e7cc874 --- /dev/null +++ b/source/ch7/InnerEx6.java @@ -0,0 +1,8 @@ +class InnerEx6 { + Object iv = new Object(){ void method(){} }; // À͸íŬ·¡½º + static Object cv = new Object(){ void method(){} }; // À͸íŬ·¡½º + + void myMethod() { + Object lv = new Object(){ void method(){} }; // À͸íŬ·¡½º + } +} diff --git a/source/ch7/InnerEx7.java b/source/ch7/InnerEx7.java new file mode 100644 index 0000000..1e7c5b3 --- /dev/null +++ b/source/ch7/InnerEx7.java @@ -0,0 +1,15 @@ +import java.awt.*; +import java.awt.event.*; + +class InnerEx7{ + public static void main(String[] args) { + Button b = new Button("Start"); + b.addActionListener(new EventHandler()); + } +} + +class EventHandler implements ActionListener { + public void actionPerformed(ActionEvent e) { + System.out.println("ActionEvent occurred!!!"); + } +} diff --git a/source/ch7/InnerEx8.java b/source/ch7/InnerEx8.java new file mode 100644 index 0000000..2ceadc2 --- /dev/null +++ b/source/ch7/InnerEx8.java @@ -0,0 +1,14 @@ +import java.awt.*; +import java.awt.event.*; + +class InnerEx8 { + public static void main(String[] args) { + Button b = new Button("Start"); + b.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + System.out.println("ActionEvent occurred!!!"); + } + } // À͸í Ŭ·¡½ºÀÇ ³¡ + ); + } // main¸Þ¼­µåÀÇ ³¡ +} // InnerEx8Ŭ·¡½ºÀÇ ³¡ diff --git a/source/ch7/InstanceofTest.java b/source/ch7/InstanceofTest.java new file mode 100644 index 0000000..0799765 --- /dev/null +++ b/source/ch7/InstanceofTest.java @@ -0,0 +1,21 @@ +class InstanceofTest { + public static void main(String args[]) { + FireEngine fe = new FireEngine(); + + if(fe instanceof FireEngine) { + System.out.println("This is a FireEngine instance."); + } + + if(fe instanceof Car) { + System.out.println("This is a Car instance."); + } + + if(fe instanceof Object) { + System.out.println("This is an Object instance."); + } + + System.out.println(fe.getClass().getName()); // Ŭ·¡½ºÀÇ À̸§À» Ãâ·Â + } +} // class +class Car {} +class FireEngine extends Car {} diff --git a/source/ch7/InterfaceTest.java b/source/ch7/InterfaceTest.java new file mode 100644 index 0000000..f614579 --- /dev/null +++ b/source/ch7/InterfaceTest.java @@ -0,0 +1,18 @@ +class A { + public void methodA(B b) { + b.methodB(); + } +} + +class B { + public void methodB() { + System.out.println("methodB()"); + } +} + +class InterfaceTest { + public static void main(String args[]) { + A a = new A(); + a.methodA(new B()); + } +} diff --git a/source/ch7/InterfaceTest2.java b/source/ch7/InterfaceTest2.java new file mode 100644 index 0000000..a988d68 --- /dev/null +++ b/source/ch7/InterfaceTest2.java @@ -0,0 +1,29 @@ + class A { + void autoPlay(I i) { + i.play(); + } + } + + interface I { + public abstract void play(); + } + + class B implements I { + public void play() { + System.out.println("play in B class"); + } + } + + class C implements I { + public void play() { + System.out.println("play in C class"); + } + } + +class InterfaceTest2 { + public static void main(String[] args) { + A a = new A(); + a.autoPlay(new B()); // void autoPlay(I i)È£Ãâ + a.autoPlay(new C()); // void autoPlay(I i)È£Ãâ + } +} diff --git a/source/ch7/InterfaceTest3.java b/source/ch7/InterfaceTest3.java new file mode 100644 index 0000000..0e14faf --- /dev/null +++ b/source/ch7/InterfaceTest3.java @@ -0,0 +1,32 @@ +class InterfaceTest3 { + public static void main(String[] args) { + A a = new A(); + a.methodA(); + } +} + + class A { + void methodA() { + I i = InstanceManager.getInstance(); + i.methodB(); + System.out.println(i.toString()); // i·Î ObjectŬ·¡½ºÀÇ ¸Þ¼­µå È£Ãâ°¡´É + } + } + + interface I { + public abstract void methodB(); + } + + class B implements I { + public void methodB() { + System.out.println("methodB in B class"); + } + + public String toString() { return "class B";} + } + + class InstanceManager { + public static I getInstance() { + return new B(); + } + } diff --git a/source/ch7/PackageTest.java b/source/ch7/PackageTest.java new file mode 100644 index 0000000..14a679a --- /dev/null +++ b/source/ch7/PackageTest.java @@ -0,0 +1,7 @@ +package com.javachobo.book; + +class PackageTest { + public static void main(String[] args) { + System.out.println("Hello World!"); + } +} diff --git a/source/ch7/ParserTest.java b/source/ch7/ParserTest.java new file mode 100644 index 0000000..8e9aaa5 --- /dev/null +++ b/source/ch7/ParserTest.java @@ -0,0 +1,40 @@ +interface Parseable { + // ±¸¹® ºÐ¼®ÀÛ¾÷À» ¼öÇàÇÑ´Ù. + public abstract void parse(String fileName); +} + +class ParserManager { + // ¸®ÅÏŸÀÔÀÌ ParseableÀÎÅÍÆäÀ̽ºÀÌ´Ù. + public static Parseable getParser(String type) { + if(type.equals("XML")) { + return new XMLParser(); + } else { + Parseable p = new HTMLParser(); + return p; + // return new HTMLParser(); + } + } +} + +class XMLParser implements Parseable { + public void parse(String fileName) { + /* ±¸¹® ºÐ¼®ÀÛ¾÷À» ¼öÇàÇÏ´Â Äڵ带 Àû´Â´Ù. */ + System.out.println(fileName + "- XML parsing completed."); + } +} + +class HTMLParser implements Parseable { + public void parse(String fileName) { + /* ±¸¹® ºÐ¼®ÀÛ¾÷À» ¼öÇàÇÏ´Â Äڵ带 Àû´Â´Ù. */ + System.out.println(fileName + "-HTML parsing completed."); + } +} + +class ParserTest { + public static void main(String args[]) { + Parseable parser = ParserManager.getParser("XML"); + parser.parse("document.xml"); + parser = ParserManager.getParser("HTML"); + parser.parse("document2.html"); + } +} diff --git a/source/ch7/PointTest.java b/source/ch7/PointTest.java new file mode 100644 index 0000000..053f995 --- /dev/null +++ b/source/ch7/PointTest.java @@ -0,0 +1,34 @@ +class PointTest { + public static void main(String args[]) { + Point3D p3 = new Point3D(1,2,3); + } +} + +class Point { + int x; + int y; + + Point(int x, int y) { + this.x = x; + this.y = y; + } + + String getLocation() { + return "x :" + x + ", y :"+ y; + } +} + +class Point3D extends Point { + int z; + + Point3D(int x, int y, int z) { + + this.x = x; + this.y = y; + this.z = z; + } + + String getLocation() { // ¿À¹ö¶óÀ̵ù + return "x :" + x + ", y :"+ y + ", z :" + z; + } +} diff --git a/source/ch7/PointTest2.java b/source/ch7/PointTest2.java new file mode 100644 index 0000000..b7c4599 --- /dev/null +++ b/source/ch7/PointTest2.java @@ -0,0 +1,32 @@ +class PointTest2 { + public static void main(String argsp[]) { + Point3D p3 = new Point3D(); + System.out.println("p3.x=" + p3.x); + System.out.println("p3.y=" + p3.y); + System.out.println("p3.z=" + p3.z); + } +} + +class Point { + int x=10; + int y=20; + + Point(int x, int y) { + + this.x = x; + this.y = y; + } +} + +class Point3D extends Point { + int z=30; + + Point3D() { + this(100, 200, 300); // Point3D(int x, int y, int z)¸¦ È£ÃâÇÑ´Ù. + } + + Point3D(int x, int y, int z) { + super(x, y); // Point(int x, int y)¸¦ È£ÃâÇÑ´Ù. + this.z = z; + } +} diff --git a/source/ch7/PolyArgumentTest.java b/source/ch7/PolyArgumentTest.java new file mode 100644 index 0000000..3a35ad1 --- /dev/null +++ b/source/ch7/PolyArgumentTest.java @@ -0,0 +1,58 @@ +class Product { + int price; // Á¦Ç°ÀÇ °¡°Ý + int bonusPoint; // Á¦Ç°±¸¸Å ½Ã Á¦°øÇÏ´Â º¸³Ê½ºÁ¡¼ö + + Product(int price) { + this.price = price; + bonusPoint =(int)(price/10.0); // º¸³Ê½ºÁ¡¼ö´Â Á¦Ç°°¡°ÝÀÇ 10% + } +} + +class Tv extends Product { + Tv() { + // Á¶»óŬ·¡½ºÀÇ »ý¼ºÀÚ Product(int price)¸¦ È£ÃâÇÑ´Ù. + super(100); // TvÀÇ °¡°ÝÀ» 100¸¸¿øÀ¸·Î ÇÑ´Ù. + } + + public String toString() { // ObjectŬ·¡½ºÀÇ toString()À» ¿À¹ö¶óÀ̵ùÇÑ´Ù. + return "Tv"; + } +} + +class Computer extends Product { + Computer() { + super(200); + } + + public String toString() { + return "Computer"; + } +} + +class Buyer { // °í°´, ¹°°ÇÀ» »ç´Â »ç¶÷ + int money = 1000; // ¼ÒÀ¯±Ý¾× + int bonusPoint = 0; // º¸³Ê½ºÁ¡¼ö + + void buy(Product p) { + if(money < p.price) { + System.out.println("Àܾ×ÀÌ ºÎÁ·ÇÏ¿© ¹°°ÇÀ» »ì¼ö ¾ø½À´Ï´Ù."); + return; + } + + money -= p.price; // °¡Áø µ·¿¡¼­ ±¸ÀÔÇÑ Á¦Ç°ÀÇ °¡°ÝÀ» »«´Ù. + bonusPoint += p.bonusPoint; // Á¦Ç°ÀÇ º¸³Ê½º Á¡¼ö¸¦ Ãß°¡ÇÑ´Ù. + System.out.println(p + "À»/¸¦ ±¸ÀÔÇϼ̽À´Ï´Ù."); + } +} + +class PolyArgumentTest { + public static void main(String args[]) { + Buyer b = new Buyer(); + + b.buy(new Tv()); + b.buy(new Computer()); + + System.out.println("ÇöÀç ³²Àº µ·Àº " + b.money + "¸¸¿øÀÔ´Ï´Ù."); + System.out.println("ÇöÀç º¸³Ê½ºÁ¡¼ö´Â " + b.bonusPoint + "Á¡ÀÔ´Ï´Ù."); + } +} diff --git a/source/ch7/PolyArgumentTest2.java b/source/ch7/PolyArgumentTest2.java new file mode 100644 index 0000000..69b96b0 --- /dev/null +++ b/source/ch7/PolyArgumentTest2.java @@ -0,0 +1,75 @@ +class Product { + int price; // Á¦Ç°ÀÇ °¡°Ý + int bonusPoint; // Á¦Ç°±¸¸Å ½Ã Á¦°øÇÏ´Â º¸³Ê½ºÁ¡¼ö + + Product(int price) { + this.price = price; + bonusPoint =(int)(price/10.0); + } + + Product() {} // ±âº» »ý¼ºÀÚ +} + +class Tv extends Product { + Tv() { + super(100); + } + + public String toString() { return "Tv"; } +} + +class Computer extends Product { + Computer() { super(200); } + + public String toString() { return "Computer"; } +} + +class Audio extends Product { + Audio() { super(50); } + + public String toString() { return "Audio"; } +} + +class Buyer { // °í°´, ¹°°ÇÀ» »ç´Â »ç¶÷ + int money = 1000; // ¼ÒÀ¯±Ý¾× + int bonusPoint = 0; // º¸³Ê½ºÁ¡¼ö + Product[] item = new Product[10]; // ±¸ÀÔÇÑ Á¦Ç°À» ÀúÀåÇϱâ À§ÇÑ ¹è¿­ + int i =0; // Product¹è¿­¿¡ »ç¿ëµÉ Ä«¿îÅÍ + + void buy(Product p) { + if(money < p.price) { + System.out.println("Àܾ×ÀÌ ºÎÁ·ÇÏ¿© ¹°°ÇÀ» »ì¼ö ¾ø½À´Ï´Ù."); + return; + } + + money -= p.price; // °¡Áø µ·¿¡¼­ ±¸ÀÔÇÑ Á¦Ç°ÀÇ °¡°ÝÀ» »«´Ù. + bonusPoint += p.bonusPoint; // Á¦Ç°ÀÇ º¸³Ê½º Á¡¼ö¸¦ Ãß°¡ÇÑ´Ù. + item[i++] = p; // Á¦Ç°À» Product[] item¿¡ ÀúÀåÇÑ´Ù. + System.out.println(p + "À»/¸¦ ±¸ÀÔÇϼ̽À´Ï´Ù."); + } + + void summary() { // ±¸¸ÅÇÑ ¹°Ç°¿¡ ´ëÇÑ Á¤º¸¸¦ ¿ä¾àÇؼ­ º¸¿© ÁØ´Ù. + int sum = 0; // ±¸ÀÔÇÑ ¹°Ç°ÀÇ °¡°ÝÇÕ°è + String itemList =""; // ±¸ÀÔÇÑ ¹°Ç°¸ñ·Ï + + // ¹Ýº¹¹®À» ÀÌ¿ëÇؼ­ ±¸ÀÔÇÑ ¹°Ç°ÀÇ ÃÑ °¡°Ý°ú ¸ñ·ÏÀ» ¸¸µç´Ù. + for(int i=0; i "+ m.group(1) +", "+ m.group(2)+", "+ m.group(3)); + } + } // mainÀÇ ³¡ +} diff --git a/source/ch9/RegularEx4.java b/source/ch9/RegularEx4.java new file mode 100644 index 0000000..ffd1d3b --- /dev/null +++ b/source/ch9/RegularEx4.java @@ -0,0 +1,27 @@ +import java.util.regex.*; // Pattern°ú Matcher°¡ ¼ÓÇÑ ÆÐÅ°Áö + +class RegularEx4 { + public static void main(String[] args) { + String source = "A broken hand works, but not a broken heart."; + String pattern = "broken"; + + StringBuffer sb = new StringBuffer(); + + Pattern p = Pattern.compile(pattern); + Matcher m = p.matcher(source); + System.out.println("source:"+source); + + int i=0; + + while(m.find()) { + System.out.println(++i + "¹ø° ¸ÅĪ:" + m.start() + "~"+ m.end()); + + // brokenÀ» drunkenÀ¸·Î ġȯÇÏ¿© sb¿¡ ÀúÀåÇÑ´Ù. + m.appendReplacement(sb, "drunken"); + } + + m.appendTail(sb); + System.out.println("Replacement count : " + i); + System.out.println("result:"+sb.toString()); + } +} diff --git a/source/ch9/ScannerEx1.java b/source/ch9/ScannerEx1.java new file mode 100644 index 0000000..2d504de --- /dev/null +++ b/source/ch9/ScannerEx1.java @@ -0,0 +1,34 @@ +import java.util.*; + +class ScannerEx1 { + public static void main(String[] args) { + Scanner s = new Scanner(System.in); + String[] argArr = null; + + while(true) { + String prompt = ">>"; + System.out.print(prompt); + + // È­¸éÀ¸·ÎºÎÅÍ ¶óÀδÜÀ§·Î ÀԷ¹޴´Ù. + String input = s.nextLine(); + + input = input.trim(); // ÀԷ¹ÞÀº °ª¿¡¼­ ºÒÇÊ¿äÇÑ ¾ÕµÚ °ø¹éÀ» Á¦°ÅÇÑ´Ù. + argArr = input.split(" +"); // ÀԷ¹ÞÀº ³»¿ëÀ» °ø¹éÀ» ±¸ºÐÀÚ·Î ÀÚ¸¥´Ù. + + String command = argArr[0].trim(); + + if("".equals(command)) continue; + + // ¸í·É¾î¸¦ ¼Ò¹®ÀÚ·Î ¹Ù²Û´Ù. + command = command.toLowerCase(); + + // q ¶Ç´Â Q¸¦ ÀÔ·ÂÇÏ¸é ½ÇÇàÁ¾·áÇÑ´Ù. + if(command.equals("q")) { + System.exit(0); + } else { + for(int i=0; i < argArr.length;i++) + System.out.println(argArr[i]); + } + } // while(true) + } // main +} diff --git a/source/ch9/ScannerEx2.java b/source/ch9/ScannerEx2.java new file mode 100644 index 0000000..bb1e373 --- /dev/null +++ b/source/ch9/ScannerEx2.java @@ -0,0 +1,18 @@ +import java.util.Scanner; +import java.io.File; + +class ScannerEx2 { + public static void main(String[] args) throws Exception { + Scanner sc = new Scanner(new File("data2.txt")); + int sum = 0; + int cnt = 0; + + while (sc.hasNextInt()) { + sum += sc.nextInt(); + cnt++; + } + + System.out.println("sum="+sum); + System.out.println("average="+ (double)sum/cnt); + } +} diff --git a/source/ch9/ScannerEx3.java b/source/ch9/ScannerEx3.java new file mode 100644 index 0000000..a928ca6 --- /dev/null +++ b/source/ch9/ScannerEx3.java @@ -0,0 +1,24 @@ +import java.util.Scanner; +import java.io.File; + +class ScannerEx3 { + public static void main(String[] args) throws Exception { + Scanner sc = new Scanner(new File("data3.txt")); + int cnt = 0; + int totalSum = 0; + + while (sc.hasNextLine()) { + String line = sc.nextLine(); + Scanner sc2 = new Scanner(line).useDelimiter(","); + int sum = 0; + + while(sc2.hasNextInt()) { + sum += sc2.nextInt(); + } + System.out.println(line + ", sum = "+ sum); + totalSum += sum; + cnt++; + } + System.out.println("Line: " + cnt + ", Total: " + totalSum); + } +} diff --git a/source/ch9/ShallowCopy.java b/source/ch9/ShallowCopy.java new file mode 100644 index 0000000..38ef04c --- /dev/null +++ b/source/ch9/ShallowCopy.java @@ -0,0 +1,70 @@ +import java.util.*; + +class Circle implements Cloneable { + Point p; // ¿øÁ¡ + double r; // ¹ÝÁö¸§ + + Circle(Point p, double r) { + this.p = p; + this.r = r; + } + + public Circle shallowCopy() { // ¾èÀº º¹»ç + Object obj = null; + + try { + obj = super.clone(); + } catch (CloneNotSupportedException e) {} + + return (Circle)obj; + } + + public Circle deepCopy() { // ±íÀº º¹»ç + Object obj = null; + + try { + obj = super.clone(); + } catch (CloneNotSupportedException e) {} + + Circle c = (Circle)obj; + c.p = new Point(this.p.x, this.p.y); + + return c; + } + + public String toString() { + return "[p=" + p + ", r="+ r +"]"; + } +} + +class Point { + int x; + int y; + + Point(int x, int y) { + this.x = x; + this.y = y; + } + + public String toString() { + return "("+x +", "+y+")"; + } +} + +class ShallowCopy { + public static void main(String[] args) { + Circle c1 = new Circle(new Point(1, 1), 2.0); + Circle c2 = c1.shallowCopy(); + Circle c3 = c1.deepCopy(); + + System.out.println("c1="+c1); + System.out.println("c2="+c2); + System.out.println("c3="+c3); + c1.p.x = 9; + c1.p.y = 9; + System.out.println("= c1ÀÇ º¯°æ ÈÄ ="); + System.out.println("c1="+c1); + System.out.println("c2="+c2); + System.out.println("c3="+c3); + } +} diff --git a/source/ch9/StringBufferEx1.java b/source/ch9/StringBufferEx1.java new file mode 100644 index 0000000..7c97c2d --- /dev/null +++ b/source/ch9/StringBufferEx1.java @@ -0,0 +1,15 @@ +class StringBufferEx1 { + public static void main(String[] args) { + StringBuffer sb = new StringBuffer("abc"); + StringBuffer sb2 = new StringBuffer("abc"); + + System.out.println("sb == sb2 ? " + (sb == sb2)); + System.out.println("sb.equals(sb2) ? " + sb.equals(sb2)); + + // StringBufferÀÇ ³»¿ëÀ» StringÀ¸·Î º¯È¯ÇÑ´Ù. + String s = sb.toString(); // String s = new String(sb);¿Í °°´Ù. + String s2 = sb2.toString(); + + System.out.println("s.equals(s2) ? " + s.equals(s2)); + } +} diff --git a/source/ch9/StringBufferEx2.java b/source/ch9/StringBufferEx2.java new file mode 100644 index 0000000..f3c321f --- /dev/null +++ b/source/ch9/StringBufferEx2.java @@ -0,0 +1,22 @@ +class StringBufferEx2 { + public static void main(String[] args) { + StringBuffer sb = new StringBuffer("01"); + StringBuffer sb2 = sb.append(23); + sb.append('4').append(56); + + StringBuffer sb3 = sb.append(78); + sb3.append(9.0); + + System.out.println("sb ="+sb); + System.out.println("sb2="+sb2); + System.out.println("sb3="+sb3); + + System.out.println("sb ="+sb.deleteCharAt(10)); + System.out.println("sb ="+sb.delete(3,6)); + System.out.println("sb ="+sb.insert(3,"abc")); + System.out.println("sb ="+sb.replace(6, sb.length(), "END")); + + System.out.println("capacity="+sb.capacity()); + System.out.println("length="+sb.length()); + } +} diff --git a/source/ch9/StringEx1.java b/source/ch9/StringEx1.java new file mode 100644 index 0000000..bc691eb --- /dev/null +++ b/source/ch9/StringEx1.java @@ -0,0 +1,22 @@ +class StringEx1 { + public static void main(String[] args) { + String str1 = "abc"; + String str2 = "abc"; + + System.out.println("String str1 = \"abc\";"); + System.out.println("String str2 = \"abc\";"); + + System.out.println("str1 == str2 ? " + (str1 == str2)); + System.out.println("str1.equals(str2) ? " + str1.equals(str2)); + System.out.println(); + + String str3 = new String("\"abc\""); + String str4 = new String("\"abc\""); + + System.out.println("String str3 = new String(\"abc\");"); + System.out.println("String str4 = new String(\"abc\");"); + + System.out.println("str3 == str4 ? " + (str3 == str4)); + System.out.println("str3.equals(str4) ? " + str3.equals(str4)); + } +} diff --git a/source/ch9/StringEx2.java b/source/ch9/StringEx2.java new file mode 100644 index 0000000..d9070f6 --- /dev/null +++ b/source/ch9/StringEx2.java @@ -0,0 +1,8 @@ +class StringEx2 { + public static void main(String args[]) { + String s1 = "AAA"; + String s2 = "AAA"; + String s3 = "AAA"; + String s4 = "BBB"; + } +} diff --git a/source/ch9/StringEx3.java b/source/ch9/StringEx3.java new file mode 100644 index 0000000..a4a4bb3 --- /dev/null +++ b/source/ch9/StringEx3.java @@ -0,0 +1,10 @@ +class StringEx3 { + public static void main(String[] args) { + // ±æÀÌ°¡ 0ÀÎ char¹è¿­À» »ý¼ºÇÑ´Ù. + char[] cArr = new char[0]; // char[] cArr = {};¿Í °°´Ù. + String s = new String(cArr); // String s = new String("");¿Í °°´Ù. + + System.out.println("cArr.length="+cArr.length); + System.out.println("@@@"+s+"@@@"); + } +} diff --git a/source/ch9/StringEx4.java b/source/ch9/StringEx4.java new file mode 100644 index 0000000..7e3e865 --- /dev/null +++ b/source/ch9/StringEx4.java @@ -0,0 +1,16 @@ +import java.util.StringJoiner; + +class StringEx4 { + public static void main(String[] args) { + String animals = "dog,cat,bear"; + String[] arr = animals.split(","); + + System.out.println(String.join("-", arr)); + + StringJoiner sj = new StringJoiner("/","[","]"); + for(String s : arr) + sj.add(s); + + System.out.println(sj.toString()); + } +} diff --git a/source/ch9/StringEx5.java b/source/ch9/StringEx5.java new file mode 100644 index 0000000..491651c --- /dev/null +++ b/source/ch9/StringEx5.java @@ -0,0 +1,25 @@ +import java.util.StringJoiner; + +class StringEx5 { + public static void main(String[] args) throws Exception { + String str = "°¡"; + + byte[] bArr = str.getBytes("UTF-8"); + byte[] bArr2 = str.getBytes("CP949"); + + System.out.println("UTF-8:" + joinByteArr(bArr)); + System.out.println("CP949:" + joinByteArr(bArr2)); + + System.out.println("UTF-8:" + new String(bArr, "UTF-8")); + System.out.println("CP949:" + new String(bArr2, "CP949")); + } + + static String joinByteArr(byte[] bArr) { + StringJoiner sj = new StringJoiner(":", "[", "]"); + + for(byte b : bArr) + sj.add(String.format("%02X",b)); + + return sj.toString(); + } +} diff --git a/source/ch9/StringEx6.java b/source/ch9/StringEx6.java new file mode 100644 index 0000000..885351f --- /dev/null +++ b/source/ch9/StringEx6.java @@ -0,0 +1,15 @@ +class StringEx6 { + public static void main(String[] args) { + int iVal = 100; + String strVal = String.valueOf(iVal); // int¸¦ StringÀ¸·Î º¯È¯ÇÑ´Ù. + + double dVal = 200.0; + String strVal2 = dVal + ""; // int¸¦ StringÀ¸·Î º¯È¯ÇÏ´Â ¶Ç ´Ù¸¥ ¹æ¹ý + + double sum = Integer.parseInt("+"+strVal)+Double.parseDouble(strVal2); + double sum2 = Integer.valueOf(strVal) + Double.valueOf(strVal2); + + System.out.println(String.join("",strVal,"+",strVal2,"=")+sum); + System.out.println(strVal+"+"+strVal2+"="+sum2); + } +} diff --git a/source/ch9/StringEx7.java b/source/ch9/StringEx7.java new file mode 100644 index 0000000..6a91255 --- /dev/null +++ b/source/ch9/StringEx7.java @@ -0,0 +1,18 @@ +class StringEx7 { + public static void main(String[] args) { + String fullName = "Hello.java"; + + // fullName¿¡¼­ '.'ÀÇ À§Ä¡¸¦ ã´Â´Ù. + int index = fullName.indexOf('.'); + + // fullNameÀÇ Ã¹¹ø° ±ÛÀÚºÎÅÍ '.'ÀÌ ÀÖ´Â °÷±îÁö ¹®ÀÚ¿­À» ÃßÃâÇÑ´Ù. + String fileName = fullName.substring(0, index); + + // '.'ÀÇ ´ÙÀ½ ¹®ÀÚ ºÎÅÍ ½ÃÀÛÇؼ­ ¹®ÀÚ¿­ÀÇ ³¡±îÁö ÃßÃâÇÑ´Ù. + // fullName.substring(index+1, fullName.length());ÀÇ °á°ú¿Í °°´Ù. + String ext = fullName.substring(index+1); + + System.out.println(fullName + "ÀÇ È®ÀåÀÚ¸¦ Á¦¿ÜÇÑ À̸§Àº " + fileName); + System.out.println(fullName + "ÀÇ È®ÀåÀÚ´Â " + ext); + } +} diff --git a/source/ch9/StringTokenizerEx1.java b/source/ch9/StringTokenizerEx1.java new file mode 100644 index 0000000..5d0392b --- /dev/null +++ b/source/ch9/StringTokenizerEx1.java @@ -0,0 +1,12 @@ +import java.util.*; + +class StringTokenizerEx1 { + public static void main(String[] args){ + String source = "100,200,300,400"; + StringTokenizer st = new StringTokenizer(source, ","); + + while(st.hasMoreTokens()){ + System.out.println(st.nextToken()); + } + } // mainÀÇ ³¡ +} diff --git a/source/ch9/StringTokenizerEx2.java b/source/ch9/StringTokenizerEx2.java new file mode 100644 index 0000000..66ecd15 --- /dev/null +++ b/source/ch9/StringTokenizerEx2.java @@ -0,0 +1,12 @@ +import java.util.*; + +class StringTokenizerEx2 { + public static void main(String[] args) { + String expression = "x=100*(200+300)/2"; + StringTokenizer st = new StringTokenizer(expression, "+-*/=()", true); + + while(st.hasMoreTokens()){ + System.out.println(st.nextToken()); + } + } // mainÀÇ ³¡ +} diff --git a/source/ch9/StringTokenizerEx3.java b/source/ch9/StringTokenizerEx3.java new file mode 100644 index 0000000..56b30e7 --- /dev/null +++ b/source/ch9/StringTokenizerEx3.java @@ -0,0 +1,18 @@ +import java.util.*; + +class StringTokenizerEx3 { + public static void main(String args[]) { + String source = "1,±èõÀç,100,100,100|2,¹Ú¼öÀç,95,80,90|3,ÀÌÀÚ¹Ù,80,90,90"; + StringTokenizer st = new StringTokenizer(source, "|"); + + while(st.hasMoreTokens()) { + String token = st.nextToken(); + + StringTokenizer st2 = new StringTokenizer(token, ","); + while(st2.hasMoreTokens()) { + System.out.println(st2.nextToken()); + } + System.out.println("------"); + } + } // mainÀÇ ³¡ +} diff --git a/source/ch9/StringTokenizerEx4.java b/source/ch9/StringTokenizerEx4.java new file mode 100644 index 0000000..8ed77f4 --- /dev/null +++ b/source/ch9/StringTokenizerEx4.java @@ -0,0 +1,44 @@ +import java.util.*; + +class StringTokenizerEx4 { + public static void main(String args[]) { + String input = "»ï½Ê¸¸»ïõ¹é½Ê¿À"; + + System.out.println(input); + System.out.println(hangulToNum(input)); + } + + // ÇѱÛÀ» ¼ýÀÚ·Î ¹Ù²Ù´Â ¸Þ¼­µå + public static long hangulToNum(String input) { + long result = 0; // ÃÖÁ¾ º¯È¯°á°ú¸¦ ÀúÀåÇϱâ À§ÇÑ º¯¼ö + long tmpResult = 0; // ½Ê¹éõ ´ÜÀ§ÀÇ °ªÀ» ÀúÀåÇϱâ À§ÇÑ Àӽú¯¼ö + long num = 0; + + final String NUMBER = "¿µÀÏÀÌ»ï»ç¿ÀÀ°Ä¥Æȱ¸"; + final String UNIT = "½Ê¹éõ¸¸¾ïÁ¶"; + final long[] UNIT_NUM = {10,100,1000,10000,(long)1e8,(long)1e12}; + + StringTokenizer st = new StringTokenizer(input, UNIT, true); + + while(st.hasMoreTokens()) { + String token = st.nextToken(); + // ¼ýÀÚÀÎÁö, ´ÜÀ§(UNIT)ÀÎÁö È®ÀÎÇÑ´Ù. + int check = NUMBER.indexOf(token); + + if(check==-1) { // ´ÜÀ§ÀÎ °æ¿ì + if("¸¸¾ïÁ¶".indexOf(token)==-1) { + tmpResult += ( num!=0 ? num : 1) * UNIT_NUM[UNIT.indexOf(token)]; + } else { + tmpResult += num; + result += (tmpResult!=0 ? tmpResult : 1) * UNIT_NUM[UNIT.indexOf(token)]; + tmpResult = 0; + } + num = 0; + } else { // ¼ýÀÚÀÎ °æ¿ì + num = check; + } + } // end of while + + return result + tmpResult + num; + } +} diff --git a/source/ch9/StringTokenizerEx5.java b/source/ch9/StringTokenizerEx5.java new file mode 100644 index 0000000..9265ddd --- /dev/null +++ b/source/ch9/StringTokenizerEx5.java @@ -0,0 +1,21 @@ +import java.util.*; + +class StringTokenizerEx5 { + public static void main(String[] args) { + String data = "100,,,200,300"; + + String[] result = data.split(","); + StringTokenizer st = new StringTokenizer(data, ","); + + for(int i=0; i < result.length;i++) + System.out.print(result[i]+"|"); + + System.out.println("°³¼ö:"+result.length); + + int i=0; + for(;st.hasMoreTokens();i++) + System.out.print(st.nextToken()+"|"); + + System.out.println("°³¼ö:"+i); + } // main +} diff --git a/source/ch9/ToStringTest.java b/source/ch9/ToStringTest.java new file mode 100644 index 0000000..4f971c8 --- /dev/null +++ b/source/ch9/ToStringTest.java @@ -0,0 +1,11 @@ +class ToStringTest { + public static void main(String args[]) { + String str = new String("KOREA"); + java.util.Date today = new java.util.Date(); + + System.out.println(str); + System.out.println(str.toString()); + System.out.println(today); + System.out.println(today.toString()); + } +} diff --git a/source/ch9/WrapperEx1.java b/source/ch9/WrapperEx1.java new file mode 100644 index 0000000..36e7961 --- /dev/null +++ b/source/ch9/WrapperEx1.java @@ -0,0 +1,17 @@ +class WrapperEx1 { + public static void main(String[] args) { + Integer i = new Integer(100); + Integer i2 = new Integer(100); + + System.out.println("i==i2 ? "+(i==i2)); + System.out.println("i.equals(i2) ? "+i.equals(i2)); + System.out.println("i.compareTo(i2)="+i.compareTo(i2)); + System.out.println("i.toString()="+i.toString()); + + System.out.println("MAX_VALUE="+Integer.MAX_VALUE); + System.out.println("MIN_VALUE="+Integer.MIN_VALUE); + System.out.println("SIZE=" +Integer.SIZE+" bits"); + System.out.println("BYTES="+Integer.BYTES+" bytes"); + System.out.println("TYPE=" +Integer.TYPE); + } +} diff --git a/source/ch9/WrapperEx2.java b/source/ch9/WrapperEx2.java new file mode 100644 index 0000000..d6bde82 --- /dev/null +++ b/source/ch9/WrapperEx2.java @@ -0,0 +1,32 @@ +class WrapperEx2 { + public static void main(String[] args) { + int i = new Integer("100").intValue(); + int i2 = Integer.parseInt("100"); + Integer i3 = Integer.valueOf("100"); + + int i4 = Integer.parseInt("100",2); + int i5 = Integer.parseInt("100",8); + int i6 = Integer.parseInt("100",16); + int i7 = Integer.parseInt("FF", 16); +// int i8 = Integer.parseInt("FF"); // NumberFormatException¹ß»ý + + Integer i9 = Integer.valueOf("100",2); + Integer i10 = Integer.valueOf("100",8); + Integer i11 = Integer.valueOf("100",16); + Integer i12 = Integer.valueOf("FF",16); +// Integer i13 = Integer.valueOf("FF"); // NumberFormatException¹ß»ý + + System.out.println(i); + System.out.println(i2); + System.out.println(i3); + System.out.println("100(2) -> "+i4); + System.out.println("100(8) -> "+i5); + System.out.println("100(16)-> "+i6); + System.out.println("FF(16) -> "+i7); + + System.out.println("100(2) -> "+i9); + System.out.println("100(8) -> "+i10); + System.out.println("100(16)-> "+i11); + System.out.println("FF(16) -> "+i12); + } +} diff --git a/source/ch9/WrapperEx3.java b/source/ch9/WrapperEx3.java new file mode 100644 index 0000000..be3aec2 --- /dev/null +++ b/source/ch9/WrapperEx3.java @@ -0,0 +1,29 @@ +class WrapperEx3 { + public static void main(String[] args) { + int i = 10; + + // ±âº»ÇüÀ» ÂüÁ¶ÇüÀ¸·Î Çüº¯È¯(Çüº¯È¯ »ý·«°¡´É) + Integer intg = (Integer)i; // Integer intg = Integer.valueOf(i); + Object obj = (Object)i; // Object obj = (Object)Integer.valueOf(i); + + Long lng = 100L; // Long lng = new Long(100L); + + int i2 = intg + 10; // ÂüÁ¶Çü°ú ±âº»Çü°£ÀÇ ¿¬»ê °¡´É + long l = intg + lng; // ÂüÁ¶Çü °£ÀÇ µ¡¼Àµµ °¡´É + + Integer intg2 = new Integer(20); + int i3 = (int)intg2; // ÂüÁ¶ÇüÀ» ±âº»ÇüÀ¸·Î Çüº¯È¯µµ °¡´É(Çüº¯È¯ »ý·«°¡´É) + + Integer intg3 = intg2 + i3; + + System.out.println("i ="+i); + System.out.println("intg ="+intg); + System.out.println("obj ="+obj); + System.out.println("lng ="+lng); + System.out.println("intg + 10 ="+i2); + System.out.println("intg + lng ="+l); + System.out.println("intg2 ="+intg2); + System.out.println("i3 ="+i3); + System.out.println("intg2 + i3 ="+intg3); + } +} diff --git a/workspace/.metadata/.lock b/workspace/.metadata/.lock new file mode 100644 index 0000000..e69de29 diff --git a/workspace/.metadata/.log b/workspace/.metadata/.log new file mode 100644 index 0000000..fca05bb --- /dev/null +++ b/workspace/.metadata/.log @@ -0,0 +1,1293 @@ +!SESSION 2016-02-09 22:39:09.641 ----------------------------------------------- +eclipse.buildId=4.5.1.M20150904-0015 +java.version=1.8.0_65 +java.vendor=Oracle Corporation +BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=ko_KR +Framework arguments: -product org.eclipse.epp.package.java.product +Command-line arguments: -os win32 -ws win32 -arch x86 -product org.eclipse.epp.package.java.product + +!ENTRY org.eclipse.egit.ui 2 0 2016-02-09 22:57:45.197 +!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git +user global configuration and to define the default location to store repositories: 'C:\Users\castello'. If this is +not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and +EGit might behave differently since they see different configuration options. +This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. +!SESSION 2016-02-18 20:09:16.573 ----------------------------------------------- +eclipse.buildId=4.5.1.M20150904-0015 +java.version=1.8.0_65 +java.vendor=Oracle Corporation +BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=ko_KR +Framework arguments: -product org.eclipse.epp.package.java.product +Command-line arguments: -os win32 -ws win32 -arch x86 -product org.eclipse.epp.package.java.product + +!ENTRY org.eclipse.egit.ui 2 0 2016-02-18 20:09:41.532 +!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git +user global configuration and to define the default location to store repositories: 'C:\Users\castello'. If this is +not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and +EGit might behave differently since they see different configuration options. +This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. + +!ENTRY org.eclipse.jdt.ui 4 10001 2016-02-18 20:59:48.971 +!MESSAGE Internal Error +!STACK 1 +org.eclipse.core.internal.resources.ResourceException: Resource '/ch5/src/FlowEx25.java' does not exist. + at org.eclipse.core.internal.resources.Resource.checkExists(Resource.java:334) + at org.eclipse.core.internal.resources.Resource.checkAccessible(Resource.java:208) + at org.eclipse.core.internal.resources.Resource.findMaxProblemSeverity(Resource.java:1017) + at org.eclipse.jdt.ui.ProblemsLabelDecorator.getPackageErrorTicksFromMarkers(ProblemsLabelDecorator.java:337) + at org.eclipse.jdt.ui.ProblemsLabelDecorator.computeAdornmentFlags(ProblemsLabelDecorator.java:212) + at org.eclipse.jdt.internal.ui.viewsupport.TreeHierarchyLayoutProblemsDecorator.computePackageAdornmentFlags(TreeHierarchyLayoutProblemsDecorator.java:47) + at org.eclipse.jdt.internal.ui.viewsupport.TreeHierarchyLayoutProblemsDecorator.computeAdornmentFlags(TreeHierarchyLayoutProblemsDecorator.java:56) + at org.eclipse.jdt.internal.ui.packageview.PackageExplorerProblemsDecorator.computeAdornmentFlags(PackageExplorerProblemsDecorator.java:35) + at org.eclipse.jdt.ui.ProblemsLabelDecorator.decorateImage(ProblemsLabelDecorator.java:170) + at org.eclipse.jdt.internal.ui.viewsupport.JavaUILabelProvider.decorateImage(JavaUILabelProvider.java:134) + at org.eclipse.jdt.internal.ui.viewsupport.JavaUILabelProvider.getImage(JavaUILabelProvider.java:149) + at org.eclipse.jdt.internal.ui.packageview.PackageExplorerLabelProvider.getImage(PackageExplorerLabelProvider.java:140) + at org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider.getImage(DelegatingStyledCellLabelProvider.java:195) + at org.eclipse.jface.viewers.DecoratingStyledCellLabelProvider.getImage(DecoratingStyledCellLabelProvider.java:173) + at org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider.update(DelegatingStyledCellLabelProvider.java:121) + at org.eclipse.jface.viewers.DecoratingStyledCellLabelProvider.update(DecoratingStyledCellLabelProvider.java:136) + at org.eclipse.jface.viewers.ViewerColumn.refresh(ViewerColumn.java:154) + at org.eclipse.jface.viewers.AbstractTreeViewer.doUpdateItem(AbstractTreeViewer.java:949) + at org.eclipse.jface.viewers.AbstractTreeViewer$UpdateItemSafeRunnable.run(AbstractTreeViewer.java:114) + at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) + at org.eclipse.ui.internal.JFaceUtil$1.run(JFaceUtil.java:50) + at org.eclipse.jface.util.SafeRunnable.run(SafeRunnable.java:173) + at org.eclipse.jface.viewers.AbstractTreeViewer.doUpdateItem(AbstractTreeViewer.java:1029) + at org.eclipse.jface.viewers.StructuredViewer$UpdateItemSafeRunnable.run(StructuredViewer.java:473) + at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) + at org.eclipse.ui.internal.JFaceUtil$1.run(JFaceUtil.java:50) + at org.eclipse.jface.util.SafeRunnable.run(SafeRunnable.java:173) + at org.eclipse.jface.viewers.StructuredViewer.updateItem(StructuredViewer.java:2176) + at org.eclipse.jface.viewers.StructuredViewer.internalUpdate(StructuredViewer.java:2159) + at org.eclipse.jface.viewers.StructuredViewer.update(StructuredViewer.java:2097) + at org.eclipse.jface.viewers.ColumnViewer.update(ColumnViewer.java:541) + at org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider$2.run(PackageExplorerContentProvider.java:837) + at org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider.runUpdates(PackageExplorerContentProvider.java:195) + at org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider.executeRunnables(PackageExplorerContentProvider.java:143) + at org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider.elementChanged(PackageExplorerContentProvider.java:128) + at org.eclipse.jdt.internal.core.DeltaProcessor$3.run(DeltaProcessor.java:1662) + at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) + at org.eclipse.jdt.internal.core.DeltaProcessor.notifyListeners(DeltaProcessor.java:1652) + at org.eclipse.jdt.internal.core.DeltaProcessor.firePostChangeDelta(DeltaProcessor.java:1486) + at org.eclipse.jdt.internal.core.DeltaProcessor.fire(DeltaProcessor.java:1462) + at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:770) + at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:789) + at org.eclipse.jdt.internal.core.CompilationUnit.discardWorkingCopy(CompilationUnit.java:491) + at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitDocumentProvider.disposeFileInfo(CompilationUnitDocumentProvider.java:1227) + at org.eclipse.ui.editors.text.TextFileDocumentProvider.disconnect(TextFileDocumentProvider.java:653) + at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitDocumentProvider.disconnect(CompilationUnitDocumentProvider.java:1303) + at org.eclipse.ui.texteditor.AbstractTextEditor.disposeDocumentProvider(AbstractTextEditor.java:4537) + at org.eclipse.ui.texteditor.AbstractDecoratedTextEditor.disposeDocumentProvider(AbstractDecoratedTextEditor.java:1463) + at org.eclipse.ui.texteditor.AbstractTextEditor.dispose(AbstractTextEditor.java:4419) + at org.eclipse.ui.texteditor.AbstractDecoratedTextEditor.dispose(AbstractDecoratedTextEditor.java:383) + at org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.dispose(JavaEditor.java:2697) + at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor.dispose(CompilationUnitEditor.java:1493) + at org.eclipse.ui.internal.e4.compatibility.CompatibilityPart.invalidate(CompatibilityPart.java:238) + at org.eclipse.ui.internal.e4.compatibility.CompatibilityPart.destroy(CompatibilityPart.java:394) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) + at java.lang.reflect.Method.invoke(Unknown Source) + at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:56) + at org.eclipse.e4.core.internal.di.InjectorImpl.processAnnotated(InjectorImpl.java:898) + at org.eclipse.e4.core.internal.di.InjectorImpl.processAnnotated(InjectorImpl.java:879) + at org.eclipse.e4.core.internal.di.InjectorImpl.uninject(InjectorImpl.java:182) + at org.eclipse.e4.core.internal.di.Requestor.uninject(Requestor.java:164) + at org.eclipse.e4.core.internal.contexts.ContextObjectSupplier$ContextInjectionListener.update(ContextObjectSupplier.java:84) + at org.eclipse.e4.core.internal.contexts.TrackableComputationExt.update(TrackableComputationExt.java:111) + at org.eclipse.e4.core.internal.contexts.EclipseContext.removeListenersTo(EclipseContext.java:473) + at org.eclipse.e4.core.contexts.ContextInjectionFactory.uninject(ContextInjectionFactory.java:144) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.safeRemoveGui(PartRenderingEngine.java:923) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.access$1(PartRenderingEngine.java:842) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$3.run(PartRenderingEngine.java:837) + at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.removeGui(PartRenderingEngine.java:821) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.subscribeTopicToBeRendered(PartRenderingEngine.java:161) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) + at java.lang.reflect.Method.invoke(Unknown Source) + at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:56) + at org.eclipse.e4.core.di.internal.extensions.EventObjectSupplier$DIEventHandler.handleEvent(EventObjectSupplier.java:83) + at org.eclipse.equinox.internal.event.EventHandlerWrapper.handleEvent(EventHandlerWrapper.java:197) + at org.eclipse.equinox.internal.event.EventHandlerTracker.dispatchEvent(EventHandlerTracker.java:197) + at org.eclipse.equinox.internal.event.EventHandlerTracker.dispatchEvent(EventHandlerTracker.java:1) + at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230) + at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:148) + at org.eclipse.equinox.internal.event.EventAdminImpl.dispatchEvent(EventAdminImpl.java:135) + at org.eclipse.equinox.internal.event.EventAdminImpl.sendEvent(EventAdminImpl.java:78) + at org.eclipse.equinox.internal.event.EventComponent.sendEvent(EventComponent.java:39) + at org.eclipse.e4.ui.services.internal.events.EventBroker.send(EventBroker.java:85) + at org.eclipse.e4.ui.internal.workbench.UIEventPublisher.notifyChanged(UIEventPublisher.java:59) + at org.eclipse.emf.common.notify.impl.BasicNotifierImpl.eNotify(BasicNotifierImpl.java:374) + at org.eclipse.e4.ui.model.application.ui.impl.UIElementImpl.setToBeRendered(UIElementImpl.java:303) + at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.hidePart(PartServiceImpl.java:1302) + at org.eclipse.ui.internal.WorkbenchPage.hidePart(WorkbenchPage.java:1582) + at org.eclipse.ui.internal.WorkbenchPage.closeEditors(WorkbenchPage.java:1495) + at org.eclipse.ui.internal.WorkbenchPage.closeEditor(WorkbenchPage.java:1628) + at org.eclipse.ui.texteditor.AbstractTextEditor$23.run(AbstractTextEditor.java:4333) + at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35) + at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:135) + at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4155) + at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3772) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1127) + at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1018) + at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:156) + at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:654) + at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337) + at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:598) + at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:150) + at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:139) + at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) + at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) + at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) + at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:380) + at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:235) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) + at java.lang.reflect.Method.invoke(Unknown Source) + at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:669) + at org.eclipse.equinox.launcher.Main.basicRun(Main.java:608) + at org.eclipse.equinox.launcher.Main.run(Main.java:1515) +!SUBENTRY 1 org.eclipse.core.resources 4 368 2016-02-18 20:59:48.971 +!MESSAGE Resource '/ch5/src/FlowEx25.java' does not exist. +!SESSION 2016-02-18 23:07:46.212 ----------------------------------------------- +eclipse.buildId=4.5.1.M20150904-0015 +java.version=1.8.0_65 +java.vendor=Oracle Corporation +BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=ko_KR +Framework arguments: -product org.eclipse.epp.package.java.product +Command-line arguments: -os win32 -ws win32 -arch x86 -product org.eclipse.epp.package.java.product + +!ENTRY org.eclipse.egit.ui 2 0 2016-02-18 23:08:02.906 +!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git +user global configuration and to define the default location to store repositories: 'C:\Users\castello'. If this is +not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and +EGit might behave differently since they see different configuration options. +This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. +!SESSION 2016-02-19 23:49:16.023 ----------------------------------------------- +eclipse.buildId=4.5.1.M20150904-0015 +java.version=1.8.0_65 +java.vendor=Oracle Corporation +BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=ko_KR +Framework arguments: -product org.eclipse.epp.package.java.product +Command-line arguments: -os win32 -ws win32 -arch x86 -product org.eclipse.epp.package.java.product + +!ENTRY org.eclipse.egit.ui 2 0 2016-02-19 23:49:31.866 +!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git +user global configuration and to define the default location to store repositories: 'C:\Users\castello'. If this is +not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and +EGit might behave differently since they see different configuration options. +This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. +!SESSION 2016-02-23 07:34:55.308 ----------------------------------------------- +eclipse.buildId=4.5.1.M20150904-0015 +java.version=1.8.0_65 +java.vendor=Oracle Corporation +BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=ko_KR +Framework arguments: -product org.eclipse.epp.package.java.product +Command-line arguments: -os win32 -ws win32 -arch x86 -product org.eclipse.epp.package.java.product + +!ENTRY org.eclipse.egit.ui 2 0 2016-02-23 07:35:11.793 +!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git +user global configuration and to define the default location to store repositories: 'C:\Users\castello'. If this is +not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and +EGit might behave differently since they see different configuration options. +This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. +!SESSION 2016-02-23 14:10:03.544 ----------------------------------------------- +eclipse.buildId=4.5.1.M20150904-0015 +java.version=1.8.0_65 +java.vendor=Oracle Corporation +BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=ko_KR +Framework arguments: -product org.eclipse.epp.package.java.product +Command-line arguments: -os win32 -ws win32 -arch x86 -product org.eclipse.epp.package.java.product + +!ENTRY org.eclipse.egit.ui 2 0 2016-02-23 14:10:23.071 +!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git +user global configuration and to define the default location to store repositories: 'C:\Users\castello'. If this is +not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and +EGit might behave differently since they see different configuration options. +This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. +!SESSION 2016-02-25 19:08:52.808 ----------------------------------------------- +eclipse.buildId=4.5.1.M20150904-0015 +java.version=1.8.0_65 +java.vendor=Oracle Corporation +BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=ko_KR +Framework arguments: -product org.eclipse.epp.package.java.product +Command-line arguments: -os win32 -ws win32 -arch x86 -product org.eclipse.epp.package.java.product + +!ENTRY org.eclipse.egit.ui 2 0 2016-02-25 19:09:08.685 +!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git +user global configuration and to define the default location to store repositories: 'C:\Users\castello'. If this is +not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and +EGit might behave differently since they see different configuration options. +This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. + +!ENTRY org.eclipse.e4.ui.workbench 4 0 2016-02-25 19:50:44.742 +!MESSAGE Error setting focus to : org.eclipse.e4.ui.model.application.ui.basic.impl.PartImpl ForkJoinEx1.java +!STACK 0 +org.eclipse.swt.SWTException: Widget is disposed + at org.eclipse.swt.SWT.error(SWT.java:4491) + at org.eclipse.swt.SWT.error(SWT.java:4406) + at org.eclipse.swt.SWT.error(SWT.java:4377) + at org.eclipse.swt.widgets.Widget.error(Widget.java:482) + at org.eclipse.swt.widgets.Widget.checkWidget(Widget.java:354) + at org.eclipse.swt.widgets.Control.setFocus(Control.java:3354) + at org.eclipse.swt.widgets.Composite.setFocus(Composite.java:1056) + at org.eclipse.swt.widgets.Composite.setFocus(Composite.java:1056) + at org.eclipse.ui.texteditor.StatusTextEditor.setFocus(StatusTextEditor.java:120) + at org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.setFocus(JavaEditor.java:2395) + at org.eclipse.ui.internal.e4.compatibility.CompatibilityPart.delegateSetFocus(CompatibilityPart.java:204) + at sun.reflect.GeneratedMethodAccessor46.invoke(Unknown Source) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) + at java.lang.reflect.Method.invoke(Unknown Source) + at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:56) + at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:252) + at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:258) + at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:229) + at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:107) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.focusGui(PartRenderingEngine.java:775) + at org.eclipse.e4.ui.workbench.renderers.swt.ContributedPartRenderer$2.setFocus(ContributedPartRenderer.java:102) + at org.eclipse.swt.custom.CTabItem.setFocus(CTabItem.java:332) + at org.eclipse.swt.custom.CTabFolder.setFocus(CTabFolder.java:2602) + at org.eclipse.swt.widgets.Control.fixFocus(Control.java:1053) + at org.eclipse.swt.widgets.Control.setVisible(Control.java:3859) + at org.eclipse.swt.custom.CTabFolder.setSelection(CTabFolder.java:3146) + at org.eclipse.swt.custom.CTabFolder.setSelection(CTabFolder.java:3103) + at org.eclipse.e4.ui.workbench.renderers.swt.StackRenderer.showTab(StackRenderer.java:1318) + at org.eclipse.e4.ui.workbench.renderers.swt.LazyStackRenderer$1.handleEvent(LazyStackRenderer.java:72) + at org.eclipse.e4.ui.services.internal.events.UIEventHandler$1.run(UIEventHandler.java:40) + at org.eclipse.swt.widgets.Synchronizer.syncExec(Synchronizer.java:186) + at org.eclipse.ui.internal.UISynchronizer.syncExec(UISynchronizer.java:145) + at org.eclipse.swt.widgets.Display.syncExec(Display.java:4761) + at org.eclipse.e4.ui.internal.workbench.swt.E4Application$1.syncExec(E4Application.java:211) + at org.eclipse.e4.ui.services.internal.events.UIEventHandler.handleEvent(UIEventHandler.java:36) + at org.eclipse.equinox.internal.event.EventHandlerWrapper.handleEvent(EventHandlerWrapper.java:197) + at org.eclipse.equinox.internal.event.EventHandlerTracker.dispatchEvent(EventHandlerTracker.java:197) + at org.eclipse.equinox.internal.event.EventHandlerTracker.dispatchEvent(EventHandlerTracker.java:1) + at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230) + at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:148) + at org.eclipse.equinox.internal.event.EventAdminImpl.dispatchEvent(EventAdminImpl.java:135) + at org.eclipse.equinox.internal.event.EventAdminImpl.sendEvent(EventAdminImpl.java:78) + at org.eclipse.equinox.internal.event.EventComponent.sendEvent(EventComponent.java:39) + at org.eclipse.e4.ui.services.internal.events.EventBroker.send(EventBroker.java:85) + at org.eclipse.e4.ui.internal.workbench.UIEventPublisher.notifyChanged(UIEventPublisher.java:59) + at org.eclipse.emf.common.notify.impl.BasicNotifierImpl.eNotify(BasicNotifierImpl.java:374) + at org.eclipse.e4.ui.model.application.ui.impl.ElementContainerImpl.setSelectedElement(ElementContainerImpl.java:171) + at org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.showElementInWindow(ModelServiceImpl.java:494) + at org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.bringToTop(ModelServiceImpl.java:458) + at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.delegateBringToTop(PartServiceImpl.java:724) + at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.showPart(PartServiceImpl.java:1163) + at org.eclipse.ui.internal.WorkbenchPage.busyOpenEditor(WorkbenchPage.java:3234) + at org.eclipse.ui.internal.WorkbenchPage.access$25(WorkbenchPage.java:3149) + at org.eclipse.ui.internal.WorkbenchPage$10.run(WorkbenchPage.java:3131) + at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) + at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:3126) + at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:3090) + at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:3080) + at org.eclipse.ui.internal.NavigationHistoryEntry.restoreLocation(NavigationHistoryEntry.java:66) + at org.eclipse.ui.internal.NavigationHistory.gotoEntry(NavigationHistory.java:452) + at org.eclipse.ui.internal.NavigationHistory.shiftEntry(NavigationHistory.java:517) + at org.eclipse.ui.internal.NavigationHistory.backward(NavigationHistory.java:501) + at org.eclipse.ui.internal.NavigationHistoryAction.run(NavigationHistoryAction.java:242) + at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) + at org.eclipse.jface.commands.ActionHandler.execute(ActionHandler.java:122) + at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:90) + at sun.reflect.GeneratedMethodAccessor56.invoke(Unknown Source) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) + at java.lang.reflect.Method.invoke(Unknown Source) + at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:56) + at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:252) + at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:234) + at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132) + at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:152) + at org.eclipse.core.commands.Command.executeWithChecks(Command.java:493) + at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:486) + at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:210) + at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.executeCommand(KeyBindingDispatcher.java:286) + at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.press(KeyBindingDispatcher.java:507) + at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.processKeyEvent(KeyBindingDispatcher.java:558) + at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.filterKeySequenceBindings(KeyBindingDispatcher.java:378) + at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.access$0(KeyBindingDispatcher.java:324) + at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher$KeyDownFilter.handleEvent(KeyBindingDispatcher.java:86) + at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) + at org.eclipse.swt.widgets.Display.filterEvent(Display.java:1266) + at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1112) + at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1137) + at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1122) + at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1164) + at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1160) + at org.eclipse.swt.widgets.Widget.wmSysKeyDown(Widget.java:2632) + at org.eclipse.swt.widgets.Control.WM_SYSKEYDOWN(Control.java:5468) + at org.eclipse.swt.widgets.Control.windowProc(Control.java:4755) + at org.eclipse.swt.widgets.Canvas.windowProc(Canvas.java:339) + at org.eclipse.swt.widgets.Display.windowProc(Display.java:5063) + at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) + at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:2549) + at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3767) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1127) + at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1018) + at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:156) + at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:654) + at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337) + at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:598) + at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:150) + at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:139) + at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) + at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) + at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) + at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:380) + at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:235) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) + at java.lang.reflect.Method.invoke(Unknown Source) + at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:669) + at org.eclipse.equinox.launcher.Main.basicRun(Main.java:608) + at org.eclipse.equinox.launcher.Main.run(Main.java:1515) + +!ENTRY org.eclipse.e4.ui.workbench 4 0 2016-02-25 19:50:45.056 +!MESSAGE Error setting focus to : org.eclipse.e4.ui.model.application.ui.basic.impl.PartImpl ThreadEx15.java +!STACK 0 +org.eclipse.swt.SWTException: Widget is disposed + at org.eclipse.swt.SWT.error(SWT.java:4491) + at org.eclipse.swt.SWT.error(SWT.java:4406) + at org.eclipse.swt.SWT.error(SWT.java:4377) + at org.eclipse.swt.widgets.Widget.error(Widget.java:482) + at org.eclipse.swt.widgets.Widget.checkWidget(Widget.java:354) + at org.eclipse.swt.widgets.Control.setFocus(Control.java:3354) + at org.eclipse.swt.widgets.Composite.setFocus(Composite.java:1056) + at org.eclipse.swt.widgets.Composite.setFocus(Composite.java:1056) + at org.eclipse.ui.texteditor.StatusTextEditor.setFocus(StatusTextEditor.java:120) + at org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.setFocus(JavaEditor.java:2395) + at org.eclipse.ui.internal.e4.compatibility.CompatibilityPart.delegateSetFocus(CompatibilityPart.java:204) + at sun.reflect.GeneratedMethodAccessor46.invoke(Unknown Source) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) + at java.lang.reflect.Method.invoke(Unknown Source) + at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:56) + at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:252) + at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:258) + at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:229) + at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:107) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.focusGui(PartRenderingEngine.java:775) + at org.eclipse.e4.ui.workbench.renderers.swt.ContributedPartRenderer$2.setFocus(ContributedPartRenderer.java:102) + at org.eclipse.swt.custom.CTabItem.setFocus(CTabItem.java:332) + at org.eclipse.swt.custom.CTabFolder.setFocus(CTabFolder.java:2602) + at org.eclipse.swt.widgets.Control.fixFocus(Control.java:1053) + at org.eclipse.swt.widgets.Control.setVisible(Control.java:3859) + at org.eclipse.swt.custom.CTabFolder.setSelection(CTabFolder.java:3146) + at org.eclipse.swt.custom.CTabFolder.setSelection(CTabFolder.java:3103) + at org.eclipse.e4.ui.workbench.renderers.swt.StackRenderer.showTab(StackRenderer.java:1318) + at org.eclipse.e4.ui.workbench.renderers.swt.LazyStackRenderer$1.handleEvent(LazyStackRenderer.java:72) + at org.eclipse.e4.ui.services.internal.events.UIEventHandler$1.run(UIEventHandler.java:40) + at org.eclipse.swt.widgets.Synchronizer.syncExec(Synchronizer.java:186) + at org.eclipse.ui.internal.UISynchronizer.syncExec(UISynchronizer.java:145) + at org.eclipse.swt.widgets.Display.syncExec(Display.java:4761) + at org.eclipse.e4.ui.internal.workbench.swt.E4Application$1.syncExec(E4Application.java:211) + at org.eclipse.e4.ui.services.internal.events.UIEventHandler.handleEvent(UIEventHandler.java:36) + at org.eclipse.equinox.internal.event.EventHandlerWrapper.handleEvent(EventHandlerWrapper.java:197) + at org.eclipse.equinox.internal.event.EventHandlerTracker.dispatchEvent(EventHandlerTracker.java:197) + at org.eclipse.equinox.internal.event.EventHandlerTracker.dispatchEvent(EventHandlerTracker.java:1) + at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230) + at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:148) + at org.eclipse.equinox.internal.event.EventAdminImpl.dispatchEvent(EventAdminImpl.java:135) + at org.eclipse.equinox.internal.event.EventAdminImpl.sendEvent(EventAdminImpl.java:78) + at org.eclipse.equinox.internal.event.EventComponent.sendEvent(EventComponent.java:39) + at org.eclipse.e4.ui.services.internal.events.EventBroker.send(EventBroker.java:85) + at org.eclipse.e4.ui.internal.workbench.UIEventPublisher.notifyChanged(UIEventPublisher.java:59) + at org.eclipse.emf.common.notify.impl.BasicNotifierImpl.eNotify(BasicNotifierImpl.java:374) + at org.eclipse.e4.ui.model.application.ui.impl.ElementContainerImpl.setSelectedElement(ElementContainerImpl.java:171) + at org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.showElementInWindow(ModelServiceImpl.java:494) + at org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.bringToTop(ModelServiceImpl.java:458) + at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.delegateBringToTop(PartServiceImpl.java:724) + at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.showPart(PartServiceImpl.java:1163) + at org.eclipse.ui.internal.WorkbenchPage.busyOpenEditor(WorkbenchPage.java:3234) + at org.eclipse.ui.internal.WorkbenchPage.access$25(WorkbenchPage.java:3149) + at org.eclipse.ui.internal.WorkbenchPage$10.run(WorkbenchPage.java:3131) + at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) + at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:3126) + at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:3090) + at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:3080) + at org.eclipse.ui.internal.NavigationHistoryEntry.restoreLocation(NavigationHistoryEntry.java:66) + at org.eclipse.ui.internal.NavigationHistory.gotoEntry(NavigationHistory.java:452) + at org.eclipse.ui.internal.NavigationHistory.shiftEntry(NavigationHistory.java:517) + at org.eclipse.ui.internal.NavigationHistory.backward(NavigationHistory.java:501) + at org.eclipse.ui.internal.NavigationHistoryAction.run(NavigationHistoryAction.java:242) + at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) + at org.eclipse.jface.commands.ActionHandler.execute(ActionHandler.java:122) + at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:90) + at sun.reflect.GeneratedMethodAccessor56.invoke(Unknown Source) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) + at java.lang.reflect.Method.invoke(Unknown Source) + at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:56) + at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:252) + at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:234) + at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132) + at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:152) + at org.eclipse.core.commands.Command.executeWithChecks(Command.java:493) + at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:486) + at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:210) + at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.executeCommand(KeyBindingDispatcher.java:286) + at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.press(KeyBindingDispatcher.java:507) + at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.processKeyEvent(KeyBindingDispatcher.java:558) + at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.filterKeySequenceBindings(KeyBindingDispatcher.java:378) + at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.access$0(KeyBindingDispatcher.java:324) + at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher$KeyDownFilter.handleEvent(KeyBindingDispatcher.java:86) + at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) + at org.eclipse.swt.widgets.Display.filterEvent(Display.java:1266) + at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1112) + at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1137) + at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1122) + at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1164) + at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1160) + at org.eclipse.swt.widgets.Widget.wmSysKeyDown(Widget.java:2632) + at org.eclipse.swt.widgets.Control.WM_SYSKEYDOWN(Control.java:5468) + at org.eclipse.swt.widgets.Control.windowProc(Control.java:4755) + at org.eclipse.swt.widgets.Canvas.windowProc(Canvas.java:339) + at org.eclipse.swt.widgets.Display.windowProc(Display.java:5063) + at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) + at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:2549) + at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3767) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1127) + at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1018) + at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:156) + at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:654) + at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337) + at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:598) + at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:150) + at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:139) + at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) + at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) + at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) + at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:380) + at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:235) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) + at java.lang.reflect.Method.invoke(Unknown Source) + at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:669) + at org.eclipse.equinox.launcher.Main.basicRun(Main.java:608) + at org.eclipse.equinox.launcher.Main.run(Main.java:1515) + +!ENTRY org.eclipse.e4.ui.workbench 4 0 2016-02-25 19:50:46.271 +!MESSAGE Error setting focus to : org.eclipse.e4.ui.model.application.ui.basic.impl.PartImpl ThreadEx12.java +!STACK 0 +org.eclipse.swt.SWTException: Widget is disposed + at org.eclipse.swt.SWT.error(SWT.java:4491) + at org.eclipse.swt.SWT.error(SWT.java:4406) + at org.eclipse.swt.SWT.error(SWT.java:4377) + at org.eclipse.swt.widgets.Widget.error(Widget.java:482) + at org.eclipse.swt.widgets.Widget.checkWidget(Widget.java:354) + at org.eclipse.swt.widgets.Control.setFocus(Control.java:3354) + at org.eclipse.swt.widgets.Composite.setFocus(Composite.java:1056) + at org.eclipse.swt.widgets.Composite.setFocus(Composite.java:1056) + at org.eclipse.ui.texteditor.StatusTextEditor.setFocus(StatusTextEditor.java:120) + at org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.setFocus(JavaEditor.java:2395) + at org.eclipse.ui.internal.e4.compatibility.CompatibilityPart.delegateSetFocus(CompatibilityPart.java:204) + at sun.reflect.GeneratedMethodAccessor46.invoke(Unknown Source) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) + at java.lang.reflect.Method.invoke(Unknown Source) + at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:56) + at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:252) + at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:258) + at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:229) + at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:107) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.focusGui(PartRenderingEngine.java:775) + at org.eclipse.e4.ui.workbench.renderers.swt.ContributedPartRenderer$2.setFocus(ContributedPartRenderer.java:102) + at org.eclipse.swt.custom.CTabItem.setFocus(CTabItem.java:332) + at org.eclipse.swt.custom.CTabFolder.setFocus(CTabFolder.java:2602) + at org.eclipse.swt.widgets.Control.fixFocus(Control.java:1053) + at org.eclipse.swt.widgets.Control.setVisible(Control.java:3859) + at org.eclipse.swt.custom.CTabFolder.setSelection(CTabFolder.java:3146) + at org.eclipse.swt.custom.CTabFolder.setSelection(CTabFolder.java:3103) + at org.eclipse.e4.ui.workbench.renderers.swt.StackRenderer.showTab(StackRenderer.java:1318) + at org.eclipse.e4.ui.workbench.renderers.swt.LazyStackRenderer$1.handleEvent(LazyStackRenderer.java:72) + at org.eclipse.e4.ui.services.internal.events.UIEventHandler$1.run(UIEventHandler.java:40) + at org.eclipse.swt.widgets.Synchronizer.syncExec(Synchronizer.java:186) + at org.eclipse.ui.internal.UISynchronizer.syncExec(UISynchronizer.java:145) + at org.eclipse.swt.widgets.Display.syncExec(Display.java:4761) + at org.eclipse.e4.ui.internal.workbench.swt.E4Application$1.syncExec(E4Application.java:211) + at org.eclipse.e4.ui.services.internal.events.UIEventHandler.handleEvent(UIEventHandler.java:36) + at org.eclipse.equinox.internal.event.EventHandlerWrapper.handleEvent(EventHandlerWrapper.java:197) + at org.eclipse.equinox.internal.event.EventHandlerTracker.dispatchEvent(EventHandlerTracker.java:197) + at org.eclipse.equinox.internal.event.EventHandlerTracker.dispatchEvent(EventHandlerTracker.java:1) + at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230) + at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:148) + at org.eclipse.equinox.internal.event.EventAdminImpl.dispatchEvent(EventAdminImpl.java:135) + at org.eclipse.equinox.internal.event.EventAdminImpl.sendEvent(EventAdminImpl.java:78) + at org.eclipse.equinox.internal.event.EventComponent.sendEvent(EventComponent.java:39) + at org.eclipse.e4.ui.services.internal.events.EventBroker.send(EventBroker.java:85) + at org.eclipse.e4.ui.internal.workbench.UIEventPublisher.notifyChanged(UIEventPublisher.java:59) + at org.eclipse.emf.common.notify.impl.BasicNotifierImpl.eNotify(BasicNotifierImpl.java:374) + at org.eclipse.e4.ui.model.application.ui.impl.ElementContainerImpl.setSelectedElement(ElementContainerImpl.java:171) + at org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.showElementInWindow(ModelServiceImpl.java:494) + at org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.bringToTop(ModelServiceImpl.java:458) + at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.delegateBringToTop(PartServiceImpl.java:724) + at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.showPart(PartServiceImpl.java:1163) + at org.eclipse.ui.internal.WorkbenchPage.busyOpenEditor(WorkbenchPage.java:3234) + at org.eclipse.ui.internal.WorkbenchPage.access$25(WorkbenchPage.java:3149) + at org.eclipse.ui.internal.WorkbenchPage$10.run(WorkbenchPage.java:3131) + at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) + at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:3126) + at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:3090) + at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:3080) + at org.eclipse.ui.internal.NavigationHistoryEntry.restoreLocation(NavigationHistoryEntry.java:66) + at org.eclipse.ui.internal.NavigationHistory.gotoEntry(NavigationHistory.java:452) + at org.eclipse.ui.internal.NavigationHistory.shiftEntry(NavigationHistory.java:517) + at org.eclipse.ui.internal.NavigationHistory.backward(NavigationHistory.java:501) + at org.eclipse.ui.internal.NavigationHistoryAction.run(NavigationHistoryAction.java:242) + at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) + at org.eclipse.jface.commands.ActionHandler.execute(ActionHandler.java:122) + at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:90) + at sun.reflect.GeneratedMethodAccessor56.invoke(Unknown Source) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) + at java.lang.reflect.Method.invoke(Unknown Source) + at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:56) + at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:252) + at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:234) + at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132) + at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:152) + at org.eclipse.core.commands.Command.executeWithChecks(Command.java:493) + at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:486) + at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:210) + at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.executeCommand(KeyBindingDispatcher.java:286) + at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.press(KeyBindingDispatcher.java:507) + at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.processKeyEvent(KeyBindingDispatcher.java:558) + at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.filterKeySequenceBindings(KeyBindingDispatcher.java:378) + at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.access$0(KeyBindingDispatcher.java:324) + at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher$KeyDownFilter.handleEvent(KeyBindingDispatcher.java:86) + at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) + at org.eclipse.swt.widgets.Display.filterEvent(Display.java:1266) + at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1112) + at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1137) + at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1122) + at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1164) + at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1160) + at org.eclipse.swt.widgets.Widget.wmSysKeyDown(Widget.java:2632) + at org.eclipse.swt.widgets.Control.WM_SYSKEYDOWN(Control.java:5468) + at org.eclipse.swt.widgets.Control.windowProc(Control.java:4755) + at org.eclipse.swt.widgets.Canvas.windowProc(Canvas.java:339) + at org.eclipse.swt.widgets.Display.windowProc(Display.java:5063) + at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) + at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:2549) + at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3767) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1127) + at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1018) + at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:156) + at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:654) + at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337) + at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:598) + at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:150) + at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:139) + at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) + at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) + at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) + at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:380) + at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:235) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) + at java.lang.reflect.Method.invoke(Unknown Source) + at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:669) + at org.eclipse.equinox.launcher.Main.basicRun(Main.java:608) + at org.eclipse.equinox.launcher.Main.run(Main.java:1515) + +!ENTRY org.eclipse.e4.ui.workbench 4 0 2016-02-25 19:50:46.581 +!MESSAGE Error setting focus to : org.eclipse.e4.ui.model.application.ui.basic.impl.PartImpl ThreadEx11.java +!STACK 0 +org.eclipse.swt.SWTException: Widget is disposed + at org.eclipse.swt.SWT.error(SWT.java:4491) + at org.eclipse.swt.SWT.error(SWT.java:4406) + at org.eclipse.swt.SWT.error(SWT.java:4377) + at org.eclipse.swt.widgets.Widget.error(Widget.java:482) + at org.eclipse.swt.widgets.Widget.checkWidget(Widget.java:354) + at org.eclipse.swt.widgets.Control.setFocus(Control.java:3354) + at org.eclipse.swt.widgets.Composite.setFocus(Composite.java:1056) + at org.eclipse.swt.widgets.Composite.setFocus(Composite.java:1056) + at org.eclipse.ui.texteditor.StatusTextEditor.setFocus(StatusTextEditor.java:120) + at org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.setFocus(JavaEditor.java:2395) + at org.eclipse.ui.internal.e4.compatibility.CompatibilityPart.delegateSetFocus(CompatibilityPart.java:204) + at sun.reflect.GeneratedMethodAccessor46.invoke(Unknown Source) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) + at java.lang.reflect.Method.invoke(Unknown Source) + at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:56) + at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:252) + at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:258) + at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:229) + at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:107) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.focusGui(PartRenderingEngine.java:775) + at org.eclipse.e4.ui.workbench.renderers.swt.ContributedPartRenderer$2.setFocus(ContributedPartRenderer.java:102) + at org.eclipse.swt.custom.CTabItem.setFocus(CTabItem.java:332) + at org.eclipse.swt.custom.CTabFolder.setFocus(CTabFolder.java:2602) + at org.eclipse.swt.widgets.Control.fixFocus(Control.java:1053) + at org.eclipse.swt.widgets.Control.setVisible(Control.java:3859) + at org.eclipse.swt.custom.CTabFolder.setSelection(CTabFolder.java:3146) + at org.eclipse.swt.custom.CTabFolder.setSelection(CTabFolder.java:3103) + at org.eclipse.e4.ui.workbench.renderers.swt.StackRenderer.showTab(StackRenderer.java:1318) + at org.eclipse.e4.ui.workbench.renderers.swt.LazyStackRenderer$1.handleEvent(LazyStackRenderer.java:72) + at org.eclipse.e4.ui.services.internal.events.UIEventHandler$1.run(UIEventHandler.java:40) + at org.eclipse.swt.widgets.Synchronizer.syncExec(Synchronizer.java:186) + at org.eclipse.ui.internal.UISynchronizer.syncExec(UISynchronizer.java:145) + at org.eclipse.swt.widgets.Display.syncExec(Display.java:4761) + at org.eclipse.e4.ui.internal.workbench.swt.E4Application$1.syncExec(E4Application.java:211) + at org.eclipse.e4.ui.services.internal.events.UIEventHandler.handleEvent(UIEventHandler.java:36) + at org.eclipse.equinox.internal.event.EventHandlerWrapper.handleEvent(EventHandlerWrapper.java:197) + at org.eclipse.equinox.internal.event.EventHandlerTracker.dispatchEvent(EventHandlerTracker.java:197) + at org.eclipse.equinox.internal.event.EventHandlerTracker.dispatchEvent(EventHandlerTracker.java:1) + at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230) + at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:148) + at org.eclipse.equinox.internal.event.EventAdminImpl.dispatchEvent(EventAdminImpl.java:135) + at org.eclipse.equinox.internal.event.EventAdminImpl.sendEvent(EventAdminImpl.java:78) + at org.eclipse.equinox.internal.event.EventComponent.sendEvent(EventComponent.java:39) + at org.eclipse.e4.ui.services.internal.events.EventBroker.send(EventBroker.java:85) + at org.eclipse.e4.ui.internal.workbench.UIEventPublisher.notifyChanged(UIEventPublisher.java:59) + at org.eclipse.emf.common.notify.impl.BasicNotifierImpl.eNotify(BasicNotifierImpl.java:374) + at org.eclipse.e4.ui.model.application.ui.impl.ElementContainerImpl.setSelectedElement(ElementContainerImpl.java:171) + at org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.showElementInWindow(ModelServiceImpl.java:494) + at org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.bringToTop(ModelServiceImpl.java:458) + at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.delegateBringToTop(PartServiceImpl.java:724) + at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.showPart(PartServiceImpl.java:1163) + at org.eclipse.ui.internal.WorkbenchPage.busyOpenEditor(WorkbenchPage.java:3234) + at org.eclipse.ui.internal.WorkbenchPage.access$25(WorkbenchPage.java:3149) + at org.eclipse.ui.internal.WorkbenchPage$10.run(WorkbenchPage.java:3131) + at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) + at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:3126) + at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:3090) + at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:3080) + at org.eclipse.ui.internal.NavigationHistoryEntry.restoreLocation(NavigationHistoryEntry.java:66) + at org.eclipse.ui.internal.NavigationHistory.gotoEntry(NavigationHistory.java:452) + at org.eclipse.ui.internal.NavigationHistory.shiftEntry(NavigationHistory.java:517) + at org.eclipse.ui.internal.NavigationHistory.backward(NavigationHistory.java:501) + at org.eclipse.ui.internal.NavigationHistoryAction.run(NavigationHistoryAction.java:242) + at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) + at org.eclipse.jface.commands.ActionHandler.execute(ActionHandler.java:122) + at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:90) + at sun.reflect.GeneratedMethodAccessor56.invoke(Unknown Source) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) + at java.lang.reflect.Method.invoke(Unknown Source) + at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:56) + at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:252) + at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:234) + at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132) + at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:152) + at org.eclipse.core.commands.Command.executeWithChecks(Command.java:493) + at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:486) + at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:210) + at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.executeCommand(KeyBindingDispatcher.java:286) + at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.press(KeyBindingDispatcher.java:507) + at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.processKeyEvent(KeyBindingDispatcher.java:558) + at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.filterKeySequenceBindings(KeyBindingDispatcher.java:378) + at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.access$0(KeyBindingDispatcher.java:324) + at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher$KeyDownFilter.handleEvent(KeyBindingDispatcher.java:86) + at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) + at org.eclipse.swt.widgets.Display.filterEvent(Display.java:1266) + at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1112) + at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1137) + at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1122) + at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1164) + at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1160) + at org.eclipse.swt.widgets.Widget.wmSysKeyDown(Widget.java:2632) + at org.eclipse.swt.widgets.Control.WM_SYSKEYDOWN(Control.java:5468) + at org.eclipse.swt.widgets.Control.windowProc(Control.java:4755) + at org.eclipse.swt.widgets.Canvas.windowProc(Canvas.java:339) + at org.eclipse.swt.widgets.Display.windowProc(Display.java:5063) + at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) + at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:2549) + at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3767) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1127) + at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1018) + at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:156) + at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:654) + at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337) + at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:598) + at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:150) + at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:139) + at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) + at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) + at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) + at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:380) + at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:235) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) + at java.lang.reflect.Method.invoke(Unknown Source) + at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:669) + at org.eclipse.equinox.launcher.Main.basicRun(Main.java:608) + at org.eclipse.equinox.launcher.Main.run(Main.java:1515) + +!ENTRY org.eclipse.e4.ui.workbench 4 0 2016-02-25 19:51:00.462 +!MESSAGE Error setting focus to : org.eclipse.e4.ui.model.application.ui.basic.impl.PartImpl ThreadEx12.java +!STACK 0 +org.eclipse.swt.SWTException: Widget is disposed + at org.eclipse.swt.SWT.error(SWT.java:4491) + at org.eclipse.swt.SWT.error(SWT.java:4406) + at org.eclipse.swt.SWT.error(SWT.java:4377) + at org.eclipse.swt.widgets.Widget.error(Widget.java:482) + at org.eclipse.swt.widgets.Widget.checkWidget(Widget.java:354) + at org.eclipse.swt.widgets.Control.setFocus(Control.java:3354) + at org.eclipse.swt.widgets.Composite.setFocus(Composite.java:1056) + at org.eclipse.swt.widgets.Composite.setFocus(Composite.java:1056) + at org.eclipse.ui.texteditor.StatusTextEditor.setFocus(StatusTextEditor.java:120) + at org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.setFocus(JavaEditor.java:2395) + at org.eclipse.ui.internal.e4.compatibility.CompatibilityPart.delegateSetFocus(CompatibilityPart.java:204) + at sun.reflect.GeneratedMethodAccessor46.invoke(Unknown Source) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) + at java.lang.reflect.Method.invoke(Unknown Source) + at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:56) + at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:252) + at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:258) + at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:229) + at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:107) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.focusGui(PartRenderingEngine.java:775) + at org.eclipse.e4.ui.workbench.renderers.swt.ContributedPartRenderer$2.setFocus(ContributedPartRenderer.java:102) + at org.eclipse.swt.custom.CTabItem.setFocus(CTabItem.java:332) + at org.eclipse.swt.custom.CTabFolder.setFocus(CTabFolder.java:2602) + at org.eclipse.swt.widgets.Control.fixFocus(Control.java:1053) + at org.eclipse.swt.widgets.Control.setVisible(Control.java:3859) + at org.eclipse.swt.custom.CTabFolder.setSelection(CTabFolder.java:3146) + at org.eclipse.swt.custom.CTabFolder.setSelection(CTabFolder.java:3103) + at org.eclipse.e4.ui.workbench.renderers.swt.StackRenderer.showTab(StackRenderer.java:1318) + at org.eclipse.e4.ui.workbench.renderers.swt.LazyStackRenderer$1.handleEvent(LazyStackRenderer.java:72) + at org.eclipse.e4.ui.services.internal.events.UIEventHandler$1.run(UIEventHandler.java:40) + at org.eclipse.swt.widgets.Synchronizer.syncExec(Synchronizer.java:186) + at org.eclipse.ui.internal.UISynchronizer.syncExec(UISynchronizer.java:145) + at org.eclipse.swt.widgets.Display.syncExec(Display.java:4761) + at org.eclipse.e4.ui.internal.workbench.swt.E4Application$1.syncExec(E4Application.java:211) + at org.eclipse.e4.ui.services.internal.events.UIEventHandler.handleEvent(UIEventHandler.java:36) + at org.eclipse.equinox.internal.event.EventHandlerWrapper.handleEvent(EventHandlerWrapper.java:197) + at org.eclipse.equinox.internal.event.EventHandlerTracker.dispatchEvent(EventHandlerTracker.java:197) + at org.eclipse.equinox.internal.event.EventHandlerTracker.dispatchEvent(EventHandlerTracker.java:1) + at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230) + at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:148) + at org.eclipse.equinox.internal.event.EventAdminImpl.dispatchEvent(EventAdminImpl.java:135) + at org.eclipse.equinox.internal.event.EventAdminImpl.sendEvent(EventAdminImpl.java:78) + at org.eclipse.equinox.internal.event.EventComponent.sendEvent(EventComponent.java:39) + at org.eclipse.e4.ui.services.internal.events.EventBroker.send(EventBroker.java:85) + at org.eclipse.e4.ui.internal.workbench.UIEventPublisher.notifyChanged(UIEventPublisher.java:59) + at org.eclipse.emf.common.notify.impl.BasicNotifierImpl.eNotify(BasicNotifierImpl.java:374) + at org.eclipse.e4.ui.model.application.ui.impl.ElementContainerImpl.setSelectedElement(ElementContainerImpl.java:171) + at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.hidePart(PartServiceImpl.java:1279) + at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.hidePart(PartServiceImpl.java:1236) + at org.eclipse.e4.ui.workbench.renderers.swt.StackRenderer.closePart(StackRenderer.java:1278) + at org.eclipse.e4.ui.workbench.renderers.swt.StackRenderer.access$4(StackRenderer.java:1260) + at org.eclipse.e4.ui.workbench.renderers.swt.StackRenderer$11.close(StackRenderer.java:1145) + at org.eclipse.swt.custom.CTabFolder.onMouse(CTabFolder.java:1921) + at org.eclipse.swt.custom.CTabFolder$1.handleEvent(CTabFolder.java:335) + at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) + at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4362) + at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1113) + at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4180) + at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3769) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1127) + at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1018) + at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:156) + at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:654) + at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337) + at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:598) + at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:150) + at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:139) + at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) + at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) + at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) + at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:380) + at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:235) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) + at java.lang.reflect.Method.invoke(Unknown Source) + at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:669) + at org.eclipse.equinox.launcher.Main.basicRun(Main.java:608) + at org.eclipse.equinox.launcher.Main.run(Main.java:1515) + +!ENTRY org.eclipse.e4.ui.workbench 4 0 2016-02-25 19:55:43.864 +!MESSAGE Error setting focus to : org.eclipse.e4.ui.model.application.ui.basic.impl.PartImpl ThreadEx12.java +!STACK 0 +org.eclipse.swt.SWTException: Widget is disposed + at org.eclipse.swt.SWT.error(SWT.java:4491) + at org.eclipse.swt.SWT.error(SWT.java:4406) + at org.eclipse.swt.SWT.error(SWT.java:4377) + at org.eclipse.swt.widgets.Widget.error(Widget.java:482) + at org.eclipse.swt.widgets.Widget.checkWidget(Widget.java:354) + at org.eclipse.swt.widgets.Control.setFocus(Control.java:3354) + at org.eclipse.swt.widgets.Composite.setFocus(Composite.java:1056) + at org.eclipse.swt.widgets.Composite.setFocus(Composite.java:1056) + at org.eclipse.ui.texteditor.StatusTextEditor.setFocus(StatusTextEditor.java:120) + at org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.setFocus(JavaEditor.java:2395) + at org.eclipse.ui.internal.e4.compatibility.CompatibilityPart.delegateSetFocus(CompatibilityPart.java:204) + at sun.reflect.GeneratedMethodAccessor46.invoke(Unknown Source) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) + at java.lang.reflect.Method.invoke(Unknown Source) + at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:56) + at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:252) + at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:258) + at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:229) + at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:107) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.focusGui(PartRenderingEngine.java:775) + at org.eclipse.e4.ui.workbench.renderers.swt.ContributedPartRenderer$2.setFocus(ContributedPartRenderer.java:102) + at org.eclipse.swt.custom.CTabItem.setFocus(CTabItem.java:332) + at org.eclipse.swt.custom.CTabFolder.setFocus(CTabFolder.java:2602) + at org.eclipse.swt.widgets.Control.fixFocus(Control.java:1053) + at org.eclipse.swt.widgets.Control.setVisible(Control.java:3859) + at org.eclipse.swt.custom.CTabFolder.setSelection(CTabFolder.java:3146) + at org.eclipse.swt.custom.CTabFolder.setSelection(CTabFolder.java:3103) + at org.eclipse.e4.ui.workbench.renderers.swt.StackRenderer.showTab(StackRenderer.java:1318) + at org.eclipse.e4.ui.workbench.renderers.swt.LazyStackRenderer$1.handleEvent(LazyStackRenderer.java:72) + at org.eclipse.e4.ui.services.internal.events.UIEventHandler$1.run(UIEventHandler.java:40) + at org.eclipse.swt.widgets.Synchronizer.syncExec(Synchronizer.java:186) + at org.eclipse.ui.internal.UISynchronizer.syncExec(UISynchronizer.java:145) + at org.eclipse.swt.widgets.Display.syncExec(Display.java:4761) + at org.eclipse.e4.ui.internal.workbench.swt.E4Application$1.syncExec(E4Application.java:211) + at org.eclipse.e4.ui.services.internal.events.UIEventHandler.handleEvent(UIEventHandler.java:36) + at org.eclipse.equinox.internal.event.EventHandlerWrapper.handleEvent(EventHandlerWrapper.java:197) + at org.eclipse.equinox.internal.event.EventHandlerTracker.dispatchEvent(EventHandlerTracker.java:197) + at org.eclipse.equinox.internal.event.EventHandlerTracker.dispatchEvent(EventHandlerTracker.java:1) + at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230) + at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:148) + at org.eclipse.equinox.internal.event.EventAdminImpl.dispatchEvent(EventAdminImpl.java:135) + at org.eclipse.equinox.internal.event.EventAdminImpl.sendEvent(EventAdminImpl.java:78) + at org.eclipse.equinox.internal.event.EventComponent.sendEvent(EventComponent.java:39) + at org.eclipse.e4.ui.services.internal.events.EventBroker.send(EventBroker.java:85) + at org.eclipse.e4.ui.internal.workbench.UIEventPublisher.notifyChanged(UIEventPublisher.java:59) + at org.eclipse.emf.common.notify.impl.BasicNotifierImpl.eNotify(BasicNotifierImpl.java:374) + at org.eclipse.e4.ui.model.application.ui.impl.ElementContainerImpl.setSelectedElement(ElementContainerImpl.java:171) + at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.hidePart(PartServiceImpl.java:1279) + at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.hidePart(PartServiceImpl.java:1236) + at org.eclipse.e4.ui.workbench.renderers.swt.StackRenderer.closePart(StackRenderer.java:1278) + at org.eclipse.e4.ui.workbench.renderers.swt.StackRenderer.access$4(StackRenderer.java:1260) + at org.eclipse.e4.ui.workbench.renderers.swt.StackRenderer$11.close(StackRenderer.java:1145) + at org.eclipse.swt.custom.CTabFolder.onMouse(CTabFolder.java:1921) + at org.eclipse.swt.custom.CTabFolder$1.handleEvent(CTabFolder.java:335) + at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) + at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4362) + at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1113) + at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4180) + at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3769) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1127) + at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1018) + at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:156) + at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:654) + at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337) + at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:598) + at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:150) + at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:139) + at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) + at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) + at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) + at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:380) + at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:235) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) + at java.lang.reflect.Method.invoke(Unknown Source) + at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:669) + at org.eclipse.equinox.launcher.Main.basicRun(Main.java:608) + at org.eclipse.equinox.launcher.Main.run(Main.java:1515) + +!ENTRY org.eclipse.e4.ui.workbench 4 0 2016-02-25 19:55:47.421 +!MESSAGE Error setting focus to : org.eclipse.e4.ui.model.application.ui.basic.impl.PartImpl ThreadEx15.java +!STACK 0 +org.eclipse.swt.SWTException: Widget is disposed + at org.eclipse.swt.SWT.error(SWT.java:4491) + at org.eclipse.swt.SWT.error(SWT.java:4406) + at org.eclipse.swt.SWT.error(SWT.java:4377) + at org.eclipse.swt.widgets.Widget.error(Widget.java:482) + at org.eclipse.swt.widgets.Widget.checkWidget(Widget.java:354) + at org.eclipse.swt.widgets.Control.setFocus(Control.java:3354) + at org.eclipse.swt.widgets.Composite.setFocus(Composite.java:1056) + at org.eclipse.swt.widgets.Composite.setFocus(Composite.java:1056) + at org.eclipse.ui.texteditor.StatusTextEditor.setFocus(StatusTextEditor.java:120) + at org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.setFocus(JavaEditor.java:2395) + at org.eclipse.ui.internal.e4.compatibility.CompatibilityPart.delegateSetFocus(CompatibilityPart.java:204) + at sun.reflect.GeneratedMethodAccessor46.invoke(Unknown Source) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) + at java.lang.reflect.Method.invoke(Unknown Source) + at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:56) + at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:252) + at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:258) + at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:229) + at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:107) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.focusGui(PartRenderingEngine.java:775) + at org.eclipse.e4.ui.workbench.renderers.swt.ContributedPartRenderer$2.setFocus(ContributedPartRenderer.java:102) + at org.eclipse.swt.custom.CTabItem.setFocus(CTabItem.java:332) + at org.eclipse.swt.custom.CTabFolder.setFocus(CTabFolder.java:2602) + at org.eclipse.swt.widgets.Control.fixFocus(Control.java:1053) + at org.eclipse.swt.widgets.Control.setVisible(Control.java:3859) + at org.eclipse.swt.custom.CTabFolder.setSelection(CTabFolder.java:3146) + at org.eclipse.swt.custom.CTabFolder.setSelection(CTabFolder.java:3103) + at org.eclipse.e4.ui.workbench.renderers.swt.StackRenderer.showTab(StackRenderer.java:1318) + at org.eclipse.e4.ui.workbench.renderers.swt.LazyStackRenderer$1.handleEvent(LazyStackRenderer.java:72) + at org.eclipse.e4.ui.services.internal.events.UIEventHandler$1.run(UIEventHandler.java:40) + at org.eclipse.swt.widgets.Synchronizer.syncExec(Synchronizer.java:186) + at org.eclipse.ui.internal.UISynchronizer.syncExec(UISynchronizer.java:145) + at org.eclipse.swt.widgets.Display.syncExec(Display.java:4761) + at org.eclipse.e4.ui.internal.workbench.swt.E4Application$1.syncExec(E4Application.java:211) + at org.eclipse.e4.ui.services.internal.events.UIEventHandler.handleEvent(UIEventHandler.java:36) + at org.eclipse.equinox.internal.event.EventHandlerWrapper.handleEvent(EventHandlerWrapper.java:197) + at org.eclipse.equinox.internal.event.EventHandlerTracker.dispatchEvent(EventHandlerTracker.java:197) + at org.eclipse.equinox.internal.event.EventHandlerTracker.dispatchEvent(EventHandlerTracker.java:1) + at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230) + at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:148) + at org.eclipse.equinox.internal.event.EventAdminImpl.dispatchEvent(EventAdminImpl.java:135) + at org.eclipse.equinox.internal.event.EventAdminImpl.sendEvent(EventAdminImpl.java:78) + at org.eclipse.equinox.internal.event.EventComponent.sendEvent(EventComponent.java:39) + at org.eclipse.e4.ui.services.internal.events.EventBroker.send(EventBroker.java:85) + at org.eclipse.e4.ui.internal.workbench.UIEventPublisher.notifyChanged(UIEventPublisher.java:59) + at org.eclipse.emf.common.notify.impl.BasicNotifierImpl.eNotify(BasicNotifierImpl.java:374) + at org.eclipse.e4.ui.model.application.ui.impl.ElementContainerImpl.setSelectedElement(ElementContainerImpl.java:171) + at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.hidePart(PartServiceImpl.java:1279) + at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.hidePart(PartServiceImpl.java:1236) + at org.eclipse.e4.ui.workbench.renderers.swt.StackRenderer.closePart(StackRenderer.java:1278) + at org.eclipse.e4.ui.workbench.renderers.swt.StackRenderer.access$4(StackRenderer.java:1260) + at org.eclipse.e4.ui.workbench.renderers.swt.StackRenderer$11.close(StackRenderer.java:1145) + at org.eclipse.swt.custom.CTabFolder.onMouse(CTabFolder.java:1921) + at org.eclipse.swt.custom.CTabFolder$1.handleEvent(CTabFolder.java:335) + at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) + at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4362) + at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1113) + at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4180) + at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3769) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1127) + at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1018) + at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:156) + at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:654) + at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337) + at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:598) + at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:150) + at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:139) + at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) + at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) + at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) + at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:380) + at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:235) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) + at java.lang.reflect.Method.invoke(Unknown Source) + at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:669) + at org.eclipse.equinox.launcher.Main.basicRun(Main.java:608) + at org.eclipse.equinox.launcher.Main.run(Main.java:1515) + +!ENTRY org.eclipse.e4.ui.workbench 4 0 2016-02-25 19:55:48.413 +!MESSAGE Error setting focus to : org.eclipse.e4.ui.model.application.ui.basic.impl.PartImpl ForkJoinEx1.java +!STACK 0 +org.eclipse.swt.SWTException: Widget is disposed + at org.eclipse.swt.SWT.error(SWT.java:4491) + at org.eclipse.swt.SWT.error(SWT.java:4406) + at org.eclipse.swt.SWT.error(SWT.java:4377) + at org.eclipse.swt.widgets.Widget.error(Widget.java:482) + at org.eclipse.swt.widgets.Widget.checkWidget(Widget.java:354) + at org.eclipse.swt.widgets.Control.setFocus(Control.java:3354) + at org.eclipse.swt.widgets.Composite.setFocus(Composite.java:1056) + at org.eclipse.swt.widgets.Composite.setFocus(Composite.java:1056) + at org.eclipse.ui.texteditor.StatusTextEditor.setFocus(StatusTextEditor.java:120) + at org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.setFocus(JavaEditor.java:2395) + at org.eclipse.ui.internal.e4.compatibility.CompatibilityPart.delegateSetFocus(CompatibilityPart.java:204) + at sun.reflect.GeneratedMethodAccessor46.invoke(Unknown Source) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) + at java.lang.reflect.Method.invoke(Unknown Source) + at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:56) + at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:252) + at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:258) + at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:229) + at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:107) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.focusGui(PartRenderingEngine.java:775) + at org.eclipse.e4.ui.workbench.renderers.swt.ContributedPartRenderer$2.setFocus(ContributedPartRenderer.java:102) + at org.eclipse.swt.custom.CTabItem.setFocus(CTabItem.java:332) + at org.eclipse.swt.custom.CTabFolder.setFocus(CTabFolder.java:2602) + at org.eclipse.swt.widgets.Control.fixFocus(Control.java:1053) + at org.eclipse.swt.widgets.Control.setVisible(Control.java:3859) + at org.eclipse.swt.custom.CTabFolder.setSelection(CTabFolder.java:3146) + at org.eclipse.swt.custom.CTabFolder.setSelection(CTabFolder.java:3103) + at org.eclipse.e4.ui.workbench.renderers.swt.StackRenderer.showTab(StackRenderer.java:1318) + at org.eclipse.e4.ui.workbench.renderers.swt.LazyStackRenderer$1.handleEvent(LazyStackRenderer.java:72) + at org.eclipse.e4.ui.services.internal.events.UIEventHandler$1.run(UIEventHandler.java:40) + at org.eclipse.swt.widgets.Synchronizer.syncExec(Synchronizer.java:186) + at org.eclipse.ui.internal.UISynchronizer.syncExec(UISynchronizer.java:145) + at org.eclipse.swt.widgets.Display.syncExec(Display.java:4761) + at org.eclipse.e4.ui.internal.workbench.swt.E4Application$1.syncExec(E4Application.java:211) + at org.eclipse.e4.ui.services.internal.events.UIEventHandler.handleEvent(UIEventHandler.java:36) + at org.eclipse.equinox.internal.event.EventHandlerWrapper.handleEvent(EventHandlerWrapper.java:197) + at org.eclipse.equinox.internal.event.EventHandlerTracker.dispatchEvent(EventHandlerTracker.java:197) + at org.eclipse.equinox.internal.event.EventHandlerTracker.dispatchEvent(EventHandlerTracker.java:1) + at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230) + at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:148) + at org.eclipse.equinox.internal.event.EventAdminImpl.dispatchEvent(EventAdminImpl.java:135) + at org.eclipse.equinox.internal.event.EventAdminImpl.sendEvent(EventAdminImpl.java:78) + at org.eclipse.equinox.internal.event.EventComponent.sendEvent(EventComponent.java:39) + at org.eclipse.e4.ui.services.internal.events.EventBroker.send(EventBroker.java:85) + at org.eclipse.e4.ui.internal.workbench.UIEventPublisher.notifyChanged(UIEventPublisher.java:59) + at org.eclipse.emf.common.notify.impl.BasicNotifierImpl.eNotify(BasicNotifierImpl.java:374) + at org.eclipse.e4.ui.model.application.ui.impl.ElementContainerImpl.setSelectedElement(ElementContainerImpl.java:171) + at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.hidePart(PartServiceImpl.java:1279) + at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.hidePart(PartServiceImpl.java:1236) + at org.eclipse.e4.ui.workbench.renderers.swt.StackRenderer.closePart(StackRenderer.java:1278) + at org.eclipse.e4.ui.workbench.renderers.swt.StackRenderer.access$4(StackRenderer.java:1260) + at org.eclipse.e4.ui.workbench.renderers.swt.StackRenderer$11.close(StackRenderer.java:1145) + at org.eclipse.swt.custom.CTabFolder.onMouse(CTabFolder.java:1921) + at org.eclipse.swt.custom.CTabFolder$1.handleEvent(CTabFolder.java:335) + at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) + at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4362) + at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1113) + at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4180) + at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3769) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1127) + at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1018) + at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:156) + at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:654) + at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337) + at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:598) + at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:150) + at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:139) + at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) + at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) + at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) + at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:380) + at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:235) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) + at java.lang.reflect.Method.invoke(Unknown Source) + at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:669) + at org.eclipse.equinox.launcher.Main.basicRun(Main.java:608) + at org.eclipse.equinox.launcher.Main.run(Main.java:1515) +!SESSION 2016-02-25 20:20:14.246 ----------------------------------------------- +eclipse.buildId=4.5.1.M20150904-0015 +java.version=1.8.0_65 +java.vendor=Oracle Corporation +BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=ko_KR +Framework arguments: -product org.eclipse.epp.package.java.product -product org.eclipse.epp.package.java.product +Command-line arguments: -os win32 -ws win32 -arch x86 -product org.eclipse.epp.package.java.product -data file:/C:/Users/castello/workspace/ -product org.eclipse.epp.package.java.product + +!ENTRY org.eclipse.egit.ui 2 0 2016-02-25 20:20:24.121 +!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git +user global configuration and to define the default location to store repositories: 'C:\Users\castello'. If this is +not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and +EGit might behave differently since they see different configuration options. +This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. +!SESSION 2016-02-25 21:39:14.846 ----------------------------------------------- +eclipse.buildId=4.5.1.M20150904-0015 +java.version=1.8.0_65 +java.vendor=Oracle Corporation +BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=ko_KR +Framework arguments: -product org.eclipse.epp.package.java.product +Command-line arguments: -os win32 -ws win32 -arch x86 -product org.eclipse.epp.package.java.product + +!ENTRY org.eclipse.egit.ui 2 0 2016-02-25 21:39:24.721 +!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git +user global configuration and to define the default location to store repositories: 'C:\Users\castello'. If this is +not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and +EGit might behave differently since they see different configuration options. +This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. +!SESSION 2016-02-26 15:38:09.343 ----------------------------------------------- +eclipse.buildId=4.5.1.M20150904-0015 +java.version=1.8.0_65 +java.vendor=Oracle Corporation +BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=ko_KR +Framework arguments: -product org.eclipse.epp.package.java.product +Command-line arguments: -os win32 -ws win32 -arch x86 -product org.eclipse.epp.package.java.product + +!ENTRY org.eclipse.egit.ui 2 0 2016-02-26 15:38:24.097 +!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git +user global configuration and to define the default location to store repositories: 'C:\Users\castello'. If this is +not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and +EGit might behave differently since they see different configuration options. +This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. + +!ENTRY org.eclipse.jface 4 2 2016-02-26 15:47:23.607 +!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jface". +!STACK 0 +java.lang.NullPointerException + at org.eclipse.core.internal.net.StringUtil.split(StringUtil.java:33) + at org.eclipse.core.internal.net.ProxyType.convertPropertyStringToHosts(ProxyType.java:102) + at org.eclipse.core.internal.net.ProxyManager.getNonProxiedHosts(ProxyManager.java:118) + at org.eclipse.core.internal.net.ProxySelector.getBypassHosts(ProxySelector.java:130) + at org.eclipse.ui.internal.net.NonProxyHostsComposite.getProxyBypassData(NonProxyHostsComposite.java:344) + at org.eclipse.ui.internal.net.NonProxyHostsComposite.initializeValues(NonProxyHostsComposite.java:283) + at org.eclipse.ui.internal.net.NonProxyHostsComposite.createWidgets(NonProxyHostsComposite.java:133) + at org.eclipse.ui.internal.net.NonProxyHostsComposite.(NonProxyHostsComposite.java:66) + at org.eclipse.ui.internal.net.ProxyPreferencePage.createNonProxiedHostsComposite(ProxyPreferencePage.java:89) + at org.eclipse.ui.internal.net.ProxyPreferencePage.createContents(ProxyPreferencePage.java:55) + at org.eclipse.jface.preference.PreferencePage.createControl(PreferencePage.java:241) + at org.eclipse.jface.preference.PreferenceDialog.createPageControl(PreferenceDialog.java:1450) + at org.eclipse.jface.preference.PreferenceDialog$13.run(PreferenceDialog.java:1217) + at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) + at org.eclipse.ui.internal.JFaceUtil$1.run(JFaceUtil.java:50) + at org.eclipse.jface.util.SafeRunnable.run(SafeRunnable.java:173) + at org.eclipse.jface.preference.PreferenceDialog.showPage(PreferenceDialog.java:1209) + at org.eclipse.ui.internal.dialogs.FilteredPreferenceDialog.showPage(FilteredPreferenceDialog.java:608) + at org.eclipse.jface.preference.PreferenceDialog$9$1.run(PreferenceDialog.java:675) + at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) + at org.eclipse.jface.preference.PreferenceDialog$9.selectionChanged(PreferenceDialog.java:670) + at org.eclipse.jface.viewers.StructuredViewer$3.run(StructuredViewer.java:877) + at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) + at org.eclipse.ui.internal.JFaceUtil$1.run(JFaceUtil.java:50) + at org.eclipse.jface.util.SafeRunnable.run(SafeRunnable.java:173) + at org.eclipse.jface.viewers.StructuredViewer.firePostSelectionChanged(StructuredViewer.java:874) + at org.eclipse.jface.viewers.StructuredViewer.handlePostSelect(StructuredViewer.java:1243) + at org.eclipse.jface.viewers.StructuredViewer$5.widgetSelected(StructuredViewer.java:1269) + at org.eclipse.jface.util.OpenStrategy.firePostSelectionEvent(OpenStrategy.java:265) + at org.eclipse.jface.util.OpenStrategy.access$5(OpenStrategy.java:259) + at org.eclipse.jface.util.OpenStrategy$1$2.run(OpenStrategy.java:440) + at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35) + at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:135) + at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4155) + at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3772) + at org.eclipse.jface.window.Window.runEventLoop(Window.java:827) + at org.eclipse.jface.window.Window.open(Window.java:803) + at org.eclipse.ui.internal.dialogs.WorkbenchPreferenceDialog.open(WorkbenchPreferenceDialog.java:211) + at org.eclipse.ui.internal.OpenPreferencesAction.run(OpenPreferencesAction.java:63) + at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) + at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:595) + at org.eclipse.jface.action.ActionContributionItem.access$2(ActionContributionItem.java:511) + at org.eclipse.jface.action.ActionContributionItem$5.handleEvent(ActionContributionItem.java:420) + at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) + at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4362) + at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1113) + at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4180) + at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3769) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1127) + at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1018) + at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:156) + at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:654) + at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337) + at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:598) + at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:150) + at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:139) + at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) + at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) + at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) + at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:380) + at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:235) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) + at java.lang.reflect.Method.invoke(Unknown Source) + at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:669) + at org.eclipse.equinox.launcher.Main.basicRun(Main.java:608) + at org.eclipse.equinox.launcher.Main.run(Main.java:1515) +!SESSION 2016-02-26 22:38:09.012 ----------------------------------------------- +eclipse.buildId=4.5.1.M20150904-0015 +java.version=1.8.0_65 +java.vendor=Oracle Corporation +BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=ko_KR +Framework arguments: -product org.eclipse.epp.package.java.product +Command-line arguments: -os win32 -ws win32 -arch x86 -product org.eclipse.epp.package.java.product + +!ENTRY org.eclipse.egit.ui 2 0 2016-02-26 22:38:18.947 +!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git +user global configuration and to define the default location to store repositories: 'C:\Users\castello'. If this is +not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and +EGit might behave differently since they see different configuration options. +This warning can be switched off on the Team > Git > Confirmations and Warnings preference page. + +!ENTRY org.eclipse.ui 4 4 2016-02-26 22:52:05.527 +!MESSAGE Unable to create part + +!ENTRY org.eclipse.jdt.ui 4 996 2016-02-26 22:52:05.621 +!MESSAGE The Class File Viewer cannot handle the given input ('org.eclipse.ui.part.FileEditorInput'). +!STACK 1 +org.eclipse.core.runtime.CoreException: The Class File Viewer cannot handle the given input ('org.eclipse.ui.part.FileEditorInput'). + at org.eclipse.jdt.internal.ui.javaeditor.ClassFileEditor.doSetInput(ClassFileEditor.java:677) + at org.eclipse.ui.texteditor.AbstractTextEditor$19.run(AbstractTextEditor.java:3220) + at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalContext.java:463) + at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:371) + at org.eclipse.ui.internal.WorkbenchWindow$14.run(WorkbenchWindow.java:2156) + at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) + at org.eclipse.ui.internal.WorkbenchWindow.run(WorkbenchWindow.java:2152) + at org.eclipse.ui.texteditor.AbstractTextEditor.internalInit(AbstractTextEditor.java:3238) + at org.eclipse.ui.texteditor.AbstractTextEditor.init(AbstractTextEditor.java:3265) + at org.eclipse.ui.internal.EditorReference.initialize(EditorReference.java:361) + at org.eclipse.ui.internal.e4.compatibility.CompatibilityPart.create(CompatibilityPart.java:319) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) + at java.lang.reflect.Method.invoke(Unknown Source) + at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:56) + at org.eclipse.e4.core.internal.di.InjectorImpl.processAnnotated(InjectorImpl.java:898) + at org.eclipse.e4.core.internal.di.InjectorImpl.processAnnotated(InjectorImpl.java:879) + at org.eclipse.e4.core.internal.di.InjectorImpl.inject(InjectorImpl.java:121) + at org.eclipse.e4.core.internal.di.InjectorImpl.internalMake(InjectorImpl.java:345) + at org.eclipse.e4.core.internal.di.InjectorImpl.make(InjectorImpl.java:264) + at org.eclipse.e4.core.contexts.ContextInjectionFactory.make(ContextInjectionFactory.java:162) + at org.eclipse.e4.ui.internal.workbench.ReflectionContributionFactory.createFromBundle(ReflectionContributionFactory.java:104) + at org.eclipse.e4.ui.internal.workbench.ReflectionContributionFactory.doCreate(ReflectionContributionFactory.java:73) + at org.eclipse.e4.ui.internal.workbench.ReflectionContributionFactory.create(ReflectionContributionFactory.java:55) + at org.eclipse.e4.ui.workbench.renderers.swt.ContributedPartRenderer.createWidget(ContributedPartRenderer.java:129) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.createWidget(PartRenderingEngine.java:971) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.safeCreateGui(PartRenderingEngine.java:640) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.safeCreateGui(PartRenderingEngine.java:746) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.access$0(PartRenderingEngine.java:717) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$2.run(PartRenderingEngine.java:711) + at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.createGui(PartRenderingEngine.java:695) + at org.eclipse.e4.ui.internal.workbench.PartServiceImpl$1.handleEvent(PartServiceImpl.java:99) + at org.eclipse.e4.ui.services.internal.events.UIEventHandler$1.run(UIEventHandler.java:40) + at org.eclipse.swt.widgets.Synchronizer.syncExec(Synchronizer.java:186) + at org.eclipse.ui.internal.UISynchronizer.syncExec(UISynchronizer.java:145) + at org.eclipse.swt.widgets.Display.syncExec(Display.java:4761) + at org.eclipse.e4.ui.internal.workbench.swt.E4Application$1.syncExec(E4Application.java:211) + at org.eclipse.e4.ui.services.internal.events.UIEventHandler.handleEvent(UIEventHandler.java:36) + at org.eclipse.equinox.internal.event.EventHandlerWrapper.handleEvent(EventHandlerWrapper.java:197) + at org.eclipse.equinox.internal.event.EventHandlerTracker.dispatchEvent(EventHandlerTracker.java:197) + at org.eclipse.equinox.internal.event.EventHandlerTracker.dispatchEvent(EventHandlerTracker.java:1) + at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230) + at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:148) + at org.eclipse.equinox.internal.event.EventAdminImpl.dispatchEvent(EventAdminImpl.java:135) + at org.eclipse.equinox.internal.event.EventAdminImpl.sendEvent(EventAdminImpl.java:78) + at org.eclipse.equinox.internal.event.EventComponent.sendEvent(EventComponent.java:39) + at org.eclipse.e4.ui.services.internal.events.EventBroker.send(EventBroker.java:85) + at org.eclipse.e4.ui.internal.workbench.UIEventPublisher.notifyChanged(UIEventPublisher.java:59) + at org.eclipse.emf.common.notify.impl.BasicNotifierImpl.eNotify(BasicNotifierImpl.java:374) + at org.eclipse.e4.ui.model.application.ui.impl.ElementContainerImpl.setSelectedElement(ElementContainerImpl.java:171) + at org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.showElementInWindow(ModelServiceImpl.java:494) + at org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.bringToTop(ModelServiceImpl.java:458) + at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.delegateBringToTop(PartServiceImpl.java:724) + at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.bringToTop(PartServiceImpl.java:396) + at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.showPart(PartServiceImpl.java:1166) + at org.eclipse.ui.internal.WorkbenchPage.busyOpenEditor(WorkbenchPage.java:3234) + at org.eclipse.ui.internal.WorkbenchPage.access$25(WorkbenchPage.java:3149) + at org.eclipse.ui.internal.WorkbenchPage$10.run(WorkbenchPage.java:3131) + at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) + at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:3126) + at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:3090) + at org.eclipse.ui.actions.OpenWithMenu.openEditor(OpenWithMenu.java:336) + at org.eclipse.ui.actions.OpenWithMenu$3.handleEvent(OpenWithMenu.java:216) + at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) + at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4362) + at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1113) + at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4180) + at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3769) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1127) + at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337) + at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1018) + at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:156) + at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:654) + at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337) + at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:598) + at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:150) + at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:139) + at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) + at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) + at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) + at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:380) + at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:235) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) + at java.lang.reflect.Method.invoke(Unknown Source) + at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:669) + at org.eclipse.equinox.launcher.Main.basicRun(Main.java:608) + at org.eclipse.equinox.launcher.Main.run(Main.java:1515) +!SUBENTRY 1 org.eclipse.jdt.ui 4 996 2016-02-26 22:52:05.621 +!MESSAGE The Class File Viewer cannot handle the given input ('org.eclipse.ui.part.FileEditorInput'). diff --git a/workspace/.metadata/.mylyn/.taskListIndex/segments.gen b/workspace/.metadata/.mylyn/.taskListIndex/segments.gen new file mode 100644 index 0000000..63a7ec9 Binary files /dev/null and b/workspace/.metadata/.mylyn/.taskListIndex/segments.gen differ diff --git a/workspace/.metadata/.mylyn/.taskListIndex/segments_1 b/workspace/.metadata/.mylyn/.taskListIndex/segments_1 new file mode 100644 index 0000000..e18d9e5 Binary files /dev/null and b/workspace/.metadata/.mylyn/.taskListIndex/segments_1 differ diff --git a/workspace/.metadata/.mylyn/.tasks.xml.zip b/workspace/.metadata/.mylyn/.tasks.xml.zip new file mode 100644 index 0000000..a2f1a1b Binary files /dev/null and b/workspace/.metadata/.mylyn/.tasks.xml.zip differ diff --git a/workspace/.metadata/.mylyn/repositories.xml.zip b/workspace/.metadata/.mylyn/repositories.xml.zip new file mode 100644 index 0000000..6cc6ce0 Binary files /dev/null and b/workspace/.metadata/.mylyn/repositories.xml.zip differ diff --git a/workspace/.metadata/.mylyn/tasks.xml.zip b/workspace/.metadata/.mylyn/tasks.xml.zip new file mode 100644 index 0000000..c3c8bb0 Binary files /dev/null and b/workspace/.metadata/.mylyn/tasks.xml.zip differ diff --git a/workspace/.metadata/version.ini b/workspace/.metadata/version.ini new file mode 100644 index 0000000..d83a68f --- /dev/null +++ b/workspace/.metadata/version.ini @@ -0,0 +1,3 @@ +#Fri Feb 26 22:38:10 KST 2016 +org.eclipse.core.runtime=2 +org.eclipse.platform=4.5.1.v20150904-0015 diff --git a/workspace/ch01/.classpath b/workspace/ch01/.classpath new file mode 100644 index 0000000..fceb480 --- /dev/null +++ b/workspace/ch01/.classpath @@ -0,0 +1,6 @@ + + + + + + diff --git a/workspace/ch01/.project b/workspace/ch01/.project new file mode 100644 index 0000000..d7c3cd9 --- /dev/null +++ b/workspace/ch01/.project @@ -0,0 +1,17 @@ + + + ch01 + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/workspace/ch01/.settings/org.eclipse.jdt.core.prefs b/workspace/ch01/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..3a21537 --- /dev/null +++ b/workspace/ch01/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,11 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/workspace/ch01/src/Hello.java b/workspace/ch01/src/Hello.java new file mode 100644 index 0000000..2dabeb9 --- /dev/null +++ b/workspace/ch01/src/Hello.java @@ -0,0 +1,7 @@ + +public class Hello { + public static void main(String[] args) { + // TODO Auto-generated method stub + System.out.println("Hello, world."); + } +} diff --git a/workspace/ch02/.classpath b/workspace/ch02/.classpath new file mode 100644 index 0000000..fceb480 --- /dev/null +++ b/workspace/ch02/.classpath @@ -0,0 +1,6 @@ + + + + + + diff --git a/workspace/ch02/.project b/workspace/ch02/.project new file mode 100644 index 0000000..b59d2a9 --- /dev/null +++ b/workspace/ch02/.project @@ -0,0 +1,17 @@ + + + ch02 + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/workspace/ch02/.settings/org.eclipse.jdt.core.prefs b/workspace/ch02/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..3a21537 --- /dev/null +++ b/workspace/ch02/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,11 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/workspace/ch02/src/CastingEx1.java b/workspace/ch02/src/CastingEx1.java new file mode 100644 index 0000000..6178ae2 --- /dev/null +++ b/workspace/ch02/src/CastingEx1.java @@ -0,0 +1,9 @@ +class CastingEx1 { + public static void main(String[] args) { + double d = 85.4; + int score = (int)d; + + System.out.println("score="+score); + System.out.println("d="+d); + } +} diff --git a/workspace/ch02/src/CastingEx2.java b/workspace/ch02/src/CastingEx2.java new file mode 100644 index 0000000..0cfbd61 --- /dev/null +++ b/workspace/ch02/src/CastingEx2.java @@ -0,0 +1,21 @@ +class CastingEx2 { + public static void main(String[] args) { + int i = 10; + byte b = (byte)i; + System.out.printf("[int -> byte] i=%d -> b=%d%n", i, b); + + i = 300; + b = (byte)i; + System.out.printf("[int -> byte] i=%d -> b=%d%n", i, b); + + b = 10; + i = (int)b; + System.out.printf("[byte -> int] b=%d -> i=%d%n", b, i); + + b = -2; + i = (int)b; + System.out.printf("[byte -> int] b=%d -> i=%d%n", b, i); + + System.out.println("i="+Integer.toBinaryString(i)); + } +} diff --git a/workspace/ch02/src/CastingEx3.java b/workspace/ch02/src/CastingEx3.java new file mode 100644 index 0000000..d392d2d --- /dev/null +++ b/workspace/ch02/src/CastingEx3.java @@ -0,0 +1,11 @@ +class CastingEx3 { + public static void main(String[] args) { + float f = 9.1234567f; + double d = 9.1234567; + double d2 = (double)f; + + System.out.printf("f =%20.18f\n", f); + System.out.printf("d =%20.18f\n", d); + System.out.printf("d2=%20.18f\n", d2); + } +} diff --git a/workspace/ch02/src/CastingEx4.java b/workspace/ch02/src/CastingEx4.java new file mode 100644 index 0000000..e7d3d5f --- /dev/null +++ b/workspace/ch02/src/CastingEx4.java @@ -0,0 +1,18 @@ +class CastingEx4 { + public static void main(String[] args) { + int i = 91234567; // 8ÀÚ¸®ÀÇ 10Áø¼ö + float f = (float)i; // int¸¦ float·Î Çüº¯È¯ + int i2 = (int)f; // float¸¦ ´Ù½Ã int·Î Çüº¯È¯ + + double d = (double)i; // int¸¦ double·Î Çüº¯È¯ + int i3 = (int)d; // doubleÀ» ´Ù½Ã int·Î Çüº¯È¯ + + float f2 = 1.666f; + int i4 = (int)f2; + + System.out.printf("i=%d\n", i); + System.out.printf("f=%f i2=%d\n", f, i2); + System.out.printf("d=%f i3=%d\n", d, i3); + System.out.printf("(int)%f=%d\n", f2, i4); + } +} diff --git a/workspace/ch02/src/CharToCode.java b/workspace/ch02/src/CharToCode.java new file mode 100644 index 0000000..cf6d45c --- /dev/null +++ b/workspace/ch02/src/CharToCode.java @@ -0,0 +1,11 @@ +class CharToCode { + public static void main(String[] args) { + char ch = 'A'; // char ch = 65; + int code = (int)ch; // ch¿¡ ÀúÀåµÈ °ªÀ» intŸÀÔÀ¸·Î º¯È¯ÇÏ¿© ÀúÀåÇÑ´Ù. + + System.out.printf("%c=%d(%#X)%n", ch, code, code); + + char hch = '°¡'; // char hch = 0xAC00; + System.out.printf("%c=%d(%#X)%n", hch, (int)hch, (int)hch); + } +} diff --git a/workspace/ch02/src/FloatEx1.java b/workspace/ch02/src/FloatEx1.java new file mode 100644 index 0000000..13a672a --- /dev/null +++ b/workspace/ch02/src/FloatEx1.java @@ -0,0 +1,13 @@ +class FloatEx1 { + public static void main(String[] args) { + float f = 9.12345678901234567890f; + float f2 = 1.2345678901234567890f; + double d = 9.12345678901234567890d; + + System.out.printf(" 123456789012345678901234%n"); + System.out.printf("f : %f%n", f); // ¼Ò¼öÁ¡ ÀÌÇÏ 6°ÀÚ¸®±îÁö Ãâ·Â. + System.out.printf("f : %24.20f%n", f); + System.out.printf("f2 : %24.20f%n", f2); + System.out.printf("d : %24.20f%n", d); + } +} diff --git a/workspace/ch02/src/FloatToBinEx.java b/workspace/ch02/src/FloatToBinEx.java new file mode 100644 index 0000000..4e001d6 --- /dev/null +++ b/workspace/ch02/src/FloatToBinEx.java @@ -0,0 +1,9 @@ +class FloatToBinEx { + public static void main(String args[]) { + float f = -9.1234567f; + int i = Float.floatToIntBits(f); + + System.out.printf("%f%n", f); + System.out.printf("%X%n", i); // 16Áø¼ö·Î Ãâ·Â + } // mainÀÇ ³¡ +} diff --git a/workspace/ch02/src/OverflowEx.java b/workspace/ch02/src/OverflowEx.java new file mode 100644 index 0000000..bc84538 --- /dev/null +++ b/workspace/ch02/src/OverflowEx.java @@ -0,0 +1,17 @@ +class OverflowEx { + public static void main(String[] args) { + short sMin = -32768; + short sMax = 32767; + char cMin = 0; + char cMax = 65535; + + System.out.println("sMin = " + sMin); + System.out.println("sMin-1= " + (short)(sMin-1)); + System.out.println("sMax = " + sMax); + System.out.println("sMax+1= " + (short)(sMax+1)); + System.out.println("cMin = " + (int)cMin); + System.out.println("cMin-1= " + (int)--cMin); + System.out.println("cMax = " + (int)cMax); + System.out.println("cMax+1= " + (int)++cMax); + } +} diff --git a/workspace/ch02/src/PrintfEx1.java b/workspace/ch02/src/PrintfEx1.java new file mode 100644 index 0000000..f19d9cd --- /dev/null +++ b/workspace/ch02/src/PrintfEx1.java @@ -0,0 +1,27 @@ +class PrintfEx1 { + public static void main(String[] args) { + byte b = 1; + short s = 2; + char c = 'A'; + + int finger = 10; + long big = 100_000_000_000L; + long hex = 0xFFFF_FFFF_FFFF_FFFFL ; // long hex = 0xFFFFFFFFFFFFFFFFL; + + int octNum = 010; // 8Áø¼ö 10, 10Áø¼ö·Î´Â 8 + int hexNum = 0x10; // 16Áø¼ö 10, 10Áø¼ö·Î´Â 16 + int binNum = 0b10; // 2Áø¼ö 10, 10Áø¼ö·Î´Â 2 + + System.out.printf("b=%d%n", b); + System.out.printf("s=%d%n", s); + System.out.printf("c=%c, %d %n", c, (int)c); + System.out.printf("finger=[%5d]%n", finger); + System.out.printf("finger=[%-5d]%n", finger); + System.out.printf("finger=[%05d]%n", finger); + System.out.printf("big=%d%n", big); + System.out.printf("hex=%#x%n", hex); // '#'Àº Á¢µÎ»ç(16Áø¼ö 0x, 8Áø¼ö 0) + System.out.printf("octNum=%o, %d%n", octNum, octNum); + System.out.printf("hexNum=%x, %d%n", hexNum, hexNum); + System.out.printf("binNum=%s, %d%n", Integer.toBinaryString(binNum), binNum); + } +} diff --git a/workspace/ch02/src/PrintfEx2.java b/workspace/ch02/src/PrintfEx2.java new file mode 100644 index 0000000..696a41e --- /dev/null +++ b/workspace/ch02/src/PrintfEx2.java @@ -0,0 +1,23 @@ +class PrintfEx2 { + public static void main(String[] args) { + String url = "www.codechobo.com"; + + float f1 = .10f; // 0.10, 1.0e-1 + float f2 = 1e1f; // 10.0, 1.0e1, 1.0e+1 + float f3 = 3.14e3f; + double d = 1.23456789; + + System.out.printf("f1=%f, %e, %g%n", f1, f1, f1); + System.out.printf("f2=%f, %e, %g%n", f2, f2, f2); + System.out.printf("f3=%f, %e, %g%n", f3, f3, f3); + + System.out.printf("d=%f%n", d); + System.out.printf("d=%14.10f%n", d); // Àüü 14ÀÚ¸® Áß ¼Ò¼öÁ¡ 10ÀÚ¸® + + System.out.printf("[12345678901234567890]%n"); + System.out.printf("[%s]%n", url); + System.out.printf("[%20s]%n", url); + System.out.printf("[%-20s]%n", url); // ¿À¸¥ÂÊ Á¤·Ä + System.out.printf("[%.8s]%n", url); // ¿ÞÂÊ¿¡¼­ 8±ÛÀÚ¸¸ Ãâ·Â + } +} diff --git a/workspace/ch02/src/ScannerEx.java b/workspace/ch02/src/ScannerEx.java new file mode 100644 index 0000000..e57d031 --- /dev/null +++ b/workspace/ch02/src/ScannerEx.java @@ -0,0 +1,15 @@ +import java.util.*; // Scanner¸¦ »ç¿ëÇϱâ À§ÇØ Ãß°¡ + +class ScannerEx { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + + System.out.print("µÎÀÚ¸® Á¤¼ö¸¦ Çϳª ÀÔ·ÂÇØÁÖ¼¼¿ä.>"); + + String input = scanner.nextLine(); + int num = Integer.parseInt(input); // ÀԷ¹ÞÀº ¹®ÀÚ¿­À» ¼ýÀÚ·Î º¯È¯ + + System.out.println("ÀԷ³»¿ë :"+input); + System.out.printf("num=%d%n", num); + } +} diff --git a/workspace/ch02/src/SpecialCharEx.java b/workspace/ch02/src/SpecialCharEx.java new file mode 100644 index 0000000..a5a4702 --- /dev/null +++ b/workspace/ch02/src/SpecialCharEx.java @@ -0,0 +1,9 @@ +class SpecialCharEx { + public static void main(String[] args) { + System.out.println('\''); // '''ó·³ ÇÒ ¼ö ¾ø´Ù. + System.out.println("abc\t123\b456"); // \b¿¡ ÀÇÇØ 3ÀÌ Áö¿öÁø´Ù. + System.out.println('\n'); // °³Çà(new line)¹®ÀÚ Ãâ·ÂÇÏ°í °³Çà + System.out.println("\"Hello\""); // Å«µû¿ÈÇ¥¸¦ Ãâ·ÂÇÏ·Á¸é ÀÌ·¸°Ô ÇÑ´Ù. + System.out.println("c:\\"); + } +} diff --git a/workspace/ch02/src/StringEx.java b/workspace/ch02/src/StringEx.java new file mode 100644 index 0000000..b9e0d93 --- /dev/null +++ b/workspace/ch02/src/StringEx.java @@ -0,0 +1,16 @@ +class StringEx { + public static void main(String[] args) { + String name = "Ja" + "va"; + String str = name + 8.0; + + System.out.println(name); + System.out.println(str); + System.out.println(7 + " "); + System.out.println(" " + 7); + System.out.println(7 + ""); + System.out.println("" + 7); + System.out.println("" + ""); + System.out.println(7 + 7 + ""); + System.out.println("" + 7 + 7); + } +} diff --git a/workspace/ch02/src/VarEx1.java b/workspace/ch02/src/VarEx1.java new file mode 100644 index 0000000..66b4d6d --- /dev/null +++ b/workspace/ch02/src/VarEx1.java @@ -0,0 +1,15 @@ +class VarEx1 { + public static void main(String[] args) { + int year = 0; + int age = 14; + + System.out.println(year); + System.out.println(age); + + year = age + 2000; // º¯¼ö ageÀÇ °ª¿¡ 2000À» ´õÇؼ­ º¯¼ö year¿¡ ÀúÀå + age = age + 1; // º¯¼ö age¿¡ ÀúÀåµÈ °ªÀ» 1Áõ°¡½ÃŲ´Ù. + + System.out.println(year); + System.out.println(age); + } +} diff --git a/workspace/ch02/src/VarEx2.java b/workspace/ch02/src/VarEx2.java new file mode 100644 index 0000000..fe8e57f --- /dev/null +++ b/workspace/ch02/src/VarEx2.java @@ -0,0 +1,15 @@ +class VarEx2 { + public static void main(String[] args) { + int x = 10; + int y = 20; + int tmp = 0; + + System.out.println("x:"+ x + " y:" + y); + + tmp = x; + x = y; + y = tmp; + + System.out.println("x:"+ x + " y:" + y); + } +} diff --git a/workspace/ch03/.classpath b/workspace/ch03/.classpath new file mode 100644 index 0000000..fceb480 --- /dev/null +++ b/workspace/ch03/.classpath @@ -0,0 +1,6 @@ + + + + + + diff --git a/workspace/ch03/.project b/workspace/ch03/.project new file mode 100644 index 0000000..2867fec --- /dev/null +++ b/workspace/ch03/.project @@ -0,0 +1,17 @@ + + + ch03 + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/workspace/ch03/.settings/org.eclipse.jdt.core.prefs b/workspace/ch03/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..3a21537 --- /dev/null +++ b/workspace/ch03/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,11 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/workspace/ch03/src/OperatorEx01.java b/workspace/ch03/src/OperatorEx01.java new file mode 100644 index 0000000..4a904a1 --- /dev/null +++ b/workspace/ch03/src/OperatorEx01.java @@ -0,0 +1,11 @@ +class OperatorEx01 { + public static void main(String args[]) { + int i=5; + i++; // i=i+1;°ú °°Àº ÀǹÌÀÌ´Ù. ++i;·Î ¹Ù²ã ½áµµ °á°ú´Â °°´Ù. + System.out.println(i); + + i=5; // °á°ú¸¦ ºñ±³Çϱâ À§ÇØ i°ªÀ» ´Ù½Ã 5·Î º¯°æ. + ++i; + System.out.println(i); + } +} diff --git a/workspace/ch03/src/OperatorEx02.java b/workspace/ch03/src/OperatorEx02.java new file mode 100644 index 0000000..b8d943d --- /dev/null +++ b/workspace/ch03/src/OperatorEx02.java @@ -0,0 +1,14 @@ +class OperatorEx02 { + public static void main(String args[]) { + int i=5, j=0; + + j = i++; + System.out.println("j=i++; ½ÇÇà ÈÄ, i=" + i +", j="+ j); + + i=5; // °á°ú¸¦ ºñ±³Çϱâ À§ÇØ, i¿Í jÀÇ °ªÀ» ´Ù½Ã 5¿Í 0À¸·Î º¯°æ + j=0; + + j = ++i; + System.out.println("j=++i; ½ÇÇà ÈÄ, i=" + i +", j="+ j); + } +} diff --git a/workspace/ch03/src/OperatorEx03.java b/workspace/ch03/src/OperatorEx03.java new file mode 100644 index 0000000..d2782f2 --- /dev/null +++ b/workspace/ch03/src/OperatorEx03.java @@ -0,0 +1,9 @@ +class OperatorEx03 { + public static void main(String args[]) { + int i=5, j=5; + + System.out.println(i++); + System.out.println(++j); + System.out.println("i = " + i + ", j = " +j); + } +} diff --git a/workspace/ch03/src/OperatorEx04.java b/workspace/ch03/src/OperatorEx04.java new file mode 100644 index 0000000..ce20f78 --- /dev/null +++ b/workspace/ch03/src/OperatorEx04.java @@ -0,0 +1,11 @@ +class OperatorEx04 { + public static void main(String[] args) { + int i = -10; + i = +i; + System.out.println(i); + + i=-10; + i = -i; + System.out.println(i); + } +} diff --git a/workspace/ch03/src/OperatorEx05.java b/workspace/ch03/src/OperatorEx05.java new file mode 100644 index 0000000..5479654 --- /dev/null +++ b/workspace/ch03/src/OperatorEx05.java @@ -0,0 +1,12 @@ +class OperatorEx05 { + public static void main(String args[]) { + int a = 10; + int b = 4; + + 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 / %f = %f%n", a, (float)b, a / (float)b); + } +} diff --git a/workspace/ch03/src/OperatorEx06.java b/workspace/ch03/src/OperatorEx06.java new file mode 100644 index 0000000..04ed29c --- /dev/null +++ b/workspace/ch03/src/OperatorEx06.java @@ -0,0 +1,9 @@ +class OperatorEx06 { + public static void main(String[] args) { + byte a = 10; + byte b = 20; + byte c = a + b; + + System.out.println(c); + } +} diff --git a/workspace/ch03/src/OperatorEx07.java b/workspace/ch03/src/OperatorEx07.java new file mode 100644 index 0000000..c26731b --- /dev/null +++ b/workspace/ch03/src/OperatorEx07.java @@ -0,0 +1,9 @@ +class OperatorEx07 { + public static void main(String[] args) { + byte a = 10; + byte b = 30; + byte c = (byte)(a * b); + + System.out.println(c); + } +} diff --git a/workspace/ch03/src/OperatorEx08.java b/workspace/ch03/src/OperatorEx08.java new file mode 100644 index 0000000..e18c92f --- /dev/null +++ b/workspace/ch03/src/OperatorEx08.java @@ -0,0 +1,10 @@ +class OperatorEx08 { + public static void main(String args[]) { + int a = 1000000; // 1,000,000 1¹é¸¸ + int b = 2000000; // 2,000,000 2¹é¸¸ + + long c = a * b; // a * b = 2,000,000,000,000 ? + + System.out.println(c); + } +} diff --git a/workspace/ch03/src/OperatorEx09.java b/workspace/ch03/src/OperatorEx09.java new file mode 100644 index 0000000..46aad0d --- /dev/null +++ b/workspace/ch03/src/OperatorEx09.java @@ -0,0 +1,9 @@ +class OperatorEx09 { + public static void main(String args[]) { + long a = 1000000 * 1000000; + long b = 1000000 * 1000000L; + + System.out.println("a="+a); + System.out.println("b="+b); + } +} diff --git a/workspace/ch03/src/OperatorEx10.java b/workspace/ch03/src/OperatorEx10.java new file mode 100644 index 0000000..828928a --- /dev/null +++ b/workspace/ch03/src/OperatorEx10.java @@ -0,0 +1,11 @@ +class OperatorEx10 { + public static void main(String args[]) { + int a = 1000000; + + int result1 = a * a / a; // 1000000 * 1000000 / 1000000 + int result2 = a / a * a; // 1000000 / 1000000 * 1000000 + + System.out.printf("%d * %d / %d = %d%n", a, a, a, result1); + System.out.printf("%d / %d * %d = %d%n", a, a, a, result2); + } +} diff --git a/workspace/ch03/src/OperatorEx11.java b/workspace/ch03/src/OperatorEx11.java new file mode 100644 index 0000000..21a0e98 --- /dev/null +++ b/workspace/ch03/src/OperatorEx11.java @@ -0,0 +1,16 @@ +class OperatorEx11 { + public static void main(String args[]) { + char a = 'a'; + char d = 'd'; + + char zero = '0'; + char two = '2'; + + System.out.printf("'%c' - '%c' = %d%n", d, a, d - a); // 'd' - 'a' = 3 + System.out.printf("'%c' - '%c' = %d%n", two, zero, two - zero); + System.out.printf("'%c'=%d%n", a, (int)a); + System.out.printf("'%c'=%d%n", d, (int)d); + System.out.printf("'%c'=%d%n", zero, (int)zero); + System.out.printf("'%c'=%d%n", two, (int)two); + } +} diff --git a/workspace/ch03/src/OperatorEx12.java b/workspace/ch03/src/OperatorEx12.java new file mode 100644 index 0000000..3de2f9d --- /dev/null +++ b/workspace/ch03/src/OperatorEx12.java @@ -0,0 +1,17 @@ +class OperatorEx12 { + public static void main(String[] args) { + char c1 = 'a'; // c1¿¡´Â ¹®ÀÚ 'a'ÀÇ Äڵ尪ÀÎ 97ÀÌ ÀúÀåµÈ´Ù. + char c2 = c1; // c1¿¡ ÀúÀåµÇ¾î ÀÖ´Â °ªÀÌ c2¿¡ ÀúÀåµÈ´Ù. + char c3 =' '; // c3¸¦ °ø¹éÀ¸·Î ÃʱâÈ­ ÇÑ´Ù. + + int i = c1 + 1; // 'a'+1 ¡æ 97+1 ¡æ 98 + + c3 = (char)(c1 + 1); + c2++; + c2++; + + System.out.println("i=" + i); + System.out.println("c2=" + c2); + System.out.println("c3=" + c3); + } +} diff --git a/workspace/ch03/src/OperatorEx13.java b/workspace/ch03/src/OperatorEx13.java new file mode 100644 index 0000000..92f5cab --- /dev/null +++ b/workspace/ch03/src/OperatorEx13.java @@ -0,0 +1,10 @@ +class OperatorEx13 { + public static void main(String[] args) { + char c1 = 'a'; + +// char c2 = c1+1; // ¶óÀÎ 5 : ÄÄÆÄÀÏ ¿¡·¯¹ß»ý!!! + char c2 = 'a'+1; // ¶óÀÎ 6 : ÄÄÆÄÀÏ ¿¡·¯¾øÀ½ + + System.out.println(c2); + } +} diff --git a/workspace/ch03/src/OperatorEx14.java b/workspace/ch03/src/OperatorEx14.java new file mode 100644 index 0000000..964593e --- /dev/null +++ b/workspace/ch03/src/OperatorEx14.java @@ -0,0 +1,23 @@ +class OperatorEx14 { + public static void main(String[] args) { + char c = 'a'; + for(int i=0; i<26; i++) { // ºí·°{} ¾ÈÀÇ ¹®ÀåÀ» 26¹øÀ» ¹Ýº¹ÇÑ´Ù. + System.out.print(c++); //'a'ºÎÅÍ 26°³ÀÇ ¹®ÀÚ¸¦ Ãâ·ÂÇÑ´Ù. + } + + System.out.println(); // ÁٹٲÞÀ» ÇÑ´Ù. + + c = 'A'; + for(int i=0; i<26; i++) { // ºí·°{} ¾ÈÀÇ ¹®ÀåÀ» 26¹øÀ» ¹Ýº¹ÇÑ´Ù. + System.out.print(c++); //'A'ºÎÅÍ 26°³ÀÇ ¹®ÀÚ¸¦ Ãâ·ÂÇÑ´Ù. + } + + System.out.println(); + + c='0'; + for(int i=0; i<10; i++) { // ºí·°{} ¾ÈÀÇ ¹®ÀåÀ» 10¹øÀ» ¹Ýº¹ÇÑ´Ù. + System.out.print(c++); //'0'ºÎÅÍ 10°³ÀÇ ¹®ÀÚ¸¦ Ãâ·ÂÇÑ´Ù. + } + System.out.println(); + } +} diff --git a/workspace/ch03/src/OperatorEx15.java b/workspace/ch03/src/OperatorEx15.java new file mode 100644 index 0000000..ca7d33a --- /dev/null +++ b/workspace/ch03/src/OperatorEx15.java @@ -0,0 +1,8 @@ +class OperatorEx15 { + public static void main(String[] args) { + char lowerCase = 'a'; + char upperCase = (char)(lowerCase - 32); + + System.out.println(upperCase); + } +} diff --git a/workspace/ch03/src/OperatorEx16.java b/workspace/ch03/src/OperatorEx16.java new file mode 100644 index 0000000..ec85686 --- /dev/null +++ b/workspace/ch03/src/OperatorEx16.java @@ -0,0 +1,8 @@ +class OperatorEx16 { + public static void main(String[] args) { + float pi = 3.141592f; + float shortPi = (int)(pi * 1000) / 1000f; + + System.out.println(shortPi); + } +} diff --git a/workspace/ch03/src/OperatorEx17.java b/workspace/ch03/src/OperatorEx17.java new file mode 100644 index 0000000..3a6bdcd --- /dev/null +++ b/workspace/ch03/src/OperatorEx17.java @@ -0,0 +1,8 @@ +class OperatorEx17 { + public static void main(String args[]) { + double pi = 3.141592; + double shortPi = (int)(pi * 1000 + 0.5) / 1000.0; + + System.out.println(shortPi); + } +} diff --git a/workspace/ch03/src/OperatorEx18.java b/workspace/ch03/src/OperatorEx18.java new file mode 100644 index 0000000..0eb7b63 --- /dev/null +++ b/workspace/ch03/src/OperatorEx18.java @@ -0,0 +1,8 @@ +class OperatorEx18 { + public static void main(String args[]) { + double pi = 3.141592; + double shortPi = Math.round(pi * 1000) / 1000.0; + + System.out.println(shortPi); + } +} diff --git a/workspace/ch03/src/OperatorEx19.java b/workspace/ch03/src/OperatorEx19.java new file mode 100644 index 0000000..548d084 --- /dev/null +++ b/workspace/ch03/src/OperatorEx19.java @@ -0,0 +1,9 @@ +class OperatorEx19 { + public static void main(String args[]) { + int x = 10; + int y = 8; + + System.out.printf("%dÀ» %d·Î ³ª´©¸é, %n", x, y); + System.out.printf("¸òÀº %dÀÌ°í, ³ª¸ÓÁö´Â %dÀÔ´Ï´Ù.%n", x / y, x % y); + } +} diff --git a/workspace/ch03/src/OperatorEx20.java b/workspace/ch03/src/OperatorEx20.java new file mode 100644 index 0000000..4f0a589 --- /dev/null +++ b/workspace/ch03/src/OperatorEx20.java @@ -0,0 +1,8 @@ + +class OperatorEx20 { + public static void main(String[] args) { + System.out.println(-10%8); + System.out.println(10%-8); + System.out.println(-10%-8); + } +} diff --git a/workspace/ch03/src/OperatorEx21.java b/workspace/ch03/src/OperatorEx21.java new file mode 100644 index 0000000..6ef93be --- /dev/null +++ b/workspace/ch03/src/OperatorEx21.java @@ -0,0 +1,10 @@ +class OperatorEx21 { + public static void main(String args[]) { + System.out.printf("10 == 10.0f \t %b%n", 10==10.0f); + System.out.printf("'0'== 0 \t %b%n", '0'== 0); + System.out.printf("'\\0'== 0 \t %b%n", '\0'== 0); + System.out.printf("'A'== 65 \t %b%n", 'A'== 65); + System.out.printf("'A' > 'B' \t %b%n", 'A' > 'B'); + System.out.printf("'A'+1 != 'B' \t %b%n", 'A'+1 != 'B'); + } +} diff --git a/workspace/ch03/src/OperatorEx22.java b/workspace/ch03/src/OperatorEx22.java new file mode 100644 index 0000000..a61d54d --- /dev/null +++ b/workspace/ch03/src/OperatorEx22.java @@ -0,0 +1,17 @@ +class OperatorEx22 { + public static void main(String args[]) { + float f = 0.1f; + double d = 0.1; + double d2 = (double)f; + + System.out.printf("10.0==10.0f %b%n", 10.0==10.0f); + System.out.printf("0.1==0.1f %b%n", 0.1==0.1f); + System.out.printf("f =%19.17f%n", f); + System.out.printf("d =%19.17f%n", d); + System.out.printf("d2=%19.17f%n", d2); + System.out.printf("d==f %b%n", d==f); + System.out.printf("d==d2 %b%n", d==d2); + System.out.printf("d2==f %b%n", d2==f); + System.out.printf("(float)d==f %b%n", (float)d==f); + } +} diff --git a/workspace/ch03/src/OperatorEx23.java b/workspace/ch03/src/OperatorEx23.java new file mode 100644 index 0000000..594e74f --- /dev/null +++ b/workspace/ch03/src/OperatorEx23.java @@ -0,0 +1,14 @@ +class OperatorEx23 { + public static void main(String[] args) { + String str1 = "abc"; + String str2 = new String("abc"); + + System.out.printf("\"abc\"==\"abc\" ? %b%n", "abc"=="abc"); + System.out.printf(" str1==\"abc\" ? %b%n", str1=="abc"); + System.out.printf(" str2==\"abc\" ? %b%n", str2=="abc"); + System.out.printf("str1.equals(\"abc\") ? %b%n", str1.equals("abc")); + System.out.printf("str2.equals(\"abc\") ? %b%n", str2.equals("abc")); + System.out.printf("str2.equals(\"ABC\") ? %b%n", str2.equals("ABC")); + System.out.printf("str2.equalsIgnoreCase(\"ABC\") ? %b%n", str2.equalsIgnoreCase("ABC")); + } +} diff --git a/workspace/ch03/src/OperatorEx24.java b/workspace/ch03/src/OperatorEx24.java new file mode 100644 index 0000000..edea194 --- /dev/null +++ b/workspace/ch03/src/OperatorEx24.java @@ -0,0 +1,25 @@ +class OperatorEx24 { + public static void main(String args[]) { + int x = 0; + char ch = ' '; + + x = 15; + System.out.printf("x=%2d, 10 < x && x < 20 =%b%n", x, 10 < x && x < 20); + + x = 6; + System.out.printf("x=%2d, x%%2==0 || x%%3==0 && x%%6!=0 =%b%n", x, x%2==0||x%3==0&&x%6!=0); + System.out.printf("x=%2d, (x%%2==0 || x%%3==0) && x%%6!=0 =%b%n", x,(x%2==0||x%3==0)&&x%6!=0); + + ch='1'; + System.out.printf("ch='%c', '0' <= ch && ch <= '9' =%b%n", ch, '0' <= ch && ch <='9'); + + ch='a'; + System.out.printf("ch='%c', 'a' <= ch && ch <= 'z' =%b%n", ch, 'a' <= ch && ch <='z'); + + ch='A'; + System.out.printf("ch='%c', 'A' <= ch && ch <= 'Z' =%b%n", ch, 'A' <= ch && ch <='Z'); + + ch='q'; + System.out.printf("ch='%c', ch=='q' || ch=='Q' =%b%n", ch, ch=='q' || ch=='Q'); + } +} diff --git a/workspace/ch03/src/OperatorEx25.java b/workspace/ch03/src/OperatorEx25.java new file mode 100644 index 0000000..b875843 --- /dev/null +++ b/workspace/ch03/src/OperatorEx25.java @@ -0,0 +1,21 @@ +import java.util.*; // ScannerŬ·¡½º¸¦ »ç¿ëÇϱâ À§ÇØ Ãß°¡ + +class OperatorEx25 { + public static void main(String args[]) { + Scanner scanner = new Scanner(System.in); + char ch = ' '; + + System.out.printf("¹®ÀÚ¸¦ Çϳª ÀÔ·ÂÇϼ¼¿ä.>"); + + String input = scanner.nextLine(); + ch = input.charAt(0); + + if('0'<= ch && ch <= '9') { + System.out.printf("ÀÔ·ÂÇϽŠ¹®ÀÚ´Â ¼ýÀÚÀÔ´Ï´Ù.%n"); + } + + if(('a'<= ch && ch <= 'z') || ('A'<= ch && ch <= 'Z')) { + System.out.printf("ÀÔ·ÂÇϽŠ¹®ÀÚ´Â ¿µ¹®ÀÚÀÔ´Ï´Ù.%n"); + } + } // main +} diff --git a/workspace/ch03/src/OperatorEx26.java b/workspace/ch03/src/OperatorEx26.java new file mode 100644 index 0000000..9a7a527 --- /dev/null +++ b/workspace/ch03/src/OperatorEx26.java @@ -0,0 +1,12 @@ +class OperatorEx26 { + public static void main(String[] args) { + int a = 5; + int b = 0; + + System.out.printf("a=%d, b=%d%n", a, b); + System.out.printf("a!=0 || ++b!=0 = %b%n", a!=0 || ++b!=0); + System.out.printf("a=%d, b=%d\n", a, b); + System.out.printf("a==0 && ++b!=0 = %b%n", a==0 && ++b!=0); + System.out.printf("a=%d, b=%d%n", a, b); + } // mainÀÇ ³¡ +} diff --git a/workspace/ch03/src/OperatorEx27.java b/workspace/ch03/src/OperatorEx27.java new file mode 100644 index 0000000..52b5b89 --- /dev/null +++ b/workspace/ch03/src/OperatorEx27.java @@ -0,0 +1,17 @@ +class OperatorEx27 { + public static void main(String[] args) { + boolean b = true; + char ch = 'C'; + + System.out.printf("b=%b%n", b); + System.out.printf("!b=%b%n", !b); + System.out.printf("!!b=%b%n", !!b); + System.out.printf("!!!b=%b%n", !!!b); + System.out.println(); + + System.out.printf("ch=%c%n", ch); + System.out.printf("ch < 'a' || ch > 'z'=%b%n", ch < 'a' || ch > 'z'); + System.out.printf("!('a'<=ch && ch<='z')=%b%n", !('a'<= ch && ch<='z')); + System.out.printf(" 'a'<=ch && ch<='z' =%b%n", 'a'<=ch && ch<='z'); + } // mainÀÇ ³¡ +} diff --git a/workspace/ch03/src/OperatorEx28.java b/workspace/ch03/src/OperatorEx28.java new file mode 100644 index 0000000..40e3b25 --- /dev/null +++ b/workspace/ch03/src/OperatorEx28.java @@ -0,0 +1,21 @@ +class OperatorEx28 { + public static void main(String[] args) { + int x = 0xAB; + int y = 0xF; + + System.out.printf("x = %#X \t\t%s%n", x, toBinaryString(x)); + System.out.printf("y = %#X \t\t%s%n", x, toBinaryString(y)); + System.out.printf("%#X | %#X = %#X \t%s%n", x, y, x | y, toBinaryString(x | y)); + System.out.printf("%#X & %#X = %#X \t%s%n", x, y, x & y, toBinaryString(x & y)); + System.out.printf("%#X ^ %#X = %#X \t%s%n", x, y, x ^ y, toBinaryString(x ^ y)); + System.out.printf("%#X ^ %#X ^ %#X = %#X %s%n", x, y, y, x ^ y ^ y, toBinaryString(x ^ y ^ y)); + } // mainÀÇ ³¡ + + // 10Áø Á¤¼ö¸¦ 2Áø¼ö·Î º¯È¯ÇÏ´Â ¸Þ¼­µå + static String toBinaryString(int x) { + String zero = "00000000000000000000000000000000"; + String tmp = zero + Integer.toBinaryString(x); + + return tmp.substring(tmp.length()-32); + } +} diff --git a/workspace/ch03/src/OperatorEx29.java b/workspace/ch03/src/OperatorEx29.java new file mode 100644 index 0000000..66491ea --- /dev/null +++ b/workspace/ch03/src/OperatorEx29.java @@ -0,0 +1,22 @@ +class OperatorEx29 { + public static void main(String[] args) { + byte p = 10; + byte n = -10; + + System.out.printf(" p =%d \t%s%n", p, toBinaryString(p)); + System.out.printf("~p =%d \t%s%n", ~p, toBinaryString(~p)); + System.out.printf("~p+1=%d \t%s%n", ~p+1, toBinaryString(~p+1)); + System.out.printf("~~p =%d \t%s%n", ~~p, toBinaryString(~~p)); + System.out.println(); + System.out.printf(" n =%d%n", n); + System.out.printf("~(n-1)=%d%n", ~(n-1)); + } // mainÀÇ ³¡ + + // 10Áø Á¤¼ö¸¦ 2Áø¼ö·Î º¯È¯ÇÏ´Â ¸Þ¼­µå + static String toBinaryString(int x) { + String zero = "00000000000000000000000000000000"; + String tmp = zero + Integer.toBinaryString(x); + + return tmp.substring(tmp.length()-32); + } +} diff --git a/workspace/ch03/src/OperatorEx30.java b/workspace/ch03/src/OperatorEx30.java new file mode 100644 index 0000000..c1a60f0 --- /dev/null +++ b/workspace/ch03/src/OperatorEx30.java @@ -0,0 +1,36 @@ +class OperatorEx30 { + public static void main(String[] args) { + int dec = 8; + + System.out.printf("%d >> %d = %4d \t%s%n", dec, 0, dec >> 0, toBinaryString(dec >> 0)); + System.out.printf("%d >> %d = %4d \t%s%n", dec, 1, dec >> 1, toBinaryString(dec >> 1)); + System.out.printf("%d >> %d = %4d \t%s%n", dec, 2, dec >> 2, toBinaryString(dec >> 2)); + + System.out.printf("%d << %d = %4d \t%s%n", dec, 0, dec << 0, toBinaryString(dec << 0)); + System.out.printf("%d << %d = %4d \t%s%n", dec, 1, dec << 1, toBinaryString(dec << 1)); + System.out.printf("%d << %d = %4d \t%s%n", dec, 2, dec << 2, toBinaryString(dec << 2)); + System.out.println(); + + dec = -8; + System.out.printf("%d >> %d = %4d \t%s%n", dec, 0, dec >> 0, toBinaryString(dec >> 0)); + System.out.printf("%d >> %d = %4d \t%s%n", dec, 1, dec >> 1, toBinaryString(dec >> 1)); + System.out.printf("%d >> %d = %4d \t%s%n", dec, 2, dec >> 2, toBinaryString(dec >> 2)); + + System.out.printf("%d << %d = %4d \t%s%n", dec, 0, dec << 0, toBinaryString(dec << 0)); + System.out.printf("%d << %d = %4d \t%s%n", dec, 1, dec << 1, toBinaryString(dec << 1)); + System.out.printf("%d << %d = %4d \t%s%n", dec, 2, dec << 2, toBinaryString(dec << 2)); + System.out.println(); + + dec = 8; + System.out.printf("%d >> %2d = %4d \t%s%n", dec, 0, dec >> 0, toBinaryString(dec << 2)); + System.out.printf("%d >> %2d = %4d \t%s%n", dec, 32, dec >> 32, toBinaryString(dec << 2)); + } // mainÀÇ ³¡ + + // 10Áø Á¤¼ö¸¦ 2Áø¼ö·Î º¯È¯ÇÏ´Â ¸Þ¼­µå + static String toBinaryString(int x) { + String zero = "00000000000000000000000000000000"; + String tmp = zero + Integer.toBinaryString(x); + + return tmp.substring(tmp.length()-32); + } +} diff --git a/workspace/ch03/src/OperatorEx31.java b/workspace/ch03/src/OperatorEx31.java new file mode 100644 index 0000000..c542b35 --- /dev/null +++ b/workspace/ch03/src/OperatorEx31.java @@ -0,0 +1,19 @@ +class OperatorEx31 { + public static void main(String[] args) { + int dec = 1234; + int hex = 0xABCD; + int mask = 0xF; + + System.out.printf("hex=%X%n", hex); + System.out.printf("%X%n", hex & mask); + + hex = hex >> 4; + System.out.printf("%X%n", hex & mask); + + hex = hex >> 4; + System.out.printf("%X%n", hex & mask); + + hex = hex >> 4; + System.out.printf("%X%n", hex & mask); + } // mainÀÇ ³¡ +} diff --git a/workspace/ch03/src/OperatorEx32.java b/workspace/ch03/src/OperatorEx32.java new file mode 100644 index 0000000..277cfc1 --- /dev/null +++ b/workspace/ch03/src/OperatorEx32.java @@ -0,0 +1,23 @@ +class OperatorEx32 { + public static void main(String args[]) { + int x, y, z; + int absX, absY, absZ; + char signX, signY, signZ; + + x = 10; + y = -5; + z = 0; + + absX = x >= 0 ? x : -x; // xÀÇ °ªÀÌ À½¼öÀ̸é, ¾ç¼ö·Î ¸¸µç´Ù. + absY = y >= 0 ? y : -y; + absZ = z >= 0 ? z : -z; + + signX = x > 0 ? '+' : ( x==0 ? ' ' : '-'); // Á¶°Ç ¿¬»êÀÚ¸¦ Áßø + signY = y > 0 ? '+' : ( y==0 ? ' ' : '-'); + signZ = z > 0 ? '+' : ( z==0 ? ' ' : '-'); + + System.out.printf("x=%c%d%n", signX, absX); + System.out.printf("y=%c%d%n", signY, absY); + System.out.printf("z=%c%d%n", signZ, absZ); + } +} diff --git a/workspace/ch04/.classpath b/workspace/ch04/.classpath new file mode 100644 index 0000000..fceb480 --- /dev/null +++ b/workspace/ch04/.classpath @@ -0,0 +1,6 @@ + + + + + + diff --git a/workspace/ch04/.project b/workspace/ch04/.project new file mode 100644 index 0000000..0f92ed5 --- /dev/null +++ b/workspace/ch04/.project @@ -0,0 +1,17 @@ + + + ch04 + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/workspace/ch04/.settings/org.eclipse.jdt.core.prefs b/workspace/ch04/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..3a21537 --- /dev/null +++ b/workspace/ch04/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,11 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/workspace/ch04/src/FlowEx01.java b/workspace/ch04/src/FlowEx01.java new file mode 100644 index 0000000..12b361e --- /dev/null +++ b/workspace/ch04/src/FlowEx01.java @@ -0,0 +1,21 @@ +class FlowEx01 { + public static void main(String[] args) { + int x= 0; + + System.out.printf("x=%d À϶§, ÂüÀÎ °ÍÀº%n", x); + + if(x==0) System.out.println("x==0"); + if(x!=0) System.out.println("x!=0"); + if(!(x==0)) System.out.println("!(x==0)"); + if(!(x!=0)) System.out.println("!(x!=0)"); + System.out.println(); + + x = 1; + System.out.printf("x=%d À϶§, ÂüÀÎ °ÍÀº%n", x); + + if(x==0) System.out.println("x==0"); + if(x!=0) System.out.println("x!=0"); + if(!(x==0)) System.out.println("!(x==0)"); + if(!(x!=0)) System.out.println("!(x!=0)"); + } +} diff --git a/workspace/ch04/src/FlowEx02.java b/workspace/ch04/src/FlowEx02.java new file mode 100644 index 0000000..6ff0d69 --- /dev/null +++ b/workspace/ch04/src/FlowEx02.java @@ -0,0 +1,21 @@ +import java.util.*; // ScannerŬ·¡½º¸¦ »ç¿ëÇϱâ À§ÇØ Ãß°¡ + +class FlowEx02 { + public static void main(String[] args) { + int input; + + System.out.print("¼ýÀÚ¸¦ Çϳª ÀÔ·ÂÇϼ¼¿ä.>"); + + Scanner scanner = new Scanner(System.in); + String tmp = scanner.nextLine(); // È­¸éÀ» ÅëÇØ ÀԷ¹ÞÀº ³»¿ëÀ» tmp¿¡ ÀúÀå + input = Integer.parseInt(tmp); // ÀԷ¹ÞÀº ¹®ÀÚ¿­(tmp)À» ¼ýÀÚ·Î º¯È¯ + + if(input==0) { + System.out.println("ÀÔ·ÂÇϽŠ¼ýÀÚ´Â 0ÀÔ´Ï´Ù."); + } + + if(input!=0) + System.out.println("ÀÔ·ÂÇϽŠ¼ýÀÚ´Â 0ÀÌ ¾Æ´Õ´Ï´Ù."); + System.out.println("ÀÔ·ÂÇϽŠ¼ýÀÚ´Â "+ input +"ÀÔ´Ï´Ù."); + } // mainÀÇ ³¡ +} diff --git a/workspace/ch04/src/FlowEx03.java b/workspace/ch04/src/FlowEx03.java new file mode 100644 index 0000000..6b0752e --- /dev/null +++ b/workspace/ch04/src/FlowEx03.java @@ -0,0 +1,19 @@ +import java.util.*; // ScannerŬ·¡½º¸¦ »ç¿ëÇϱâ À§ÇØ Ãß°¡ + +class FlowEx03 { + public static void main(String[] args) { + int input; + + System.out.print("¼ýÀÚ¸¦ Çϳª ÀÔ·ÂÇϼ¼¿ä.>"); + + Scanner scanner = new Scanner(System.in); + String tmp = scanner.nextLine(); // È­¸éÀ» ÅëÇØ ÀԷ¹ÞÀº ³»¿ëÀ» tmp¿¡ ÀúÀå + input = Integer.parseInt(tmp); // ÀԷ¹ÞÀº ¹®ÀÚ¿­(tmp)À» ¼ýÀÚ·Î º¯È¯ + + if(input==0) { + System.out.println("ÀÔ·ÂÇϽŠ¼ýÀÚ´Â 0ÀÔ´Ï´Ù."); + } else { // input!=0ÀÎ °æ¿ì + System.out.println("ÀÔ·ÂÇϽŠ¼ýÀÚ´Â 0ÀÌ ¾Æ´Õ´Ï´Ù."); + } + } // mainÀÇ ³¡ +} diff --git a/workspace/ch04/src/FlowEx04.java b/workspace/ch04/src/FlowEx04.java new file mode 100644 index 0000000..c104fd7 --- /dev/null +++ b/workspace/ch04/src/FlowEx04.java @@ -0,0 +1,25 @@ +import java.util.*; + +class FlowEx04 { + public static void main(String[] args) { + int score = 0; // Á¡¼ö¸¦ ÀúÀåÇϱâ À§ÇÑ º¯¼ö + char grade =' '; // ÇÐÁ¡À» ÀúÀåÇϱâ À§ÇÑ º¯¼ö. °ø¹éÀ¸·Î ÃʱâÈ­ÇÑ´Ù. + + System.out.print("Á¡¼ö¸¦ ÀÔ·ÂÇϼ¼¿ä.>"); + Scanner scanner = new Scanner(System.in); + String tmp = scanner.nextLine(); // È­¸éÀ» ÅëÇØ ÀԷ¹ÞÀº ³»¿ëÀ» tmp¿¡ ÀúÀå + score = Integer.parseInt(tmp); // ÀԷ¹ÞÀº ¹®ÀÚ¿­(tmp)À» ¼ýÀÚ·Î º¯È¯ + + if (score >= 90) { // score°¡ 90Á¡ º¸´Ù °°°Å³ª Å©¸é AÇÐÁ¡ + grade = 'A'; + } else if (score >=80) { // score°¡ 80Á¡ º¸´Ù °°°Å³ª Å©¸é BÇÐÁ¡ + grade = 'B'; + } else if (score >=70) { // score°¡ 70Á¡ º¸´Ù °°°Å³ª Å©¸é CÇÐÁ¡ + grade = 'C'; + } else { // ³ª¸ÓÁö´Â DÇÐÁ¡ + grade = 'D'; + } + + System.out.println("´ç½ÅÀÇ ÇÐÁ¡Àº "+ grade +"ÀÔ´Ï´Ù."); + } +} diff --git a/workspace/ch04/src/FlowEx05.java b/workspace/ch04/src/FlowEx05.java new file mode 100644 index 0000000..d5360e6 --- /dev/null +++ b/workspace/ch04/src/FlowEx05.java @@ -0,0 +1,37 @@ +import java.util.*; + +class FlowEx05 { + public static void main(String[] args) { + int score = 0; + char grade = ' '; + char opt = '0'; + + System.out.print("Á¡¼ö¸¦ ÀÔ·ÂÇØÁÖ¼¼¿ä.>"); + + Scanner scanner = new Scanner(System.in); + String tmp = scanner.nextLine(); // È­¸éÀ» ÅëÇØ ÀԷ¹ÞÀº ³»¿ëÀ» tmp¿¡ ÀúÀå + score = Integer.parseInt(tmp); // ÀԷ¹ÞÀº ¹®ÀÚ¿­(tmp)À» ¼ýÀÚ·Î º¯È¯ + + System.out.printf("´ç½ÅÀÇ Á¡¼ö´Â %dÀÔ´Ï´Ù.", score); + + if (score >= 90) { // score°¡ 90Á¡ º¸´Ù °°°Å³ª Å©¸é AÇÐÁ¡(grade) + grade = 'A'; + if (score >= 98) { // 90Á¡ ÀÌ»ó Áß¿¡¼­µµ 98Á¡ ÀÌ»óÀº A+ + opt = '+'; + } else if (score < 94) { // 90Á¡ ÀÌ»ó 94Á¡ ¹Ì¸¸Àº A- + opt = '-'; + } + } else if (score >= 80){ // score°¡ 80Á¡ º¸´Ù °°°Å³ª Å©¸é BÇÐÁ¡(grade) + grade = 'B'; + if (score >= 88) { + opt = '+'; + } else if (score < 84) { + opt = '-'; + } + } else { // ³ª¸ÓÁö´Â CÇÐÁ¡(grade) + grade = 'C'; + } + + System.out.printf("´ç½ÅÀÇ ÇÐÁ¡Àº %c%cÀÔ´Ï´Ù.%n", grade, opt); + } +} diff --git a/workspace/ch04/src/FlowEx06.java b/workspace/ch04/src/FlowEx06.java new file mode 100644 index 0000000..0685877 --- /dev/null +++ b/workspace/ch04/src/FlowEx06.java @@ -0,0 +1,30 @@ +import java.util.*; + +class FlowEx06 { + public static void main(String[] args) { + int month = 0; + + System.out.print("ÇöÀç ¿ùÀ» ÀÔ·ÂÇϼ¼¿ä.>"); + + Scanner scanner = new Scanner(System.in); + String tmp = scanner.nextLine(); // È­¸éÀ» ÅëÇØ ÀԷ¹ÞÀº ³»¿ëÀ» tmp¿¡ ÀúÀå + month = Integer.parseInt(tmp); // ÀԷ¹ÞÀº ¹®ÀÚ¿­(tmp)À» ¼ýÀÚ·Î º¯È¯ + + switch(month) { + case 3: + case 4: + case 5: + System.out.println("ÇöÀçÀÇ °èÀýÀº º½ÀÔ´Ï´Ù."); + break; + case 6: case 7: case 8: + System.out.println("ÇöÀçÀÇ °èÀýÀº ¿©¸§ÀÔ´Ï´Ù."); + break; + case 9: case 10: case 11: + System.out.println("ÇöÀçÀÇ °èÀýÀº °¡À»ÀÔ´Ï´Ù."); + break; + default: + // case 12: case 1: case 2: + System.out.println("ÇöÀçÀÇ °èÀýÀº °Ü¿ïÀÔ´Ï´Ù."); + } + } // mainÀÇ ³¡ +} diff --git a/workspace/ch04/src/FlowEx07.java b/workspace/ch04/src/FlowEx07.java new file mode 100644 index 0000000..8b4431f --- /dev/null +++ b/workspace/ch04/src/FlowEx07.java @@ -0,0 +1,30 @@ +import java.util.*; + +class FlowEx07 { + public static void main(String[] args) { + int user, com; + + System.out.print("°¡À§(1),¹ÙÀ§(2), º¸(3) Áß Çϳª¸¦ ÀÔ·ÂÇϼ¼¿ä.>"); + + Scanner scanner = new Scanner(System.in); + String tmp = scanner.nextLine(); // È­¸éÀ» ÅëÇØ ÀԷ¹ÞÀº ³»¿ëÀ» tmp¿¡ ÀúÀå + user = Integer.parseInt(tmp); // ÀԷ¹ÞÀº ¹®ÀÚ¿­(tmp)¸¦ ¼ýÀÚ·Î º¯È¯ + + com = (int)(Math.random() * 3) + 1; // 1,2,3Áß Çϳª°¡ com¿¡ ÀúÀåµÊ + + System.out.println("´ç½ÅÀº "+ user +"ÀÔ´Ï´Ù."); + System.out.println("ÄÄÀº "+ com +"ÀÔ´Ï´Ù."); + + switch(user-com) { + case 2: case -1: + System.out.println("´ç½ÅÀÌ Á³½À´Ï´Ù."); + break; + case 1: case -2: + System.out.println("´ç½ÅÀÌ ÀÌ°å½À´Ï´Ù."); + break; + case 0: + System.out.println("ºñ°å½À´Ï´Ù."); + // break; // ¸¶Áö¸· ¹®ÀåÀ̹ǷΠbreak¸¦ »ç¿ëÇÒ ÇÊ¿ä°¡ ¾ø´Ù. + } + } // mainÀÇ ³¡ +} diff --git a/workspace/ch04/src/FlowEx08.java b/workspace/ch04/src/FlowEx08.java new file mode 100644 index 0000000..1762ac7 --- /dev/null +++ b/workspace/ch04/src/FlowEx08.java @@ -0,0 +1,28 @@ +import java.util.*; + +class FlowEx08 { + public static void main(String[] args) { + char gender; + String regNo = ""; + + System.out.print("´ç½ÅÀÇ ÁֹιøÈ£¸¦ ÀÔ·ÂÇϼ¼¿ä.(011231-1111222)>"); + + Scanner scanner = new Scanner(System.in); + regNo = scanner.nextLine(); + + gender = regNo.charAt(7); // ÀԷ¹ÞÀº ¹øÈ£ÀÇ 8¹ø° ¹®ÀÚ¸¦ gender¿¡ ÀúÀå + + switch(gender) { + case '1': + case '3': + System.out.println("´ç½ÅÀº ³²ÀÚÀÔ´Ï´Ù."); + break; + case '2': + case '4': + System.out.println("´ç½ÅÀº ¿©ÀÚÀÔ´Ï´Ù."); + break; + default: + System.out.println("À¯È¿ÇÏÁö ¾ÊÀº Áֹεî·Ï¹øÈ£ÀÔ´Ï´Ù.");; + } + } // mainÀÇ ³¡ +} diff --git a/workspace/ch04/src/FlowEx09.java b/workspace/ch04/src/FlowEx09.java new file mode 100644 index 0000000..cd3ee43 --- /dev/null +++ b/workspace/ch04/src/FlowEx09.java @@ -0,0 +1,36 @@ +import java.util.*; + +class FlowEx09 { + public static void main(String[] args) { + int score = 0; + char grade = ' '; + + System.out.print("´ç½ÅÀÇ Á¡¼ö¸¦ ÀÔ·ÂÇϼ¼¿ä.(1~100)>"); + + Scanner scanner = new Scanner(System.in); + String tmp = scanner.nextLine(); // È­¸éÀ» ÅëÇØ ÀԷ¹ÞÀº ³»¿ëÀ» tmp¿¡ ÀúÀå + score = Integer.parseInt(tmp); // ÀԷ¹ÞÀº ¹®ÀÚ¿­(tmp)¸¦ ¼ýÀÚ·Î º¯È¯ + + switch(score) { + case 100: case 99: case 98: case 97: case 96: + case 95: case 94: case 93: case 92: case 91: + case 90 : + grade = 'A'; + break; + case 89: case 88: case 87: case 86: + case 85: case 84: case 83: case 82: case 81: + case 80 : + grade = 'B'; + break; + case 79: case 78: case 77: case 76: + case 75: case 74: case 73: case 72: case 71: + case 70 : + grade = 'C'; + break; + default : + grade = 'F'; + } // end of switch + + System.out.println("´ç½ÅÀÇ ÇÐÁ¡Àº "+ grade +"ÀÔ´Ï´Ù."); + } // mainÀÇ ³¡ +} diff --git a/workspace/ch04/src/FlowEx10.java b/workspace/ch04/src/FlowEx10.java new file mode 100644 index 0000000..6e9221f --- /dev/null +++ b/workspace/ch04/src/FlowEx10.java @@ -0,0 +1,31 @@ +import java.util.*; + +class FlowEx10 { + public static void main(String[] args) { + int score = 0; + char grade = ' '; + + System.out.print("´ç½ÅÀÇ Á¡¼ö¸¦ ÀÔ·ÂÇϼ¼¿ä.(1~100)>"); + + Scanner scanner = new Scanner(System.in); + String tmp = scanner.nextLine(); // È­¸éÀ» ÅëÇØ ÀԷ¹ÞÀº ³»¿ëÀ» tmp¿¡ ÀúÀå + score = Integer.parseInt(tmp); // ÀԷ¹ÞÀº ¹®ÀÚ¿­(tmp)¸¦ ¼ýÀÚ·Î º¯È¯ + + switch(score/10) { + case 10: + case 9 : + grade = 'A'; + break; + case 8 : + grade = 'B'; + break; + case 7 : + grade = 'C'; + break; + default : + grade = 'F'; + } // end of switch + + System.out.println("´ç½ÅÀÇ ÇÐÁ¡Àº "+ grade +"ÀÔ´Ï´Ù."); + } // mainÀÇ ³¡ +} diff --git a/workspace/ch04/src/FlowEx11.java b/workspace/ch04/src/FlowEx11.java new file mode 100644 index 0000000..5672d38 --- /dev/null +++ b/workspace/ch04/src/FlowEx11.java @@ -0,0 +1,40 @@ +import java.util.*; + +class FlowEx11 { + public static void main(String[] args) { + char gender; + String regNo = ""; + System.out.print("´ç½ÅÀÇ ÁֹιøÈ£¸¦ ÀÔ·ÂÇϼ¼¿ä.(011231-1111222)>"); + + Scanner scanner = new Scanner(System.in); + regNo = scanner.nextLine(); + + gender = regNo.charAt(7); // ÀԷ¹ÞÀº ¹øÈ£ÀÇ 8¹ø° ¹®ÀÚ¸¦ gender¿¡ ÀúÀå + + switch(gender) { + case '1': + case '3': + switch(gender) { + case '1': + System.out.println("´ç½ÅÀº 2000³â ÀÌÀü¿¡ Ãâ»ýÇÑ ³²ÀÚÀÔ´Ï´Ù."); + break; + case '3': + System.out.println("´ç½ÅÀº 2000³â ÀÌÈÄ¿¡ Ãâ»ýÇÑ ³²ÀÚÀÔ´Ï´Ù."); + } + break; // ÀÌ break¹®À» »©¸ÔÁö ¾Êµµ·Ï ÁÖÀÇ + case '2': + case '4': + switch(gender) { + case '2': + System.out.println("´ç½ÅÀº 2000³â ÀÌÀü¿¡ Ãâ»ýÇÑ ¿©ÀÚÀÔ´Ï´Ù."); + break; + case '4': + System.out.println("´ç½ÅÀº 2000³â ÀÌÈÄ¿¡ Ãâ»ýÇÑ ¿©ÀÚÀÔ´Ï´Ù."); + break; + } + break; + default: + System.out.println("À¯È¿ÇÏÁö ¾ÊÀº Áֹεî·Ï¹øÈ£ÀÔ´Ï´Ù.");; + } + } // mainÀÇ ³¡ +} diff --git a/workspace/ch04/src/FlowEx12.java b/workspace/ch04/src/FlowEx12.java new file mode 100644 index 0000000..e4bd6ca --- /dev/null +++ b/workspace/ch04/src/FlowEx12.java @@ -0,0 +1,11 @@ +class FlowEx12 { + public static void main(String[] args) { + for(int i=1;i<=5;i++) + System.out.println(i); // iÀÇ °ªÀ» Ãâ·ÂÇÑ´Ù. + + for(int i=1;i<=5;i++) + System.out.print(i); // println()´ë½Å print()¸¦ ¾²¸é °¡·Î·Î Ãâ·ÂµÈ´Ù. + + System.out.println(); + } +} diff --git a/workspace/ch04/src/FlowEx13.java b/workspace/ch04/src/FlowEx13.java new file mode 100644 index 0000000..da55d1e --- /dev/null +++ b/workspace/ch04/src/FlowEx13.java @@ -0,0 +1,10 @@ +class FlowEx13 { + public static void main(String[] args) { + int sum = 0; // Çհ踦 ÀúÀåÇϱâ À§ÇÑ º¯¼ö. + + for(int i=1; i <= 10; i++) { + sum += i ; // sum = sum + i; + System.out.printf("1ºÎÅÍ %2d ±îÁöÀÇ ÇÕ: %2d%n", i, sum); + } + } // mainÀÇ ³¡ +} diff --git a/workspace/ch04/src/FlowEx14.java b/workspace/ch04/src/FlowEx14.java new file mode 100644 index 0000000..13af0e2 --- /dev/null +++ b/workspace/ch04/src/FlowEx14.java @@ -0,0 +1,6 @@ +class FlowEx14 { + public static void main(String[] args) { + for(int i=1,j=10;i<=10;i++,j--) + System.out.printf("%d \t %d%n", i, j); + } +} diff --git a/workspace/ch04/src/FlowEx15.java b/workspace/ch04/src/FlowEx15.java new file mode 100644 index 0000000..996c464 --- /dev/null +++ b/workspace/ch04/src/FlowEx15.java @@ -0,0 +1,10 @@ +class FlowEx15 { + public static void main(String[] args) { + System.out.println("i \t 2*i \t 2*i-1 \t i*i \t 11-i \t i%3 \t i/3"); + System.out.println("----------------------------------------------------"); + + for(int i=1;i<=10;i++) { + System.out.printf("%d \t %d \t %d \t %d \t %d \t %d \t %d%n", i, 2*i, 2*i-1, i*i, 11-i, i%3, i/3); + } + } +} diff --git a/workspace/ch04/src/FlowEx16.java b/workspace/ch04/src/FlowEx16.java new file mode 100644 index 0000000..c60d287 --- /dev/null +++ b/workspace/ch04/src/FlowEx16.java @@ -0,0 +1,10 @@ +class FlowEx16 { + public static void main(String[] args) { + for(int i=1;i<=5;i++) { + for(int j=1;j<=10;j++) { + System.out.print("*"); + } + System.out.println(); + } + } // mainÀÇ ³¡ +} diff --git a/workspace/ch04/src/FlowEx17.java b/workspace/ch04/src/FlowEx17.java new file mode 100644 index 0000000..1eca170 --- /dev/null +++ b/workspace/ch04/src/FlowEx17.java @@ -0,0 +1,20 @@ +import java.util.*; + +class FlowEx17 { + public static void main(String[] args) { + int num = 0; + + System.out.print("*À» Ãâ·ÂÇÒ ¶óÀÎÀÇ ¼ö¸¦ ÀÔ·ÂÇϼ¼¿ä.>"); + + Scanner scanner = new Scanner(System.in); + String tmp = scanner.nextLine(); // È­¸éÀ» ÅëÇØ ÀԷ¹ÞÀº ³»¿ëÀ» tmp¿¡ ÀúÀå + num = Integer.parseInt(tmp); // ÀԷ¹ÞÀº ¹®ÀÚ¿­(tmp)À» ¼ýÀÚ·Î º¯È¯ + + for(int i=0;i"); + Scanner scanner = new Scanner(System.in); + String tmp = scanner.nextLine(); // È­¸éÀ» ÅëÇØ ÀԷ¹ÞÀº ³»¿ëÀ» tmp¿¡ ÀúÀå + num = Integer.parseInt(tmp); // ÀԷ¹ÞÀº ¹®ÀÚ¿­(tmp)À» ¼ýÀÚ·Î º¯È¯ + + while(num!=0) { + // numÀ» 10À¸·Î ³ª´« ³ª¸ÓÁö¸¦ sum¿¡ ´õÇÔ + sum += num%10; // sum = sum + num%10; + System.out.printf("sum=%3d num=%d%n", sum, num); + + num /= 10; // num = num / 10; numÀ» 10À¸·Î ³ª´« °ªÀ» ´Ù½Ã num¿¡ ÀúÀå + } + + System.out.println("°¢ ÀÚ¸®¼öÀÇ ÇÕ:"+ sum); + } +} diff --git a/workspace/ch04/src/FlowEx26.java b/workspace/ch04/src/FlowEx26.java new file mode 100644 index 0000000..d559aba --- /dev/null +++ b/workspace/ch04/src/FlowEx26.java @@ -0,0 +1,10 @@ +class FlowEx26 { + public static void main(String[] args) { + int sum = 0; + int i = 0; + + while((sum += ++i) <= 100) { // i¸¦ 1¾¿ Áõ°¡½ÃÄѼ­ sum¿¡ °è¼Ó ´õÇسª°£´Ù. + System.out.printf("%d - %d%n", i, sum); + } + } // mainÀÇ ³¡ +} diff --git a/workspace/ch04/src/FlowEx27.java b/workspace/ch04/src/FlowEx27.java new file mode 100644 index 0000000..931fc0a --- /dev/null +++ b/workspace/ch04/src/FlowEx27.java @@ -0,0 +1,27 @@ +import java.util.*; + +class FlowEx27 { + public static void main(String[] args) { + int num; + int sum = 0; + boolean flag = true; // while¹®ÀÇ Á¶°Ç½ÄÀ¸·Î »ç¿ëµÉ º¯¼ö + + System.out.println("Çհ踦 ±¸ÇÒ ¼ýÀÚ¸¦ ÀÔ·ÂÇϼ¼¿ä.(²ø³»·Á¸é 0À» ÀÔ·Â)"); + + while(flag) { // flagÀÇ °ªÀÌ trueÀ̹ǷΠÁ¶°Ç½ÄÀº ÂüÀÌ µÈ´Ù. + System.out.print(">>"); + + Scanner scanner = new Scanner(System.in); + String tmp = scanner.nextLine(); + num = Integer.parseInt(tmp); + + if(num!=0) { + sum += num; // numÀÌ 0ÀÌ ¾Æ´Ï¸é, sum¿¡ ´õÇÑ´Ù. + } else { + flag = false; // numÀÌ 0À̸é, flagÀÇ °ªÀ» false·Î º¯°æ. + } + } // while¹®ÀÇ ³¡ + + System.out.println("ÇÕ°è:"+ sum); + } +} diff --git a/workspace/ch04/src/FlowEx28.java b/workspace/ch04/src/FlowEx28.java new file mode 100644 index 0000000..e95f721 --- /dev/null +++ b/workspace/ch04/src/FlowEx28.java @@ -0,0 +1,26 @@ +import java.util.*; + +class FlowEx28 { + public static void main(String[] args) { + int input = 0; + int answer = 0; + + answer = (int)(Math.random() * 100) + 1; // 1~100»çÀÌÀÇ ÀÓÀÇÀÇ ¼ö¸¦ ÀúÀå + Scanner scanner = new Scanner(System.in); + + do { + System.out.print("1°ú 100»çÀÌÀÇ Á¤¼ö¸¦ ÀÔ·ÂÇϼ¼¿ä.>"); + + String tmp = scanner.nextLine(); + input = Integer.parseInt(tmp); + + if(input > answer) { + System.out.println("´õ ÀÛÀº ¼ö·Î ´Ù½Ã ½ÃµµÇغ¸¼¼¿ä."); + } else if(input < answer) { + System.out.println("´õ Å« ¼ö·Î ´Ù½Ã ½ÃµµÇغ¸¼¼¿ä."); + } + } while(input!=answer); + + System.out.println("Á¤´äÀÔ´Ï´Ù."); + } +} diff --git a/workspace/ch04/src/FlowEx29.java b/workspace/ch04/src/FlowEx29.java new file mode 100644 index 0000000..15aa83d --- /dev/null +++ b/workspace/ch04/src/FlowEx29.java @@ -0,0 +1,16 @@ +class FlowEx29 { + public static void main(String[] args) { + for(int i=1;i<=100;i++) { + System.out.printf("i=%d ", i); + + int tmp = i; + + do { + if(tmp%10%3==0 && tmp%10!=0) // tmp%10ÀÌ 3ÀÇ ¹è¼öÀÎÁö È®ÀÎ(0 Á¦¿Ü) + System.out.print("¦"); + } while((tmp/=10)!=0); // tmp /= 10Àº tmp = tmp / 10°ú µ¿ÀÏ + + System.out.println(); + } + } // main +} diff --git a/workspace/ch04/src/FlowEx30.java b/workspace/ch04/src/FlowEx30.java new file mode 100644 index 0000000..de226e7 --- /dev/null +++ b/workspace/ch04/src/FlowEx30.java @@ -0,0 +1,16 @@ +class FlowEx30 { + public static void main(String[] args) { + int sum = 0; + int i = 0; + + while(true) { + if(sum > 100) + break; + ++i; + sum += i; + } // end of while + + System.out.println("i=" + i); + System.out.println("sum=" + sum); + } +} diff --git a/workspace/ch04/src/FlowEx31.java b/workspace/ch04/src/FlowEx31.java new file mode 100644 index 0000000..637e43d --- /dev/null +++ b/workspace/ch04/src/FlowEx31.java @@ -0,0 +1,9 @@ +class FlowEx31 { + public static void main(String[] args) { + for(int i=0;i <= 10;i++) { + if (i%3==0) + continue; + System.out.println(i); + } + } +} diff --git a/workspace/ch04/src/FlowEx32.java b/workspace/ch04/src/FlowEx32.java new file mode 100644 index 0000000..ce8afc7 --- /dev/null +++ b/workspace/ch04/src/FlowEx32.java @@ -0,0 +1,30 @@ +import java.util.*; + +class FlowEx32 { + public static void main(String[] args) { + int menu = 0; + int num = 0; + + Scanner scanner = new Scanner(System.in); + + while(true) { + System.out.println("(1) square"); + System.out.println("(2) square root"); + System.out.println("(3) log"); + System.out.print("¿øÇÏ´Â ¸Þ´º(1~3)¸¦ ¼±ÅÃÇϼ¼¿ä.(Á¾·á:0)>"); + + String tmp = scanner.nextLine(); // È­¸é¿¡¼­ ÀԷ¹ÞÀº ³»¿ëÀ» tmp¿¡ ÀúÀå + menu = Integer.parseInt(tmp); // ÀԷ¹ÞÀº ¹®ÀÚ¿­(tmp)À» ¼ýÀÚ·Î º¯È¯ + + if(menu==0) { + System.out.println("ÇÁ·Î±×·¥À» Á¾·áÇÕ´Ï´Ù."); + break; + } else if (!(1 <= menu && menu <= 3)) { + System.out.println("¸Þ´º¸¦ À߸ø ¼±ÅÃÇϼ̽À´Ï´Ù.(Á¾·á´Â 0)"); + continue; + } + + System.out.println("¼±ÅÃÇϽŠ¸Þ´º´Â "+ menu +"¹øÀÔ´Ï´Ù."); + } + } // mainÀÇ ³¡ +} diff --git a/workspace/ch04/src/FlowEx33.java b/workspace/ch04/src/FlowEx33.java new file mode 100644 index 0000000..6c4ebc8 --- /dev/null +++ b/workspace/ch04/src/FlowEx33.java @@ -0,0 +1,18 @@ +class FlowEx33 { + public static void main(String[] args) + { + // for¹®¿¡ Loop1À̶ó´Â À̸§À» ºÙ¿´´Ù. + Loop1 : for(int i=2;i <=9;i++) { + for(int j=1;j <=9;j++) { + if(j==5) + break Loop1; +// break; +// continue Loop1; +// continue; + System.out.println(i+"*"+ j +"="+ i*j); + } // end of for i + System.out.println(); + } // end of Loop1 + + } +} diff --git a/workspace/ch04/src/FlowEx34.java b/workspace/ch04/src/FlowEx34.java new file mode 100644 index 0000000..310afb3 --- /dev/null +++ b/workspace/ch04/src/FlowEx34.java @@ -0,0 +1,52 @@ +import java.util.*; + +class FlowEx34 { + public static void main(String[] args) { + int menu = 0; + int num = 0; + + Scanner scanner = new Scanner(System.in); + + outer: + while(true) { + System.out.println("(1) square"); + System.out.println("(2) square root"); + System.out.println("(3) log"); + System.out.print("¿øÇÏ´Â ¸Þ´º(1~3)¸¦ ¼±ÅÃÇϼ¼¿ä.(Á¾·á:0)>"); + + String tmp = scanner.nextLine(); // È­¸é¿¡¼­ ÀԷ¹ÞÀº ³»¿ëÀ» tmp¿¡ ÀúÀå + menu = Integer.parseInt(tmp); // ÀԷ¹ÞÀº ¹®ÀÚ¿­(tmp)À» ¼ýÀÚ·Î º¯È¯ + + if(menu==0) { + System.out.println("ÇÁ·Î±×·¥À» Á¾·áÇÕ´Ï´Ù."); + break; + } else if (!(1<= menu && menu <= 3)) { + System.out.println("¸Þ´º¸¦ À߸ø ¼±ÅÃÇϼ̽À´Ï´Ù.(Á¾·á´Â 0)"); + continue; + } + + for(;;) { + System.out.print("°è»êÇÒ °ªÀ» ÀÔ·ÂÇϼ¼¿ä.(°è»ê Á¾·á:0, Àüü Á¾·á:99)>"); + tmp = scanner.nextLine(); // È­¸é¿¡¼­ ÀԷ¹ÞÀº ³»¿ëÀ» tmp¿¡ ÀúÀå + num = Integer.parseInt(tmp); // ÀԷ¹ÞÀº ¹®ÀÚ¿­(tmp)À» ¼ýÀÚ·Î º¯È¯ + + if(num==0) + break; // °è»ê Á¾·á. for¹®À» ¹þ¾î³­´Ù. + if(num==99) + break outer; // Àüü Á¾·á. for¹®°ú while¹®À» ¸ðµÎ ¹þ¾î³­´Ù. + + switch(menu) { + case 1: + System.out.println("result="+ num*num); + break; + case 2: + System.out.println("result="+ Math.sqrt(num)); + break; + case 3: + System.out.println("result="+ Math.log(num)); + break; + } + } // for(;;) + } // whileÀÇ ³¡ + } // mainÀÇ ³¡ +} diff --git a/workspace/ch05/.classpath b/workspace/ch05/.classpath new file mode 100644 index 0000000..fceb480 --- /dev/null +++ b/workspace/ch05/.classpath @@ -0,0 +1,6 @@ + + + + + + diff --git a/workspace/ch05/.project b/workspace/ch05/.project new file mode 100644 index 0000000..19f4a32 --- /dev/null +++ b/workspace/ch05/.project @@ -0,0 +1,17 @@ + + + ch05 + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/workspace/ch05/.settings/org.eclipse.jdt.core.prefs b/workspace/ch05/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..3a21537 --- /dev/null +++ b/workspace/ch05/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,11 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/workspace/ch05/src/ArrayEx01.java b/workspace/ch05/src/ArrayEx01.java new file mode 100644 index 0000000..f698ea3 --- /dev/null +++ b/workspace/ch05/src/ArrayEx01.java @@ -0,0 +1,22 @@ +class ArrayEx01 { + public static void main(String[] args) { + int[] score = new int[5]; + int k = 1; + + score[0] = 50; + score[1] = 60; + score[k+1] = 70; // score[2] = 70 + score[3] = 80; + score[4] = 90; + + int tmp = score[k+2] + score[4]; // int tmp = score[3] + score[4] + + // for¹®À¸·Î ¹è¿­ÀÇ ¸ðµç ¿ä¼Ò¸¦ Ãâ·ÂÇÑ´Ù. + for(int i=0; i < 5; i++) { + System.out.printf("score[%d]:%d%n",i, score[i]); + } + + System.out.printf("tmp:%d%n", tmp); + System.out.printf("score[%d]:%d%n",7,score[7]); //indexÀÇ ¹üÀ§¸¦ ¹þ¾î³­ °ª + } // main +} diff --git a/workspace/ch05/src/ArrayEx02.java b/workspace/ch05/src/ArrayEx02.java new file mode 100644 index 0000000..8ff25b3 --- /dev/null +++ b/workspace/ch05/src/ArrayEx02.java @@ -0,0 +1,30 @@ +import java.util.*; // Arrays.toString()À» »ç¿ëÇϱâ À§ÇØ Ãß°¡ + +class ArrayEx02 { + public static void main(String[] args) { + int[] iArr1 = new int[10]; + int[] iArr2 = new int[10]; +// int[] iArr3 = new int[]{100, 95, 80, 70, 60}; + int[] iArr3 = {100, 95, 80, 70, 60}; + char[] chArr = {'a', 'b', 'c', 'd'}; + + for (int i=0; i < iArr1.length ; i++ ) { + iArr1[i] = i + 1; // 1~10ÀÇ ¼ýÀÚ¸¦ ¼ø¼­´ë·Î ¹è¿­¿¡ ³Ö´Â´Ù. + } + + for (int i=0; i < iArr2.length ; i++ ) { + iArr2[i] = (int)(Math.random()*10) + 1; // 1~10ÀÇ °ªÀ» ¹è¿­¿¡ ÀúÀå + } + + // ¹è¿­¿¡ ÀúÀåµÈ °ªµéÀ» Ãâ·ÂÇÑ´Ù. + for(int i=0; i < iArr1.length;i++) { + System.out.print(iArr1[i]+","); + } + System.out.println(); + System.out.println(Arrays.toString(iArr2)); + System.out.println(Arrays.toString(iArr3)); + System.out.println(Arrays.toString(chArr)); + System.out.println(iArr3); + System.out.println(chArr); + } +} diff --git a/workspace/ch05/src/ArrayEx03.java b/workspace/ch05/src/ArrayEx03.java new file mode 100644 index 0000000..e8bed92 --- /dev/null +++ b/workspace/ch05/src/ArrayEx03.java @@ -0,0 +1,25 @@ +class ArrayEx03{ + public static void main(String[] args) { + int[] arr = new int[5]; + + // ¹è¿­ arr¿¡ 1~5¸¦ ÀúÀåÇÑ´Ù. + for(int i=0; i < arr.length;i++) + arr[i] = i + 1; + + System.out.println("º¯°æÀü - arr.length:"+arr.length); + for(int i=0; i < arr.length;i++) + System.out.println("arr["+i+"]:"+arr[i]); + + int[] tmp = new int[arr.length*2]; + + // ¹è¿­ arr¿¡ ÀúÀåµÈ °ªµéÀ» ¹è¿­ tmp¿¡ º¹»çÇÑ´Ù. + for(int i=0; i < arr.length;i++) + tmp[i] = arr[i]; + + arr = tmp; // tmp¿¡ ÀúÀåµÈ °ªÀ» arr¿¡ ÀúÀåÇÑ´Ù. + + System.out.println("º¯°æÈÄ - arr.length:"+arr.length); + for(int i=0; i < arr.length;i++) + System.out.println("arr["+i+"]:"+arr[i]); + } +} diff --git a/workspace/ch05/src/ArrayEx04.java b/workspace/ch05/src/ArrayEx04.java new file mode 100644 index 0000000..cf630e4 --- /dev/null +++ b/workspace/ch05/src/ArrayEx04.java @@ -0,0 +1,22 @@ +class ArrayEx04 { + public static void main(String[] args) { + char[] abc = { 'A', 'B', 'C', 'D'}; + char[] num = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; + System.out.println(abc); + System.out.println(num); + + // ¹è¿­ abc¿Í numÀ» ºÙ¿©¼­ ÇϳªÀÇ ¹è¿­(result)·Î ¸¸µç´Ù. + char[] result = new char[abc.length+num.length]; + System.arraycopy(abc, 0, result, 0, abc.length); + System.arraycopy(num, 0, result, abc.length, num.length); + System.out.println(result); + + // ¹è¿­ abcÀ» ¹è¿­ numÀÇ Ã¹ ¹ø° À§Ä¡ºÎÅÍ ¹è¿­ abcÀÇ ±æÀ̸¸Å­ º¹»ç + System.arraycopy(abc, 0, num, 0, abc.length); + System.out.println(num); + + // numberÀÇ À妽º6 À§Ä¡¿¡ 3°³¸¦ º¹»ç + System.arraycopy(abc, 0, num, 6, 3); + System.out.println(num); + } +} diff --git a/workspace/ch05/src/ArrayEx05.java b/workspace/ch05/src/ArrayEx05.java new file mode 100644 index 0000000..bf3ae0a --- /dev/null +++ b/workspace/ch05/src/ArrayEx05.java @@ -0,0 +1,17 @@ +class ArrayEx05 { + public static void main(String[] args) { + int sum =0; // ÃÑÁ¡À» ÀúÀåÇϱâ À§ÇÑ º¯¼ö + float average = 0f; // Æò±ÕÀ» ÀúÀåÇϱâ À§ÇÑ º¯¼ö + + int[] score = {100, 88, 100, 100, 90}; + + for (int i=0; i < score.length ; i++ ) { + sum += score[i]; + } + + average = sum / (float)score.length ; // °è»ê°á°ú¸¦ float·Î ¾ò±â À§ÇÔ. + + System.out.println("ÃÑÁ¡ : " + sum); + System.out.println("Æò±Õ : " + average); + } +} diff --git a/workspace/ch05/src/ArrayEx06.java b/workspace/ch05/src/ArrayEx06.java new file mode 100644 index 0000000..d92180d --- /dev/null +++ b/workspace/ch05/src/ArrayEx06.java @@ -0,0 +1,19 @@ +class ArrayEx06 { + public static void main(String[] args) { + int[] score = { 79, 88, 91, 33, 100, 55, 95}; + + int max = score[0]; // ¹è¿­ÀÇ Ã¹ ¹ø° °ªÀ¸·Î ÃÖ´ë°ªÀ» ÃʱâÈ­ ÇÑ´Ù. + int min = score[0]; // ¹è¿­ÀÇ Ã¹ ¹ø° °ªÀ¸·Î ÃÖ¼Ò°ªÀ» ÃʱâÈ­ ÇÑ´Ù. + + for(int i=1; i < score.length;i++) { + if(score[i] > max) { + max = score[i]; + } else if(score[i] < min) { + min = score[i]; + } + } // end of for + + System.out.println("ÃÖ´ë°ª :" + max); + System.out.println("ÃÖ¼Ò°ª :" + min); + } // end of main +} // end of class diff --git a/workspace/ch05/src/ArrayEx07.java b/workspace/ch05/src/ArrayEx07.java new file mode 100644 index 0000000..9771587 --- /dev/null +++ b/workspace/ch05/src/ArrayEx07.java @@ -0,0 +1,22 @@ +class ArrayEx07 { + public static void main(String[] args) { + int[] numArr = new int[10]; + + for (int i=0; i < numArr.length ; i++ ) { + numArr[i] = i; // ¹è¿­À» 0~9ÀÇ ¼ýÀÚ·Î ÃʱâÈ­ÇÑ´Ù. + System.out.print(numArr[i]); + } + System.out.println(); + + for (int i=0; i < 100; i++ ) { + int n = (int)(Math.random() * 10); // 0~9ÁßÀÇ ÇÑ °ªÀ» ÀÓÀÇ·Î ¾ò´Â´Ù. + + int tmp = numArr[0]; + numArr[0] = numArr[n]; + numArr[n] = tmp; + } + + for (int i=0; i < numArr.length ; i++ ) + System.out.print(numArr[i]); + } // mainÀÇ ³¡ +} diff --git a/workspace/ch05/src/ArrayEx08.java b/workspace/ch05/src/ArrayEx08.java new file mode 100644 index 0000000..d1b1934 --- /dev/null +++ b/workspace/ch05/src/ArrayEx08.java @@ -0,0 +1,26 @@ +class ArrayEx08 { + public static void main(String[] args) { + // 45°³ÀÇ Á¤¼ö°ªÀ» ÀúÀåÇϱâ À§ÇÑ ¹è¿­ »ý¼º. + int[] ball = new int[45]; + + // ¹è¿­ÀÇ °¢ ¿ä¼Ò¿¡ 1~45ÀÇ °ªÀ» ÀúÀåÇÑ´Ù. + for(int i=0; i < ball.length; i++) + ball[i] = i+1; // ball[0]¿¡ 1ÀÌ ÀúÀåµÈ´Ù. + + int temp = 0; // µÎ °ªÀ» ¹Ù²Ù´Âµ¥ »ç¿ëÇÒ Àӽú¯¼ö + int j = 0; // ÀÓÀÇÀÇ °ªÀ» ¾ò¾î¼­ ÀúÀåÇÒ º¯¼ö + + // ¹è¿­ÀÇ i¹ø° ¿ä¼Ò¿Í ÀÓÀÇÀÇ ¿ä¼Ò¿¡ ÀúÀåµÈ °ªÀ» ¼­·Î ¹Ù²ã¼­ °ªÀ» ¼¯´Â´Ù. + // 0¹ø° ºÎÅÍ 5¹ø° ¿ä¼Ò±îÁö ¸ðµÎ 6°³¸¸ ¹Ù²Û´Ù. + for(int i=0; i < 6; i++) { + j = (int)(Math.random() * 45); // 0~44¹üÀ§ÀÇ ÀÓÀÇÀÇ °ªÀ» ¾ò´Â´Ù. + temp = ball[i]; + ball[i] = ball[j]; + ball[j] = temp; + } + + // ¹è¿­ ballÀÇ ¾Õ¿¡¼­ ºÎÅÍ 6°³ÀÇ ¿ä¼Ò¸¦ Ãâ·ÂÇÑ´Ù. + for(int i=0; i < 6; i++) + System.out.printf("ball[%d]=%d%n", i, ball[i]); + } +} diff --git a/workspace/ch05/src/ArrayEx09.java b/workspace/ch05/src/ArrayEx09.java new file mode 100644 index 0000000..58e4ecc --- /dev/null +++ b/workspace/ch05/src/ArrayEx09.java @@ -0,0 +1,15 @@ +import java.util.*; // Arrays.toString()À» »ç¿ëÇϱâ À§ÇØ Ãß°¡ + +class ArrayEx09 { + public static void main(String[] args) { + int[] code = { -4, -1, 3, 6, 11 }; // ºÒ¿¬¼ÓÀûÀÎ °ªµé·Î ±¸¼ºµÈ ¹è¿­ + int[] arr = new int[10]; + + for (int i=0; i < arr.length ; i++ ) { + int tmp = (int)(Math.random() * code.length); + arr[i] = code[tmp]; + } + + System.out.println(Arrays.toString(arr)); + } // mainÀÇ ³¡ +} diff --git a/workspace/ch05/src/ArrayEx10.java b/workspace/ch05/src/ArrayEx10.java new file mode 100644 index 0000000..32b6e8a --- /dev/null +++ b/workspace/ch05/src/ArrayEx10.java @@ -0,0 +1,29 @@ +class ArrayEx10 { + public static void main(String[] args) { + int[] numArr = new int[10]; + + for (int i=0; i < numArr.length ; i++ ) { + System.out.print(numArr[i] = (int)(Math.random() * 10)); + } + System.out.println(); + + for (int i=0; i < numArr.length-1 ; i++ ) { + boolean changed = false; // ÀÚ¸®¹Ù²ÞÀÌ ¹ß»ýÇß´ÂÁö¸¦ üũÇÑ´Ù. + + for (int j=0; j < numArr.length-1-i ;j++) { + if(numArr[j] > numArr[j+1]) { // ¿·ÀÇ °ªÀÌ ÀÛÀ¸¸é ¼­·Î ¹Ù²Û´Ù. + int temp = numArr[j]; + numArr[j] = numArr[j+1]; + numArr[j+1] = temp; + changed = true; // ÀÚ¸®¹Ù²ÞÀÌ ¹ß»ýÇßÀ¸´Ï changed¸¦ true·Î. + } + } // end for j + + if (!changed) break; // ÀÚ¸®¹Ù²ÞÀÌ ¾øÀ¸¸é ¹Ýº¹¹®À» ¹þ¾î³­´Ù. + + for(int k=0; k='0' && hex[i] <='9') { + result +=binary[hex[i]-'0']; // '8'-'0'ÀÇ °á°ú´Â 8ÀÌ´Ù. + } else { // A~FÀ̸é + result +=binary[hex[i]-'A'+10]; // 'C'-'A'ÀÇ °á°ú´Â 2 + } + } + + System.out.println("hex:"+ new String(hex)); // String(char[] value) + System.out.println("binary:"+result); + } +} diff --git a/workspace/ch05/src/ArrayEx14.java b/workspace/ch05/src/ArrayEx14.java new file mode 100644 index 0000000..3b12d95 --- /dev/null +++ b/workspace/ch05/src/ArrayEx14.java @@ -0,0 +1,14 @@ +class ArrayEx14 { + public static void main(String[] args) { + String src = "ABCDE"; + + for(int i=0; i < src.length(); i++) { + char ch = src.charAt(i); // srcÀÇ i¹ø° ¹®ÀÚ¸¦ ch¿¡ ÀúÀå + System.out.println("src.charAt("+i+"):"+ ch); + } + + char[] chArr = src.toCharArray(); // StringÀ» char[]·Î º¯È¯ + + System.out.println(chArr); // char¹è¿­(char[])À» Ãâ·Â + } +} diff --git a/workspace/ch05/src/ArrayEx15.java b/workspace/ch05/src/ArrayEx15.java new file mode 100644 index 0000000..59a7b62 --- /dev/null +++ b/workspace/ch05/src/ArrayEx15.java @@ -0,0 +1,19 @@ +class ArrayEx15 { + public static void main(String[] args) { + String source = "SOSHELP"; + String[] morse = {".-", "-...", "-.-.","-..", "." + ,"..-.", "--.", "....","..",".---" + , "-.-", ".-..", "--", "-.", "---" + , ".--.", "--.-",".-.","...","-" + , "..-", "...-", ".--", "-..-","-.--" + , "--.." }; + + String result=""; + + for (int i=0; i < source.length() ; i++ ) { + result+=morse[source.charAt(i)-'A']; + } + System.out.println("source:"+ source); + System.out.println("morse:"+result); + } +} diff --git a/workspace/ch05/src/ArrayEx16.java b/workspace/ch05/src/ArrayEx16.java new file mode 100644 index 0000000..5d8d943 --- /dev/null +++ b/workspace/ch05/src/ArrayEx16.java @@ -0,0 +1,9 @@ +class ArrayEx16 { + public static void main(String[] args) { + System.out.println("¸Å°³º¯¼öÀÇ °³¼ö:"+args.length); + + for(int i=0;i< args.length;i++) { + System.out.println("args[" + i + "] = \""+ args[i] + "\""); + } + } +} diff --git a/workspace/ch05/src/ArrayEx17.java b/workspace/ch05/src/ArrayEx17.java new file mode 100644 index 0000000..b21cbe1 --- /dev/null +++ b/workspace/ch05/src/ArrayEx17.java @@ -0,0 +1,33 @@ +class ArrayEx17 { + public static void main(String[] args) { + if (args.length !=3) { + System.out.println("usage: java ArrayEx15 NUM1 OP NUM2"); + System.exit(0); + } + + int num1 = Integer.parseInt(args[0]); // ¹®ÀÚ¿­À» ¼ýÀÚ·Î º¯È¯ÇÑ´Ù. + char op = args[1].charAt(0); // ¹®ÀÚ¿­À» ¹®ÀÚ(char)·Î º¯È¯ÇÑ´Ù. + int num2 = Integer.parseInt(args[2]); + + int result = 0; + + switch(op) { // switch¹®ÀÇ ¼ö½ÄÀ¸·Î charŸÀÔÀÇ º¯¼öµµ °¡´ÉÇÏ´Ù. + case '+': + result = num1 + num2; + break; + case '-': + result = num1 - num2; + break; + case 'x': + result = num1 * num2; + break; + case '/': + result = num1 / num2; + break; + default : + System.out.println("Áö¿øµÇÁö ¾Ê´Â ¿¬»êÀÔ´Ï´Ù."); + } + + System.out.println("°á°ú:"+result); + } +} diff --git a/workspace/ch05/src/ArrayEx18.java b/workspace/ch05/src/ArrayEx18.java new file mode 100644 index 0000000..666297e --- /dev/null +++ b/workspace/ch05/src/ArrayEx18.java @@ -0,0 +1,25 @@ +class ArrayEx18 { + public static void main(String[] args) { + int[][] score = { + { 100, 100, 100} + , { 20, 20, 20} + , { 30, 30, 30} + , { 40, 40, 40} + }; + int sum = 0; + + for(int i=0;i < score.length;i++) { + for(int j=0;j < score[i].length;j++) { + System.out.printf("score[%d][%d]=%d%n", i, j, score[i][j]); + } + } + + for (int[] tmp : score) { + for (int i : tmp) { + sum += i; + } + } + + System.out.println("sum="+sum); + } +} diff --git a/workspace/ch05/src/ArrayEx19.java b/workspace/ch05/src/ArrayEx19.java new file mode 100644 index 0000000..e9c2a89 --- /dev/null +++ b/workspace/ch05/src/ArrayEx19.java @@ -0,0 +1,39 @@ +class ArrayEx19 { + public static void main(String[] args) { + int[][] score = { + { 100, 100, 100} + , { 20, 20, 20} + , { 30, 30, 30} + , { 40, 40, 40} + , { 50, 50, 50} + }; + // °ú¸ñº° ÃÑÁ¡ + int korTotal = 0; + int engTotal = 0; + int mathTotal = 0; + + System.out.println("¹øÈ£ ±¹¾î ¿µ¾î ¼öÇÐ ÃÑÁ¡ Æò±Õ "); + System.out.println("============================="); + + for(int i=0;i < score.length;i++) { + int sum = 0; // °³Àκ° ÃÑÁ¡ + float avg = 0.0f; // °³Àκ° Æò±Õ + + korTotal += score[i][0]; + engTotal += score[i][1]; + mathTotal += score[i][2]; + System.out.printf("%3d", i+1); + + for(int j=0;j < score[i].length;j++) { + sum += score[i][j]; + System.out.printf("%5d", score[i][j]); + } + + avg = sum/(float)score[i].length; // Æò±Õ°è»ê + System.out.printf("%5d %5.1f%n", sum, avg); + } + + System.out.println("============================="); + System.out.printf("ÃÑÁ¡:%3d %4d %4d%n", korTotal, engTotal, mathTotal); + } +} diff --git a/workspace/ch05/src/MultiArrEx1.java b/workspace/ch05/src/MultiArrEx1.java new file mode 100644 index 0000000..c145f99 --- /dev/null +++ b/workspace/ch05/src/MultiArrEx1.java @@ -0,0 +1,55 @@ +import java.util.*; + +class MultiArrEx1 { + public static void main(String[] args) { + final int SIZE = 10; + int x = 0, y = 0; + + char[][] board = new char[SIZE][SIZE]; + byte[][] shipBoard = { + // 1 2 3 4 5 6 7 8 9 + { 0, 0, 0, 0, 0, 0, 1, 0, 0 }, // 1 + { 1, 1, 1, 1, 0, 0, 1, 0, 0 }, // 2 + { 0, 0, 0, 0, 0, 0, 1, 0, 0 }, // 3 + { 0, 0, 0, 0, 0, 0, 1, 0, 0 }, // 4 + { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, // 5 + { 1, 1, 0, 1, 0, 0, 0, 0, 0 }, // 6 + { 0, 0, 0, 1, 0, 0, 0, 0, 0 }, // 7 + { 0, 0, 0, 1, 0, 0, 0, 0, 0 }, // 8 + { 0, 0, 0, 0, 0, 1, 1, 1, 0 }, // 9 + }; + + // 0Çà¿¡ Çà¹øÈ£¸¦, 0¿­¿¡ ¿­¹øÈ£¸¦ ÀúÀåÇÑ´Ù. + for(int i=1;i"); + String input = scanner.nextLine(); // È­¸éÀԷ¹ÞÀº ³»¿ëÀ» tmp¿¡ ÀúÀå + + if(input.length()==2) { // µÎ ±ÛÀÚ¸¦ ÀÔ·ÂÇÑ °æ¿ì + x = input.charAt(0) - '0'; // ¹®ÀÚ¸¦ ¼ýÀÚ·Î º¯È¯ + y = input.charAt(1) - '0'; + + if(x==0 && y==0) // x¿Í y°¡ ¸ðµÎ 0ÀÎ °æ¿ì Á¾·á + break; + } + + if(input.length()!=2 || x <= 0 || x >= SIZE || y <= 0 || y >= SIZE){ + System.out.println("À߸øµÈ ÀÔ·ÂÀÔ´Ï´Ù. ´Ù½Ã ÀÔ·ÂÇØÁÖ¼¼¿ä."); + continue; + } + + // shipBoard[x-1][y-1]ÀÇ °ªÀÌ 1À̸é, 'O'À» board[x][y]¿¡ ÀúÀåÇÑ´Ù. + board[x][y] = shipBoard[x-1][y-1]==1 ? 'O' : 'X'; + + // ¹è¿­ boardÀÇ ³»¿ëÀ» È­¸é¿¡ Ãâ·ÂÇÑ´Ù. + for(int i=0;i", SIZE*SIZE); + String tmp = scanner.nextLine(); // È­¸é¿¡¼­ ÀԷ¹ÞÀº ³»¿ëÀ» tmp¿¡ ÀúÀå + num = Integer.parseInt(tmp); // ÀԷ¹ÞÀº ¹®ÀÚ¿­(tmp)¸¦ ¼ýÀÚ·Î º¯È¯ + + // ÀԷ¹ÞÀº ¼ýÀÚ¿Í °°Àº ¼ýÀÚ°¡ ÀúÀåµÈ ¿ä¼Ò¸¦ ã¾Æ¼­ 0À» ÀúÀå + outer: + for(int i=0;i + + + + + diff --git a/workspace/ch06/.project b/workspace/ch06/.project new file mode 100644 index 0000000..cf9d717 --- /dev/null +++ b/workspace/ch06/.project @@ -0,0 +1,17 @@ + + + ch06 + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/workspace/ch06/.settings/org.eclipse.jdt.core.prefs b/workspace/ch06/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..3a21537 --- /dev/null +++ b/workspace/ch06/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,11 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/workspace/ch06/src/BlockTest.java b/workspace/ch06/src/BlockTest.java new file mode 100644 index 0000000..35b4a4a --- /dev/null +++ b/workspace/ch06/src/BlockTest.java @@ -0,0 +1,22 @@ +class BlockTest { + + static { + System.out.println("static { }"); + } + + { + System.out.println("{ }"); + } + + public BlockTest() { + System.out.println("»ý¼ºÀÚ"); + } + + public static void main(String args[]) { + System.out.println("BlockTest bt = new BlockTest(); "); + BlockTest bt = new BlockTest(); + + System.out.println("BlockTest bt2 = new BlockTest(); "); + BlockTest bt2 = new BlockTest(); + } +} diff --git a/workspace/ch06/src/CallStackTest.java b/workspace/ch06/src/CallStackTest.java new file mode 100644 index 0000000..064dd35 --- /dev/null +++ b/workspace/ch06/src/CallStackTest.java @@ -0,0 +1,13 @@ +class CallStackTest { + public static void main(String[] args) { + firstMethod(); + } + + static void firstMethod() { + secondMethod(); + } + + static void secondMethod() { + System.out.println("secondMethod()"); + } +} diff --git a/workspace/ch06/src/CallStackTest2.java b/workspace/ch06/src/CallStackTest2.java new file mode 100644 index 0000000..f9f0226 --- /dev/null +++ b/workspace/ch06/src/CallStackTest2.java @@ -0,0 +1,18 @@ +class CallStackTest2 { + public static void main(String[] args) { + System.out.println("main(String[] args)ÀÌ ½ÃÀ۵ǾúÀ½."); + firstMethod(); + System.out.println("main(String[] args)ÀÌ ³¡³µÀ½."); + } + + static void firstMethod() { + System.out.println("firstMethod()ÀÌ ½ÃÀ۵ǾúÀ½."); + secondMethod(); + System.out.println("firstMethod()ÀÌ ³¡³µÀ½."); + } + + static void secondMethod() { + System.out.println("secondMethod()ÀÌ ½ÃÀ۵ǾúÀ½."); + System.out.println("secondMethod()ÀÌ ³¡³µÀ½."); + } +} diff --git a/workspace/ch06/src/CarTest.java b/workspace/ch06/src/CarTest.java new file mode 100644 index 0000000..88b97c5 --- /dev/null +++ b/workspace/ch06/src/CarTest.java @@ -0,0 +1,26 @@ +class Car { + String color; // »ö»ó + String gearType; // º¯¼Ó±â Á¾·ù - auto(ÀÚµ¿), manual(¼öµ¿) + int door; // ¹®ÀÇ °³¼ö + + Car() {} + Car(String c, String g, int d) { + color = c; + gearType = g; + door = d; + } +} + +class CarTest { + public static void main(String[] args) { + Car c1 = new Car(); + c1.color = "white"; + c1.gearType = "auto"; + c1.door = 4; + + Car c2 = new Car("white", "auto", 4); + + System.out.println("c1ÀÇ color=" + c1.color + ", gearType=" + c1.gearType+ ", door="+c1.door); + System.out.println("c2ÀÇ color=" + c2.color + ", gearType=" + c2.gearType+ ", door="+c2.door); + } +} diff --git a/workspace/ch06/src/CarTest2.java b/workspace/ch06/src/CarTest2.java new file mode 100644 index 0000000..6e9a6dd --- /dev/null +++ b/workspace/ch06/src/CarTest2.java @@ -0,0 +1,28 @@ +class Car2 { + String color; // »ö»ó + String gearType; // º¯¼Ó±â Á¾·ù - auto(ÀÚµ¿), manual(¼öµ¿) + int door; // ¹®ÀÇ °³¼ö + + Car2() { + this("white", "auto", 4); + } + + Car2(String color) { + this(color, "auto", 4); + } + Car2(String color, String gearType, int door) { + this.color = color; + this.gearType = gearType; + this.door = door; + } +} + +class CarTest2 { + public static void main(String[] args) { + Car2 c1 = new Car2(); + Car2 c2 = new Car2("blue"); + + System.out.println("c1ÀÇ color=" + c1.color + ", gearType=" + c1.gearType+ ", door="+c1.door); + System.out.println("c2ÀÇ color=" + c2.color + ", gearType=" + c2.gearType+ ", door="+c2.door); + } +} diff --git a/workspace/ch06/src/CarTest3.java b/workspace/ch06/src/CarTest3.java new file mode 100644 index 0000000..5cb0edd --- /dev/null +++ b/workspace/ch06/src/CarTest3.java @@ -0,0 +1,34 @@ +class Car3 { + String color; // »ö»ó + String gearType; // º¯¼Ó±â Á¾·ù - auto(ÀÚµ¿), manual(¼öµ¿) + int door; // ¹®ÀÇ °³¼ö + + Car3() { + this("white", "auto", 4); + } + + Car3(Car3 c) { // ÀνºÅϽºÀÇ º¹»ç¸¦ À§ÇÑ »ý¼ºÀÚ. + color = c.color; + gearType = c.gearType; + door = c.door; + } + + Car3(String color, String gearType, int door) { + this.color = color; + this.gearType = gearType; + this.door = door; + } +} +class CarTest3 { + public static void main(String[] args) { + Car3 c1 = new Car3(); + Car3 c2 = new Car3(c1); // c1ÀÇ º¹»çº» c2¸¦ »ý¼ºÇÑ´Ù. + System.out.println("c1ÀÇ color=" + c1.color + ", gearType=" + c1.gearType+ ", door="+c1.door); + System.out.println("c2ÀÇ color=" + c2.color + ", gearType=" + c2.gearType+ ", door="+c2.door); + + c1.door=100; // c1ÀÇ ÀνºÅϽºº¯¼ö doorÀÇ °ªÀ» º¯°æÇÑ´Ù. + System.out.println("c1.door=100; ¼öÇà ÈÄ"); + System.out.println("c1ÀÇ color=" + c1.color + ", gearType=" + c1.gearType+ ", door="+c1.door); + System.out.println("c2ÀÇ color=" + c2.color + ", gearType=" + c2.gearType+ ", door="+c2.door); + } +} diff --git a/workspace/ch06/src/CardTest.java b/workspace/ch06/src/CardTest.java new file mode 100644 index 0000000..2d82934 --- /dev/null +++ b/workspace/ch06/src/CardTest.java @@ -0,0 +1,31 @@ +class CardTest{ + public static void main(String args[]) { + System.out.println("Card.width = " + Card.width); + System.out.println("Card.height = " + Card.height); + + Card c1 = new Card(); + c1.kind = "Heart"; + c1.number = 7; + + Card c2 = new Card(); + c2.kind = "Spade"; + c2.number = 4; + + System.out.println("c1Àº " + c1.kind + ", " + c1.number + "À̸ç, Å©±â´Â (" + c1.width + ", " + c1.height + ")" ); + System.out.println("c2´Â " + c2.kind + ", " + c2.number + "À̸ç, Å©±â´Â (" + c2.width + ", " + c2.height + ")" ); + + System.out.println("c1ÀÇ width¿Í height¸¦ °¢°¢ 50, 80À¸·Î º¯°æÇÕ´Ï´Ù."); + c1.width = 50; + c1.height = 80; + + System.out.println("c1Àº " + c1.kind + ", " + c1.number + "À̸ç, Å©±â´Â (" + c1.width + ", " + c1.height + ")" ); + System.out.println("c2´Â " + c2.kind + ", " + c2.number + "À̸ç, Å©±â´Â (" + c2.width + ", " + c2.height + ")" ); + } + } + +class Card { + String kind ; // Ä«µåÀÇ ¹«´Ì - ÀνºÅϽº º¯¼ö + int number; // Ä«µåÀÇ ¼ýÀÚ - ÀνºÅϽº º¯¼ö + static int width = 100; // Ä«µåÀÇ Æø - Ŭ·¡½º º¯¼ö + static int height = 250; // Ä«µåÀÇ ³ôÀÌ - Ŭ·¡½º º¯¼ö +} diff --git a/workspace/ch06/src/ConstructorTest.java b/workspace/ch06/src/ConstructorTest.java new file mode 100644 index 0000000..8dee764 --- /dev/null +++ b/workspace/ch06/src/ConstructorTest.java @@ -0,0 +1,18 @@ +class Data1 { + int value; +} + +class Data2 { + int value; + + Data2(int x) { // ¸Å°³º¯¼ö°¡ ÀÖ´Â »ý¼ºÀÚ. + value = x; + } +} + +class ConstructorTest { + public static void main(String[] args) { + Data1 d1 = new Data1(); + Data2 d2 = new Data2(); // compile error¹ß»ý + } +} diff --git a/workspace/ch06/src/DocumentTest.java b/workspace/ch06/src/DocumentTest.java new file mode 100644 index 0000000..2c7c3c6 --- /dev/null +++ b/workspace/ch06/src/DocumentTest.java @@ -0,0 +1,22 @@ +class Document { + static int count = 0; + String name; // ¹®¼­¸í(Document name) + + Document() { // ¹®¼­ »ý¼º ½Ã ¹®¼­¸íÀ» ÁöÁ¤ÇÏÁö ¾Ê¾ÒÀ» ¶§ + this("Á¦¸ñ¾øÀ½" + ++count); + } + + Document(String name) { + this.name = name; + System.out.println("¹®¼­ " + this.name + "°¡ »ý¼ºµÇ¾ú½À´Ï´Ù."); + } +} + +class DocumentTest { + public static void main(String args[]) { + Document d1 = new Document(); + Document d2 = new Document("ÀÚ¹Ù.txt"); + Document d3 = new Document(); + Document d4 = new Document(); + } +} diff --git a/workspace/ch06/src/FactorialTest.java b/workspace/ch06/src/FactorialTest.java new file mode 100644 index 0000000..404dc50 --- /dev/null +++ b/workspace/ch06/src/FactorialTest.java @@ -0,0 +1,19 @@ +class FactorialTest { + public static void main(String args[]) { + int result = factorial(4); // int result = FactorialTest.factorial(4); + + System.out.println(result); + } + + static int factorial(int n) { + int result=0; + + if ( n == 1) { + result = 1; + } else { + result = n * factorial(n-1); // ´Ù½Ã ¸Þ¼­µå ÀÚ½ÅÀ» È£ÃâÇÑ´Ù. + } + + return result; + } +} diff --git a/workspace/ch06/src/FactorialTest2.java b/workspace/ch06/src/FactorialTest2.java new file mode 100644 index 0000000..cec802e --- /dev/null +++ b/workspace/ch06/src/FactorialTest2.java @@ -0,0 +1,24 @@ +class FactorialTest2 { + static long factorial(int n) { + if(n<=0 || n>20) return -1; // ¸Å°³º¯¼öÀÇ À¯È¿¼º °Ë»ç. + if(n<=1) + return 1; + return n * factorial(n-1); + } + + public static void main(String args[]) { + int n = 21; + long result = 0; + + for(int i = 1; i <= n; i++) { + result = factorial(i); + + if(result==-1) { + System.out.printf("À¯È¿ÇÏÁö ¾ÊÀº °ªÀÔ´Ï´Ù.(0 arr[j+1]) { + int tmp = arr[j]; + arr[j] = arr[j+1]; + arr[j+1] = tmp; + } + } // sortArr(int[] arr) +} diff --git a/workspace/ch06/src/ReferenceReturnEx.java b/workspace/ch06/src/ReferenceReturnEx.java new file mode 100644 index 0000000..4166fa6 --- /dev/null +++ b/workspace/ch06/src/ReferenceReturnEx.java @@ -0,0 +1,20 @@ +class Data3 { int x; } + +class ReferenceReturnEx { + public static void main(String[] args) + { + Data3 d = new Data3(); + d.x = 10; + + Data3 d2 = copy(d); + System.out.println("d.x ="+d.x); + System.out.println("d2.x="+d2.x); + } + + static Data3 copy(Data3 d) { + Data3 tmp = new Data3(); + tmp.x = d.x; + + return tmp; + } +} diff --git a/workspace/ch06/src/ReturnTest.java b/workspace/ch06/src/ReturnTest.java new file mode 100644 index 0000000..c14e000 --- /dev/null +++ b/workspace/ch06/src/ReturnTest.java @@ -0,0 +1,20 @@ +class ReturnTest { + public static void main(String[] args) { + ReturnTest r = new ReturnTest(); + + int result = r.add(3,5); + System.out.println(result); + + int[] result2 = {0}; // ¹è¿­À» »ý¼ºÇÏ°í result2[0]ÀÇ °ªÀ» 0À¸·Î ÃʱâÈ­ + r.add(3,5,result2); // ¹è¿­À» add¸Þ¼­µåÀÇ ¸Å°³º¯¼ö·Î Àü´Þ + System.out.println(result2[0]); + } + + int add(int a, int b) { + return a + b; + } + + void add(int a, int b, int[] result) { + result[0] = a + b; // ¸Å°³º¯¼ö·Î ³Ñ°Ü¹ÞÀº ¹è¿­¿¡ ¿¬»ê°á°ú¸¦ ÀúÀå + } +} diff --git a/workspace/ch06/src/StaticBlockTest.java b/workspace/ch06/src/StaticBlockTest.java new file mode 100644 index 0000000..8d69cfb --- /dev/null +++ b/workspace/ch06/src/StaticBlockTest.java @@ -0,0 +1,16 @@ +class StaticBlockTest +{ + static int[] arr = new int[10]; + + static { + for(int i=0;i + + + + + diff --git a/workspace/ch07/.project b/workspace/ch07/.project new file mode 100644 index 0000000..3a65819 --- /dev/null +++ b/workspace/ch07/.project @@ -0,0 +1,17 @@ + + + ch07 + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/workspace/ch07/.settings/org.eclipse.jdt.core.prefs b/workspace/ch07/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..3a21537 --- /dev/null +++ b/workspace/ch07/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,11 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/workspace/ch07/src/BindingTest.java b/workspace/ch07/src/BindingTest.java new file mode 100644 index 0000000..a04bd5b --- /dev/null +++ b/workspace/ch07/src/BindingTest.java @@ -0,0 +1,28 @@ +class BindingTest{ + public static void main(String[] args) { + Parent3 p = new Child3(); + Child3 c = new Child3(); + + System.out.println("p.x = " + p.x); + p.method(); + + System.out.println("c.x = " + c.x); + c.method(); + } +} + +class Parent3 { + int x = 100; + + void method() { + System.out.println("Parent Method"); + } +} + +class Child3 extends Parent3 { + int x = 200; + + void method() { + System.out.println("Child Method"); + } +} diff --git a/workspace/ch07/src/BindingTest2.java b/workspace/ch07/src/BindingTest2.java new file mode 100644 index 0000000..5f086ba --- /dev/null +++ b/workspace/ch07/src/BindingTest2.java @@ -0,0 +1,22 @@ +class BindingTest2 { + public static void main(String[] args) { + Parent4 p = new Child4(); + Child4 c = new Child4(); + + System.out.println("p.x = " + p.x); + p.method(); + + System.out.println("c.x = " + c.x); + c.method(); + } +} + +class Parent4 { + int x = 100; + + void method() { + System.out.println("Parent Method"); + } +} + +class Child4 extends Parent4 { } diff --git a/workspace/ch07/src/BindingTest3.java b/workspace/ch07/src/BindingTest3.java new file mode 100644 index 0000000..7821c8a --- /dev/null +++ b/workspace/ch07/src/BindingTest3.java @@ -0,0 +1,30 @@ +class BindingTest3{ + public static void main(String[] args) { + Parent5 p = new Child5(); + Child5 c = new Child5(); + + System.out.println("p.x = " + p.x); + p.method(); + System.out.println(); + System.out.println("c.x = " + c.x); + c.method(); + } +} + +class Parent5 { + int x = 100; + + void method() { + System.out.println("Parent Method"); + } +} + +class Child5 extends Parent5 { + int x = 200; + + void method() { + System.out.println("x=" + x); // this.x¿Í °°´Ù. + System.out.println("super.x=" + super.x); + System.out.println("this.x=" + this.x); + } +} diff --git a/workspace/ch07/src/CaptionTvTest.java b/workspace/ch07/src/CaptionTvTest.java new file mode 100644 index 0000000..8c6d7aa --- /dev/null +++ b/workspace/ch07/src/CaptionTvTest.java @@ -0,0 +1,29 @@ +class Tv { + boolean power; // Àü¿ø»óÅÂ(on/off) + int channel; // ä³Î + + void power() { power = !power; } + void channelUp() { ++channel; } + void channelDown() { --channel; } +} + +class CaptionTv extends Tv { + boolean caption; // ĸ¼Ç»óÅÂ(on/off) + void displayCaption(String text) { + if (caption) { // ĸ¼Ç »óÅ°¡ on(true)ÀÏ ¶§¸¸ text¸¦ º¸¿© ÁØ´Ù. + System.out.println(text); + } + } +} + +class CaptionTvTest { + public static void main(String args[]) { + CaptionTv ctv = new CaptionTv(); + ctv.channel = 10; // Á¶»ó Ŭ·¡½º·ÎºÎÅÍ »ó¼Ó¹ÞÀº ¸â¹ö + ctv.channelUp(); // Á¶»ó Ŭ·¡½º·ÎºÎÅÍ »ó¼Ó¹ÞÀº ¸â¹ö + System.out.println(ctv.channel); + ctv.displayCaption("Hello, World"); + ctv.caption = true; // ĸ¼Ç±â´ÉÀ» ÄÒ´Ù. + ctv.displayCaption("Hello, World"); // ĸ¼ÇÀ» È­¸é¿¡ º¸¿© ÁØ´Ù. + } +} diff --git a/workspace/ch07/src/CastingTest1.java b/workspace/ch07/src/CastingTest1.java new file mode 100644 index 0000000..5586790 --- /dev/null +++ b/workspace/ch07/src/CastingTest1.java @@ -0,0 +1,32 @@ +class CastingTest1 { + public static void main(String args[]) { + Car car = null; + FireEngine fe = new FireEngine(); + FireEngine fe2 = null; + + fe.water(); + car = fe; // car =(Car)fe;¿¡¼­ Çüº¯È¯ÀÌ »ý·«µÈ ÇüÅ´Ù. +// car.water(); + fe2 = (FireEngine)car; // ÀÚ¼ÕŸÀÔ ¡ç Á¶»óŸÀÔ + fe2.water(); + } +} + +class Car { + String color; + int door; + + void drive() { // ¿îÀüÇÏ´Â ±â´É + System.out.println("drive, Brrrr~"); + } + + void stop() { // ¸ØÃß´Â ±â´É + System.out.println("stop!!!"); + } +} + +class FireEngine extends Car { // ¼Ò¹æÂ÷ + void water() { // ¹°À» »Ñ¸®´Â ±â´É + System.out.println("water!!!"); + } +} diff --git a/workspace/ch07/src/CastingTest2.java b/workspace/ch07/src/CastingTest2.java new file mode 100644 index 0000000..9c45bec --- /dev/null +++ b/workspace/ch07/src/CastingTest2.java @@ -0,0 +1,13 @@ +class CastingTest2 { + public static void main(String args[]) { + Car car = new Car(); + Car car2 = null; + FireEngine fe = null; + + car.drive(); + fe = (FireEngine)car; // 8¹ø° ÁÙ. ÄÄÆÄÀÏÀº OK. ½ÇÇà ½Ã ¿¡·¯°¡ ¹ß»ý + fe.drive(); + car2 = fe; + car2.drive(); + } +} diff --git a/workspace/ch07/src/DeckTest.java b/workspace/ch07/src/DeckTest.java new file mode 100644 index 0000000..7e09572 --- /dev/null +++ b/workspace/ch07/src/DeckTest.java @@ -0,0 +1,75 @@ +class DeckTest { + public static void main(String args[]) { + Deck d = new Deck(); // Ä«µå ÇÑ ¹ú(Deck)À» ¸¸µç´Ù. + Card c = d.pick(0); // ¼¯±â Àü¿¡ Á¦ÀÏ À§ÀÇ Ä«µå¸¦ »Ì´Â´Ù. + System.out.println(c); // System.out.println(c.toString());°ú °°´Ù. + + d.shuffle(); // Ä«µå¸¦ ¼¯´Â´Ù. + c = d.pick(0); // ¼¯Àº ÈÄ¿¡ Á¦ÀÏ À§ÀÇ Ä«µå¸¦ »Ì´Â´Ù. + System.out.println(c); + } +} + +// DeckŬ·¡½º +class Deck { + final int CARD_NUM = 52; // Ä«µåÀÇ °³¼ö + Card cardArr[] = new Card[CARD_NUM]; // Card°´Ã¼ ¹è¿­À» Æ÷ÇÔ + + Deck () { // DeckÀÇ Ä«µå¸¦ ÃʱâÈ­ÇÑ´Ù. + int i=0; + + for(int k=Card.KIND_MAX; k > 0; k--) + for(int n=0; n < Card.NUM_MAX ; n++) + cardArr[i++] = new Card(k, n+1); + } + + Card pick(int index) { // ÁöÁ¤µÈ À§Ä¡(index)¿¡ ÀÖ´Â Ä«µå Çϳª¸¦ ²¨³»¼­ ¹Ýȯ + return cardArr[index]; + } + + Card pick() { // Deck¿¡¼­ Ä«µå Çϳª¸¦ ¼±ÅÃÇÑ´Ù. + int index = (int)(Math.random() * CARD_NUM); + return pick(index); + } + + void shuffle() { // Ä«µåÀÇ ¼ø¼­¸¦ ¼¯´Â´Ù. + for(int i=0; i < cardArr.length; i++) { + int r = (int)(Math.random() * CARD_NUM); + + Card temp = cardArr[i]; + cardArr[i] = cardArr[r]; + cardArr[r] = temp; + } + } +} // DeckŬ·¡½ºÀÇ ³¡ + +// CardŬ·¡½º +class Card { + static final int KIND_MAX = 4; // Ä«µå ¹«´ÌÀÇ ¼ö + static final int NUM_MAX = 13; // ¹«´Ìº° Ä«µå ¼ö + + static final int SPADE = 4; + static final int DIAMOND = 3; + static final int HEART = 2; + static final int CLOVER = 1; + + int kind; + int number; + + Card() { + this(SPADE, 1); + } + + Card(int kind, int number) { + this.kind = kind; + this.number = number; + } + + public String toString() { + String[] kinds = {"", "CLOVER", "HEART", "DIAMOND", "SPADE"}; + String numbers = "0123456789XJQK"; // ¼ýÀÚ 10Àº X·Î Ç¥Çö + + return "kind : " + kinds[this.kind] + + ", number : " + numbers.charAt(this.number); + } // toString()ÀÇ ³¡ +} // CardŬ·¡½ºÀÇ ³¡ diff --git a/workspace/ch07/src/DefaultMethodTest.java b/workspace/ch07/src/DefaultMethodTest.java new file mode 100644 index 0000000..db20543 --- /dev/null +++ b/workspace/ch07/src/DefaultMethodTest.java @@ -0,0 +1,45 @@ +class DefaultMethodTest { + public static void main(String[] args) { + Child c = new Child(); + c.method1(); + c.method2(); + MyInterface.staticMethod(); + MyInterface2.staticMethod(); + } +} + +class Child extends Parent implements MyInterface, MyInterface2 { + public void method1() { + System.out.println("method1() in Child"); // ¿À¹ö¶óÀ̵ù + } +} + +class Parent { + public void method2() { + System.out.println("method2() in Parent"); + } +} + +interface MyInterface { + default void method1() { + System.out.println("method1() in MyInterface"); + } + + default void method2() { + System.out.println("method2() in MyInterface"); + } + + static void staticMethod() { + System.out.println("staticMethod() in MyInterface"); + } +} + +interface MyInterface2 { + default void method1() { + System.out.println("method1() in MyInterface2"); + } + + static void staticMethod() { + System.out.println("staticMethod() in MyInterface2"); + } +} diff --git a/workspace/ch07/src/DrawShape.java b/workspace/ch07/src/DrawShape.java new file mode 100644 index 0000000..a37edd7 --- /dev/null +++ b/workspace/ch07/src/DrawShape.java @@ -0,0 +1,69 @@ +class DrawShape { + public static void main(String[] args) { + Point[] p = { new Point(100, 100), + new Point(140, 50), + new Point(200, 100) + }; + + Triangle t = new Triangle(p); + Circle c = new Circle(new Point(150, 150), 50); + + t.draw(); // »ï°¢ÇüÀ» ±×¸°´Ù. + c.draw(); // ¿øÀ» ±×¸°´Ù. + } +} + +class Shape { + String color = "black"; + void draw() { + System.out.printf("[color=%s]%n", color); + } +} + +class Point { + int x; + int y; + + Point(int x, int y) { + this.x = x; + this.y = y; + } + + Point() { + this(0,0); + } + + String getXY() { + return "("+x+","+y+")"; // x¿Í yÀÇ °ªÀ» ¹®ÀÚ¿­·Î ¹Ýȯ + } +} + +class Circle extends Shape { + Point center; // ¿øÀÇ ¿øÁ¡ÁÂÇ¥ + int r; // ¹ÝÁö¸§ + + Circle() { + this(new Point(0, 0), 100); // Circle(Point center, int r)¸¦ È£Ãâ + } + + Circle(Point center, int r) { + this.center = center; + this.r = r; + } + + void draw() { // ¿øÀ» ±×¸®´Â ´ë½Å¿¡ ¿øÀÇ Á¤º¸¸¦ Ãâ·ÂÇϵµ·Ï Çß´Ù. + System.out.printf("[center=(%d, %d), r=%d, color=%s]%n", center.x, center.y, r, color); + } +} + +class Triangle extends Shape { + Point[] p = new Point[3]; + + Triangle(Point[] p) { + this.p = p; + } + + void draw() { + System.out.printf("[p1=%s, p2=%s, p3=%s, color=%s]%n", p[0].getXY(), p[1].getXY(), p[2].getXY(), color); + } +} diff --git a/workspace/ch07/src/FighterTest.java b/workspace/ch07/src/FighterTest.java new file mode 100644 index 0000000..134a436 --- /dev/null +++ b/workspace/ch07/src/FighterTest.java @@ -0,0 +1,36 @@ +class FighterTest { + public static void main(String[] args) { + Fighter f = new Fighter(); + + if (f instanceof Unit) { + System.out.println("f´Â UnitŬ·¡½ºÀÇ ÀÚ¼ÕÀÔ´Ï´Ù."); + } + if (f instanceof Fightable) { + System.out.println("f´Â FightableÀÎÅÍÆäÀ̽º¸¦ ±¸ÇöÇß½À´Ï´Ù."); + } + if (f instanceof Movable) { + System.out.println("f´Â MovableÀÎÅÍÆäÀ̽º¸¦ ±¸ÇöÇß½À´Ï´Ù."); + } + if (f instanceof Attackable) { + System.out.println("f´Â AttackableÀÎÅÍÆäÀ̽º¸¦ ±¸ÇöÇß½À´Ï´Ù."); + } + if (f instanceof Object) { + System.out.println("f´Â ObjectŬ·¡½ºÀÇ ÀÚ¼ÕÀÔ´Ï´Ù."); + } + } +} + +class Fighter extends Unit implements Fightable { + public void move(int x, int y) { /* ³»¿ë »ý·« */ } + public void attack(Unit u) { /* ³»¿ë »ý·« */ } +} + +class Unit { + int currentHP; // À¯´ÖÀÇ Ã¼·Â + int x; // À¯´ÖÀÇ À§Ä¡(xÁÂÇ¥) + int y; // À¯´ÖÀÇ À§Ä¡(yÁÂÇ¥) +} + +interface Fightable extends Movable, Attackable { } +interface Movable { void move(int x, int y); } +interface Attackable { void attack(Unit u); } diff --git a/workspace/ch07/src/FinalCardTest.java b/workspace/ch07/src/FinalCardTest.java new file mode 100644 index 0000000..9ea433a --- /dev/null +++ b/workspace/ch07/src/FinalCardTest.java @@ -0,0 +1,29 @@ +class Card2 { + final int NUMBER; // »ó¼öÁö¸¸ ¼±¾ð°ú ÇÔ²² ÃʱâÈ­ ÇÏÁö ¾Ê°í + final String KIND; // »ý¼ºÀÚ¿¡¼­ ´Ü Çѹø¸¸ ÃʱâÈ­ÇÒ ¼ö ÀÖ´Ù. + static int width = 100; + static int height = 250; + + Card2(String kind, int num) { + KIND = kind; + NUMBER = num; + } + + Card2() { + this("HEART", 1); + } + + public String toString() { + return KIND +" "+ NUMBER; + } +} + +class FinalCardTest { + public static void main(String args[]) { + Card2 c = new Card2("HEART", 10); +// c.NUMBER = 5; + System.out.println(c.KIND); + System.out.println(c.NUMBER); + System.out.println(c); // System.out.println(c.toString()); + } +} diff --git a/workspace/ch07/src/ImportTest.java b/workspace/ch07/src/ImportTest.java new file mode 100644 index 0000000..a524a08 --- /dev/null +++ b/workspace/ch07/src/ImportTest.java @@ -0,0 +1,16 @@ +import java.text.SimpleDateFormat; +import java.util.Date; + +class ImportTest +{ + public static void main(String[] args) + { + Date today = new Date(); + + SimpleDateFormat date = new SimpleDateFormat("yyyy/MM/dd"); + SimpleDateFormat time = new SimpleDateFormat("hh:mm:ss a"); + + System.out.println("¿À´Ã ³¯Â¥´Â " + date.format(today)); + System.out.println("ÇöÀç ½Ã°£Àº " + time.format(today)); + } +} diff --git a/workspace/ch07/src/InnerEx1.java b/workspace/ch07/src/InnerEx1.java new file mode 100644 index 0000000..a9b5f36 --- /dev/null +++ b/workspace/ch07/src/InnerEx1.java @@ -0,0 +1,25 @@ +class InnerEx1 { + class InstanceInner { + int iv = 100; +// static int cv = 100; // ¿¡·¯! staticº¯¼ö¸¦ ¼±¾ðÇÒ ¼ö ¾ø´Ù. + final static int CONST = 100; // final staticÀº »ó¼öÀ̹ǷΠÇã¿ëÇÑ´Ù. + } + + static class StaticInner { + int iv = 200; + static int cv = 200; // staticŬ·¡½º¸¸ static¸â¹ö¸¦ Á¤ÀÇÇÒ ¼ö ÀÖ´Ù. + } + + void myMethod() { + class LocalInner { + int iv = 300; +// static int cv = 300; // ¿¡·¯! staticº¯¼ö¸¦ ¼±¾ðÇÒ ¼ö ¾ø´Ù. + final static int CONST = 300; // final staticÀº »ó¼öÀ̹ǷΠÇã¿ë + } + } + + public static void main(String args[]) { + System.out.println(InstanceInner.CONST); + System.out.println(StaticInner.cv); + } +} diff --git a/workspace/ch07/src/InnerEx2.java b/workspace/ch07/src/InnerEx2.java new file mode 100644 index 0000000..737ceff --- /dev/null +++ b/workspace/ch07/src/InnerEx2.java @@ -0,0 +1,33 @@ +class InnerEx2 { + class InstanceInner {} + static class StaticInner {} + + // ÀνºÅϽº¸â¹ö °£¿¡´Â ¼­·Î Á÷Á¢ Á¢±ÙÀÌ °¡´ÉÇÏ´Ù. + InstanceInner iv = new InstanceInner(); + // static ¸â¹ö °£¿¡´Â ¼­·Î Á÷Á¢ Á¢±ÙÀÌ °¡´ÉÇÏ´Ù. + static StaticInner cv = new StaticInner(); + + static void staticMethod() { + // static¸â¹ö´Â ÀνºÅϽº¸â¹ö¿¡ Á÷Á¢ Á¢±ÙÇÒ ¼ö ¾ø´Ù. +// InstanceInner obj1 = new InstanceInner(); + StaticInner obj2 = new StaticInner(); + + // ±»ÀÌ Á¢±ÙÇÏ·Á¸é ¾Æ·¡¿Í °°ÀÌ °´Ã¼¸¦ »ý¼ºÇØ¾ß ÇÑ´Ù. + // ÀνºÅϽºÅ¬·¡½º´Â ¿ÜºÎ Ŭ·¡½º¸¦ ¸ÕÀú »ý¼ºÇؾ߸¸ »ý¼ºÇÒ ¼ö ÀÖ´Ù. + InnerEx2 outer = new InnerEx2(); + InstanceInner obj1 = outer.new InstanceInner(); + } + + void instanceMethod() { + // ÀνºÅϽº¸Þ¼­µå¿¡¼­´Â ÀνºÅϽº¸â¹ö¿Í static¸â¹ö ¸ðµÎ Á¢±Ù °¡´ÉÇÏ´Ù. + InstanceInner obj1 = new InstanceInner(); + StaticInner obj2 = new StaticInner(); + // ¸Þ¼­µå ³»¿¡ Áö¿ªÀûÀ¸·Î ¼±¾ðµÈ ³»ºÎ Ŭ·¡½º´Â ¿ÜºÎ¿¡¼­ Á¢±ÙÇÒ ¼ö ¾ø´Ù. +// LocalInner lv = new LocalInner(); + } + + void myMethod() { + class LocalInner {} + LocalInner lv = new LocalInner(); + } +} diff --git a/workspace/ch07/src/InnerEx3.java b/workspace/ch07/src/InnerEx3.java new file mode 100644 index 0000000..8e1106e --- /dev/null +++ b/workspace/ch07/src/InnerEx3.java @@ -0,0 +1,28 @@ +class InnerEx3 { + private int outerIv = 0; + static int outerCv = 0; + + class InstanceInner { + int iiv = outerIv; // ¿ÜºÎ Ŭ·¡½ºÀÇ private¸â¹öµµ Á¢±Ù°¡´ÉÇÏ´Ù. + int iiv2 = outerCv; + } + + static class StaticInner { +// ½ºÅÂƽ Ŭ·¡½º´Â ¿ÜºÎ Ŭ·¡½ºÀÇ ÀνºÅϽº¸â¹ö¿¡ Á¢±ÙÇÒ ¼ö ¾ø´Ù. +// int siv = outerIv; + static int scv = outerCv; + } + + void myMethod() { + int lv = 0; + final int LV = 0; // JDK1.8ºÎÅÍ final »ý·« °¡´É + + class LocalInner { + int liv = outerIv; + int liv2 = outerCv; +// ¿ÜºÎ Ŭ·¡½ºÀÇ Áö¿ªº¯¼ö´Â finalÀÌ ºÙÀº º¯¼ö(»ó¼ö)¸¸ Á¢±Ù°¡´ÉÇÏ´Ù. +// int liv3 = lv; // ¿¡·¯!!!(JDK1.8ºÎÅÍ ¿¡·¯ ¾Æ´Ô) + int liv4 = LV; // OK + } + } +} diff --git a/workspace/ch07/src/InnerEx4.java b/workspace/ch07/src/InnerEx4.java new file mode 100644 index 0000000..9b12ec7 --- /dev/null +++ b/workspace/ch07/src/InnerEx4.java @@ -0,0 +1,31 @@ +class Outer { + class InstanceInner { + int iv=100; + } + static class StaticInner { + int iv=200; + static int cv=300; + } + + void myMethod() { + class LocalInner { + int iv=400; + } + } +} + +class InnerEx4 { + public static void main(String[] args) { + // ÀνºÅϽºÅ¬·¡½ºÀÇ ÀνºÅϽº¸¦ »ý¼ºÇÏ·Á¸é + // ¿ÜºÎ Ŭ·¡½ºÀÇ ÀνºÅϽº¸¦ ¸ÕÀú »ý¼ºÇØ¾ß ÇÑ´Ù. + Outer oc = new Outer(); + Outer.InstanceInner ii = oc.new InstanceInner(); + + System.out.println("ii.iv : "+ ii.iv); + System.out.println("Outer.StaticInner.cv : " + Outer.StaticInner.cv); + + // ½ºÅÂƽ ³»ºÎ Ŭ·¡½ºÀÇ ÀνºÅϽº´Â ¿ÜºÎ Ŭ·¡½º¸¦ ¸ÕÀú »ý¼ºÇÏÁö ¾Ê¾Æµµ µÈ´Ù. + Outer.StaticInner si = new Outer.StaticInner(); + System.out.println("si.iv : "+ si.iv); + } +} diff --git a/workspace/ch07/src/InnerEx5.java b/workspace/ch07/src/InnerEx5.java new file mode 100644 index 0000000..82ac402 --- /dev/null +++ b/workspace/ch07/src/InnerEx5.java @@ -0,0 +1,22 @@ +class Outer2 { + int value=10; // Outer.this.value + + class Inner { + int value=20; // this.value + + void method1() { + int value=30; + System.out.println(" value :" + value); + System.out.println(" this.value :" + this.value); + System.out.println("Outer2.this.value :" + Outer2.this.value); + } + } // InnerŬ·¡½ºÀÇ ³¡ +} // OuterŬ·¡½ºÀÇ ³¡ + +class InnerEx5 { + public static void main(String args[]) { + Outer2 outer = new Outer2(); + Outer2.Inner inner = outer.new Inner(); + inner.method1(); + } +} // InnerEx5 ³¡ diff --git a/workspace/ch07/src/InnerEx6.java b/workspace/ch07/src/InnerEx6.java new file mode 100644 index 0000000..e7cc874 --- /dev/null +++ b/workspace/ch07/src/InnerEx6.java @@ -0,0 +1,8 @@ +class InnerEx6 { + Object iv = new Object(){ void method(){} }; // À͸íŬ·¡½º + static Object cv = new Object(){ void method(){} }; // À͸íŬ·¡½º + + void myMethod() { + Object lv = new Object(){ void method(){} }; // À͸íŬ·¡½º + } +} diff --git a/workspace/ch07/src/InnerEx7.java b/workspace/ch07/src/InnerEx7.java new file mode 100644 index 0000000..1e7c5b3 --- /dev/null +++ b/workspace/ch07/src/InnerEx7.java @@ -0,0 +1,15 @@ +import java.awt.*; +import java.awt.event.*; + +class InnerEx7{ + public static void main(String[] args) { + Button b = new Button("Start"); + b.addActionListener(new EventHandler()); + } +} + +class EventHandler implements ActionListener { + public void actionPerformed(ActionEvent e) { + System.out.println("ActionEvent occurred!!!"); + } +} diff --git a/workspace/ch07/src/InnerEx8.java b/workspace/ch07/src/InnerEx8.java new file mode 100644 index 0000000..2ceadc2 --- /dev/null +++ b/workspace/ch07/src/InnerEx8.java @@ -0,0 +1,14 @@ +import java.awt.*; +import java.awt.event.*; + +class InnerEx8 { + public static void main(String[] args) { + Button b = new Button("Start"); + b.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + System.out.println("ActionEvent occurred!!!"); + } + } // À͸í Ŭ·¡½ºÀÇ ³¡ + ); + } // main¸Þ¼­µåÀÇ ³¡ +} // InnerEx8Ŭ·¡½ºÀÇ ³¡ diff --git a/workspace/ch07/src/InstanceofTest.java b/workspace/ch07/src/InstanceofTest.java new file mode 100644 index 0000000..481d056 --- /dev/null +++ b/workspace/ch07/src/InstanceofTest.java @@ -0,0 +1,21 @@ +class InstanceofTest { + public static void main(String args[]) { + FireEngine2 fe = new FireEngine2(); + + if(fe instanceof FireEngine2) { + System.out.println("This is a FireEngine2 instance."); + } + + if(fe instanceof Car2) { + System.out.println("This is a Car2 instance."); + } + + if(fe instanceof Object) { + System.out.println("This is an Object instance."); + } + + System.out.println(fe.getClass().getName()); // Ŭ·¡½ºÀÇ À̸§À» Ãâ·Â + } +} // class +class Car2 {} +class FireEngine2 extends Car2 {} diff --git a/workspace/ch07/src/InterfaceTest.java b/workspace/ch07/src/InterfaceTest.java new file mode 100644 index 0000000..f614579 --- /dev/null +++ b/workspace/ch07/src/InterfaceTest.java @@ -0,0 +1,18 @@ +class A { + public void methodA(B b) { + b.methodB(); + } +} + +class B { + public void methodB() { + System.out.println("methodB()"); + } +} + +class InterfaceTest { + public static void main(String args[]) { + A a = new A(); + a.methodA(new B()); + } +} diff --git a/workspace/ch07/src/InterfaceTest2.java b/workspace/ch07/src/InterfaceTest2.java new file mode 100644 index 0000000..858d821 --- /dev/null +++ b/workspace/ch07/src/InterfaceTest2.java @@ -0,0 +1,29 @@ + class A2 { + void autoPlay(I i) { + i.play(); + } + } + + interface I { + public abstract void play(); + } + + class B2 implements I { + public void play() { + System.out.println("play in B class"); + } + } + + class C2 implements I { + public void play() { + System.out.println("play in C class"); + } + } + +class InterfaceTest2 { + public static void main(String[] args) { + A2 a = new A2(); + a.autoPlay(new B2()); // void autoPlay(I i)È£Ãâ + a.autoPlay(new C2()); // void autoPlay(I i)È£Ãâ + } +} diff --git a/workspace/ch07/src/InterfaceTest3.java b/workspace/ch07/src/InterfaceTest3.java new file mode 100644 index 0000000..434f328 --- /dev/null +++ b/workspace/ch07/src/InterfaceTest3.java @@ -0,0 +1,32 @@ +class InterfaceTest3 { + public static void main(String[] args) { + A3 a = new A3(); + a.methodA(); + } +} + + class A3 { + void methodA() { + I3 i = InstanceManager.getInstance(); + i.methodB(); + System.out.println(i.toString()); // i·Î ObjectŬ·¡½ºÀÇ ¸Þ¼­µå È£Ãâ°¡´É + } + } + + interface I3 { + public abstract void methodB(); + } + + class B3 implements I3 { + public void methodB() { + System.out.println("methodB in B3 class"); + } + + public String toString() { return "class B3";} + } + + class InstanceManager { + public static I3 getInstance() { + return new B3(); + } + } diff --git a/workspace/ch07/src/PackageTest.java b/workspace/ch07/src/PackageTest.java new file mode 100644 index 0000000..14a679a --- /dev/null +++ b/workspace/ch07/src/PackageTest.java @@ -0,0 +1,7 @@ +package com.javachobo.book; + +class PackageTest { + public static void main(String[] args) { + System.out.println("Hello World!"); + } +} diff --git a/workspace/ch07/src/ParserTest.java b/workspace/ch07/src/ParserTest.java new file mode 100644 index 0000000..8e9aaa5 --- /dev/null +++ b/workspace/ch07/src/ParserTest.java @@ -0,0 +1,40 @@ +interface Parseable { + // ±¸¹® ºÐ¼®ÀÛ¾÷À» ¼öÇàÇÑ´Ù. + public abstract void parse(String fileName); +} + +class ParserManager { + // ¸®ÅÏŸÀÔÀÌ ParseableÀÎÅÍÆäÀ̽ºÀÌ´Ù. + public static Parseable getParser(String type) { + if(type.equals("XML")) { + return new XMLParser(); + } else { + Parseable p = new HTMLParser(); + return p; + // return new HTMLParser(); + } + } +} + +class XMLParser implements Parseable { + public void parse(String fileName) { + /* ±¸¹® ºÐ¼®ÀÛ¾÷À» ¼öÇàÇÏ´Â Äڵ带 Àû´Â´Ù. */ + System.out.println(fileName + "- XML parsing completed."); + } +} + +class HTMLParser implements Parseable { + public void parse(String fileName) { + /* ±¸¹® ºÐ¼®ÀÛ¾÷À» ¼öÇàÇÏ´Â Äڵ带 Àû´Â´Ù. */ + System.out.println(fileName + "-HTML parsing completed."); + } +} + +class ParserTest { + public static void main(String args[]) { + Parseable parser = ParserManager.getParser("XML"); + parser.parse("document.xml"); + parser = ParserManager.getParser("HTML"); + parser.parse("document2.html"); + } +} diff --git a/workspace/ch07/src/PointTest.java b/workspace/ch07/src/PointTest.java new file mode 100644 index 0000000..e5ea879 --- /dev/null +++ b/workspace/ch07/src/PointTest.java @@ -0,0 +1,34 @@ +class PointTest { + public static void main(String args[]) { + Point3D p3 = new Point3D(1,2,3); + } +} + +class Point2 { + int x; + int y; + + Point2(int x, int y) { + this.x = x; + this.y = y; + } + + String getLocation() { + return "x :" + x + ", y :"+ y; + } +} + +class Point3D extends Point2 { + int z; + + Point3D(int x, int y, int z) { + + this.x = x; + this.y = y; + this.z = z; + } + + String getLocation() { // ¿À¹ö¶óÀ̵ù + return "x :" + x + ", y :"+ y + ", z :" + z; + } +} diff --git a/workspace/ch07/src/PointTest2.java b/workspace/ch07/src/PointTest2.java new file mode 100644 index 0000000..84ff993 --- /dev/null +++ b/workspace/ch07/src/PointTest2.java @@ -0,0 +1,32 @@ +class PointTest2 { + public static void main(String argsp[]) { + Point3D2 p3 = new Point3D2(); + System.out.println("p3.x=" + p3.x); + System.out.println("p3.y=" + p3.y); + System.out.println("p3.z=" + p3.z); + } +} + +class Point3 { + int x=10; + int y=20; + + Point3(int x, int y) { + + this.x = x; + this.y = y; + } +} + +class Point3D2 extends Point3 { + int z=30; + + Point3D2() { + this(100, 200, 300); // Point3D2(int x, int y, int z)¸¦ È£ÃâÇÑ´Ù. + } + + Point3D2(int x, int y, int z) { + super(x, y); // Point3(int x, int y)¸¦ È£ÃâÇÑ´Ù. + this.z = z; + } +} diff --git a/workspace/ch07/src/PolyArgumentTest.java b/workspace/ch07/src/PolyArgumentTest.java new file mode 100644 index 0000000..5d297f5 --- /dev/null +++ b/workspace/ch07/src/PolyArgumentTest.java @@ -0,0 +1,58 @@ +class Product { + int price; // Á¦Ç°ÀÇ °¡°Ý + int bonusPoint; // Á¦Ç°±¸¸Å ½Ã Á¦°øÇÏ´Â º¸³Ê½ºÁ¡¼ö + + Product(int price) { + this.price = price; + bonusPoint =(int)(price/10.0); // º¸³Ê½ºÁ¡¼ö´Â Á¦Ç°°¡°ÝÀÇ 10% + } +} + +class Tv3 extends Product { + Tv3() { + // Á¶»óŬ·¡½ºÀÇ »ý¼ºÀÚ Product(int price)¸¦ È£ÃâÇÑ´Ù. + super(100); // TvÀÇ °¡°ÝÀ» 100¸¸¿øÀ¸·Î ÇÑ´Ù. + } + + public String toString() { // ObjectŬ·¡½ºÀÇ toString()À» ¿À¹ö¶óÀ̵ùÇÑ´Ù. + return "Tv"; + } +} + +class Computer extends Product { + Computer() { + super(200); + } + + public String toString() { + return "Computer"; + } +} + +class Buyer { // °í°´, ¹°°ÇÀ» »ç´Â »ç¶÷ + int money = 1000; // ¼ÒÀ¯±Ý¾× + int bonusPoint = 0; // º¸³Ê½ºÁ¡¼ö + + void buy(Product p) { + if(money < p.price) { + System.out.println("Àܾ×ÀÌ ºÎÁ·ÇÏ¿© ¹°°ÇÀ» »ì¼ö ¾ø½À´Ï´Ù."); + return; + } + + money -= p.price; // °¡Áø µ·¿¡¼­ ±¸ÀÔÇÑ Á¦Ç°ÀÇ °¡°ÝÀ» »«´Ù. + bonusPoint += p.bonusPoint; // Á¦Ç°ÀÇ º¸³Ê½º Á¡¼ö¸¦ Ãß°¡ÇÑ´Ù. + System.out.println(p + "À»/¸¦ ±¸ÀÔÇϼ̽À´Ï´Ù."); + } +} + +class PolyArgumentTest { + public static void main(String args[]) { + Buyer b = new Buyer(); + + b.buy(new Tv3()); + b.buy(new Computer()); + + System.out.println("ÇöÀç ³²Àº µ·Àº " + b.money + "¸¸¿øÀÔ´Ï´Ù."); + System.out.println("ÇöÀç º¸³Ê½ºÁ¡¼ö´Â " + b.bonusPoint + "Á¡ÀÔ´Ï´Ù."); + } +} diff --git a/workspace/ch07/src/PolyArgumentTest2.java b/workspace/ch07/src/PolyArgumentTest2.java new file mode 100644 index 0000000..a394787 --- /dev/null +++ b/workspace/ch07/src/PolyArgumentTest2.java @@ -0,0 +1,75 @@ +class Product2 { + int price; // Á¦Ç°ÀÇ °¡°Ý + int bonusPoint; // Á¦Ç°±¸¸Å ½Ã Á¦°øÇÏ´Â º¸³Ê½ºÁ¡¼ö + + Product2(int price) { + this.price = price; + bonusPoint =(int)(price/10.0); + } + + Product2() {} // ±âº» »ý¼ºÀÚ +} + +class Tv4 extends Product2 { + Tv4() { + super(100); + } + + public String toString() { return "Tv"; } +} + +class Computer2 extends Product2 { + Computer2() { super(200); } + + public String toString() { return "Computer"; } +} + +class Audio extends Product2 { + Audio() { super(50); } + + public String toString() { return "Audio"; } +} + +class Buyer2 { // °í°´, ¹°°ÇÀ» »ç´Â »ç¶÷ + int money = 1000; // ¼ÒÀ¯±Ý¾× + int bonusPoint = 0; // º¸³Ê½ºÁ¡¼ö + Product2[] item = new Product2[10]; // ±¸ÀÔÇÑ Á¦Ç°À» ÀúÀåÇϱâ À§ÇÑ ¹è¿­ + int i =0; // Product¹è¿­¿¡ »ç¿ëµÉ Ä«¿îÅÍ + + void buy(Product2 p) { + if(money < p.price) { + System.out.println("Àܾ×ÀÌ ºÎÁ·ÇÏ¿© ¹°°ÇÀ» »ì¼ö ¾ø½À´Ï´Ù."); + return; + } + + money -= p.price; // °¡Áø µ·¿¡¼­ ±¸ÀÔÇÑ Á¦Ç°ÀÇ °¡°ÝÀ» »«´Ù. + bonusPoint += p.bonusPoint; // Á¦Ç°ÀÇ º¸³Ê½º Á¡¼ö¸¦ Ãß°¡ÇÑ´Ù. + item[i++] = p; // Á¦Ç°À» Product[] item¿¡ ÀúÀåÇÑ´Ù. + System.out.println(p + "À»/¸¦ ±¸ÀÔÇϼ̽À´Ï´Ù."); + } + + void summary() { // ±¸¸ÅÇÑ ¹°Ç°¿¡ ´ëÇÑ Á¤º¸¸¦ ¿ä¾àÇؼ­ º¸¿© ÁØ´Ù. + int sum = 0; // ±¸ÀÔÇÑ ¹°Ç°ÀÇ °¡°ÝÇÕ°è + String itemList =""; // ±¸ÀÔÇÑ ¹°Ç°¸ñ·Ï + + // ¹Ýº¹¹®À» ÀÌ¿ëÇؼ­ ±¸ÀÔÇÑ ¹°Ç°ÀÇ ÃÑ °¡°Ý°ú ¸ñ·ÏÀ» ¸¸µç´Ù. + for(int i=0; i + + + + + diff --git a/workspace/ch08/.project b/workspace/ch08/.project new file mode 100644 index 0000000..b006897 --- /dev/null +++ b/workspace/ch08/.project @@ -0,0 +1,17 @@ + + + ch08 + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/workspace/ch08/.settings/org.eclipse.jdt.core.prefs b/workspace/ch08/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..3a21537 --- /dev/null +++ b/workspace/ch08/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,11 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/workspace/ch08/src/ChainedExceptionEx.java b/workspace/ch08/src/ChainedExceptionEx.java new file mode 100644 index 0000000..a1a29ff --- /dev/null +++ b/workspace/ch08/src/ChainedExceptionEx.java @@ -0,0 +1,69 @@ +class ChainedExceptionEx { + public static void main(String args[]) { + try { + install(); + } catch(InstallException e) { + e.printStackTrace(); + } catch(Exception e) { + e.printStackTrace(); + } + } // mainÀÇ ³¡ + + static void install() throws InstallException { + try { + startInstall(); // ÇÁ·Î±×·¥ ¼³Ä¡¿¡ ÇÊ¿äÇÑ Áغñ¸¦ ÇÑ´Ù. + copyFiles(); // ÆÄÀϵéÀ» º¹»çÇÑ´Ù. + } catch (SpaceException2 e) { + InstallException ie = new InstallException("¼³Ä¡Áß ¿¹¿Ü¹ß»ý"); + ie.initCause(e); + throw ie; + } catch (MemoryException2 me) { + InstallException ie = new InstallException("¼³Ä¡Áß ¿¹¿Ü¹ß»ý"); + ie.initCause(me); + throw ie; + } finally { + deleteTempFiles(); // ÇÁ·Î±×·¥ ¼³Ä¡¿¡ »ç¿ëµÈ ÀÓ½ÃÆÄÀϵéÀ» »èÁ¦ÇÑ´Ù. + } // tryÀÇ ³¡ + } + +static void startInstall() throws SpaceException2, MemoryException2 { + if(!enoughSpace()) { // ÃæºÐÇÑ ¼³Ä¡ °ø°£ÀÌ ¾øÀ¸¸é... + throw new SpaceException2("¼³Ä¡ÇÒ °ø°£ÀÌ ºÎÁ·ÇÕ´Ï´Ù."); + } + + if (!enoughMemory()) { // ÃæºÐÇÑ ¸Þ¸ð¸®°¡ ¾øÀ¸¸é... + throw new MemoryException2("¸Þ¸ð¸®°¡ ºÎÁ·ÇÕ´Ï´Ù."); +// throw new RuntimeException(new MemoryException("¸Þ¸ð¸®°¡ ºÎÁ·ÇÕ´Ï´Ù.")); + } +} // startInstall¸Þ¼­µåÀÇ ³¡ + + static void copyFiles() { /* ÆÄÀϵéÀ» º¹»çÇÏ´Â Äڵ带 Àû´Â´Ù. */ } + static void deleteTempFiles() { /* ÀÓ½ÃÆÄÀϵéÀ» »èÁ¦ÇÏ´Â Äڵ带 Àû´Â´Ù.*/} + + static boolean enoughSpace() { + // ¼³Ä¡Çϴµ¥ ÇÊ¿äÇÑ °ø°£ÀÌ ÀÖ´ÂÁö È®ÀÎÇÏ´Â Äڵ带 Àû´Â´Ù. + return false; + } + static boolean enoughMemory() { + // ¼³Ä¡Çϴµ¥ ÇÊ¿äÇÑ ¸Þ¸ð¸®°ø°£ÀÌ ÀÖ´ÂÁö È®ÀÎÇÏ´Â Äڵ带 Àû´Â´Ù. + return true; + } +} // ExceptionTestŬ·¡½ºÀÇ ³¡ + +class InstallException extends Exception { + InstallException(String msg) { + super(msg); + } +} + +class SpaceException2 extends Exception { + SpaceException2(String msg) { + super(msg); + } +} + +class MemoryException2 extends Exception { + MemoryException2(String msg) { + super(msg); + } +} diff --git a/workspace/ch08/src/ExceptionEx01.java b/workspace/ch08/src/ExceptionEx01.java new file mode 100644 index 0000000..2c6055e --- /dev/null +++ b/workspace/ch08/src/ExceptionEx01.java @@ -0,0 +1,16 @@ +class ExceptionEx01 { + public static void main(String[] args) + { + try { + try { } catch (Exception e) { } + } catch (Exception e) { + try { } catch (Exception e) { } // ¿¡·¯. º¯¼ö e°¡ Áߺ¹ ¼±¾ðµÇ¾ú´Ù. + } // try-catchÀÇ ³¡ + + try { + + } catch (Exception e) { + + } // try-catchÀÇ ³¡ + } // main¸Þ¼­µåÀÇ ³¡ +} diff --git a/workspace/ch08/src/ExceptionEx02.java b/workspace/ch08/src/ExceptionEx02.java new file mode 100644 index 0000000..8295e2b --- /dev/null +++ b/workspace/ch08/src/ExceptionEx02.java @@ -0,0 +1,11 @@ +class ExceptionEx02 { + public static void main(String args[]) { + int number = 100; + int result = 0; + + for(int i=0; i < 10; i++) { + result = number / (int)(Math.random() * 10); // 7¹ø° ¶óÀÎ + System.out.println(result); + } + } // mainÀÇ ³¡ +} diff --git a/workspace/ch08/src/ExceptionEx03.java b/workspace/ch08/src/ExceptionEx03.java new file mode 100644 index 0000000..afa58fd --- /dev/null +++ b/workspace/ch08/src/ExceptionEx03.java @@ -0,0 +1,15 @@ +class ExceptionEx03 { + public static void main(String args[]) { + int number = 100; + int result = 0; + + for(int i=0; i < 10; i++) { + try { + result = number / (int)(Math.random() * 10); + System.out.println(result); + } catch (ArithmeticException e) { + System.out.println("0"); + } // try-catchÀÇ ³¡ + } // forÀÇ ³¡ + } +} diff --git a/workspace/ch08/src/ExceptionEx04.java b/workspace/ch08/src/ExceptionEx04.java new file mode 100644 index 0000000..1cfcb9a --- /dev/null +++ b/workspace/ch08/src/ExceptionEx04.java @@ -0,0 +1,13 @@ +class ExceptionEx04 { + public static void main(String args[]) { + System.out.println(1); + System.out.println(2); + try { + System.out.println(3); + System.out.println(4); + } catch (Exception e) { + System.out.println(5); + } // try-catchÀÇ ³¡ + System.out.println(6); + } // main¸Þ¼­µåÀÇ ³¡ +} diff --git a/workspace/ch08/src/ExceptionEx05.java b/workspace/ch08/src/ExceptionEx05.java new file mode 100644 index 0000000..31f8d42 --- /dev/null +++ b/workspace/ch08/src/ExceptionEx05.java @@ -0,0 +1,14 @@ +class ExceptionEx05 { + public static void main(String args[]) { + System.out.println(1); + System.out.println(2); + try { + System.out.println(3); + System.out.println(0/0); + System.out.println(4); // ½ÇÇàµÇÁö ¾Ê´Â´Ù. + } catch (ArithmeticException ae) { + System.out.println(5); + } // try-catchÀÇ ³¡ + System.out.println(6); + } // main¸Þ¼­µåÀÇ ³¡ +} diff --git a/workspace/ch08/src/ExceptionEx06.java b/workspace/ch08/src/ExceptionEx06.java new file mode 100644 index 0000000..024fc6a --- /dev/null +++ b/workspace/ch08/src/ExceptionEx06.java @@ -0,0 +1,14 @@ +class ExceptionEx06 { + public static void main(String args[]) { + System.out.println(1); + System.out.println(2); + try { + System.out.println(3); + System.out.println(0/0); + System.out.println(4); // ½ÇÇàµÇÁö ¾Ê´Â´Ù. + } catch (Exception e) { // ArithmeticException´ë½Å ExceptionÀ» »ç¿ë. + System.out.println(5); + } // try-catchÀÇ ³¡ + System.out.println(6); + } // main¸Þ¼­µåÀÇ ³¡ +} diff --git a/workspace/ch08/src/ExceptionEx07.java b/workspace/ch08/src/ExceptionEx07.java new file mode 100644 index 0000000..c825ee4 --- /dev/null +++ b/workspace/ch08/src/ExceptionEx07.java @@ -0,0 +1,18 @@ +class ExceptionEx07 { + public static void main(String args[]) { + System.out.println(1); + System.out.println(2); + try { + System.out.println(3); + System.out.println(0/0); + System.out.println(4); // ½ÇÇàµÇÁö ¾Ê´Â´Ù. + } catch (ArithmeticException ae) { + if (ae instanceof ArithmeticException) + System.out.println("true"); + System.out.println("ArithmeticException"); + } catch (Exception e) { + System.out.println("Exception"); + } // try-catchÀÇ ³¡ + System.out.println(6); + } // main¸Þ¼­µåÀÇ ³¡ +} diff --git a/workspace/ch08/src/ExceptionEx08.java b/workspace/ch08/src/ExceptionEx08.java new file mode 100644 index 0000000..5e51bc3 --- /dev/null +++ b/workspace/ch08/src/ExceptionEx08.java @@ -0,0 +1,15 @@ +class ExceptionEx08 { + public static void main(String args[]) { + System.out.println(1); + System.out.println(2); + try { + System.out.println(3); + System.out.println(0/0); // ¿¹¿Ü¹ß»ý!!! + System.out.println(4); // ½ÇÇàµÇÁö ¾Ê´Â´Ù. + } catch (ArithmeticException ae) { + ae.printStackTrace(); + System.out.println("¿¹¿Ü¸Þ½ÃÁö : " + ae.getMessage()); + } // try-catchÀÇ ³¡ + System.out.println(6); + } // main¸Þ¼­µåÀÇ ³¡ +} diff --git a/workspace/ch08/src/ExceptionEx09.java b/workspace/ch08/src/ExceptionEx09.java new file mode 100644 index 0000000..a96a5eb --- /dev/null +++ b/workspace/ch08/src/ExceptionEx09.java @@ -0,0 +1,14 @@ +class ExceptionEx09 { + public static void main(String args[]) { + try { + Exception e = new Exception("°íÀÇ·Î ¹ß»ý½ÃÄ×À½."); + throw e; // ¿¹¿Ü¸¦ ¹ß»ý½ÃÅ´ + // throw new Exception("°íÀÇ·Î ¹ß»ý½ÃÄ×À½."); + + } catch (Exception e) { + System.out.println("¿¡·¯ ¸Þ½ÃÁö : " + e.getMessage()); + e.printStackTrace(); + } + System.out.println("ÇÁ·Î±×·¥ÀÌ Á¤»ó Á¾·áµÇ¾úÀ½."); + } +} diff --git a/workspace/ch08/src/ExceptionEx10.java b/workspace/ch08/src/ExceptionEx10.java new file mode 100644 index 0000000..ae11e7b --- /dev/null +++ b/workspace/ch08/src/ExceptionEx10.java @@ -0,0 +1,5 @@ +class ExceptionEx10 { + public static void main(String[] args) { + throw new Exception(); // ExceptionÀ» °íÀÇ·Î ¹ß»ý½ÃŲ´Ù. + } +} diff --git a/workspace/ch08/src/ExceptionEx11.java b/workspace/ch08/src/ExceptionEx11.java new file mode 100644 index 0000000..5abb1b6 --- /dev/null +++ b/workspace/ch08/src/ExceptionEx11.java @@ -0,0 +1,5 @@ +class ExceptionEx11 { + public static void main(String[] args) { + throw new RuntimeException(); // RuntimeExceptionÀ» °íÀÇ·Î ¹ß»ý½ÃŲ´Ù. + } +} diff --git a/workspace/ch08/src/ExceptionEx12.java b/workspace/ch08/src/ExceptionEx12.java new file mode 100644 index 0000000..be3980b --- /dev/null +++ b/workspace/ch08/src/ExceptionEx12.java @@ -0,0 +1,13 @@ +class ExceptionEx12 { + public static void main(String[] args) throws Exception { + method1(); // °°Àº Ŭ·¡½º³»ÀÇ static¸â¹öÀ̹ǷΠ°´Ã¼»ý¼º¾øÀÌ Á÷Á¢ È£Ãâ°¡´É. + } // main¸Þ¼­µåÀÇ ³¡ + + static void method1() throws Exception { + method2(); + } // method1ÀÇ ³¡ + + static void method2() throws Exception { + throw new Exception(); + } // method2ÀÇ ³¡ +} diff --git a/workspace/ch08/src/ExceptionEx13.java b/workspace/ch08/src/ExceptionEx13.java new file mode 100644 index 0000000..8f847c2 --- /dev/null +++ b/workspace/ch08/src/ExceptionEx13.java @@ -0,0 +1,14 @@ +class ExceptionEx13 { + public static void main(String[] args) { + method1(); // °°Àº Ŭ·¡½º³»ÀÇ static¸â¹öÀ̹ǷΠ°´Ã¼»ý¼º¾øÀÌ Á÷Á¢ È£Ãâ°¡´É. + } // main¸Þ¼­µåÀÇ ³¡ + + static void method1() { + try { + throw new Exception(); + } catch (Exception e) { + System.out.println("method1¸Þ¼­µå¿¡¼­ ¿¹¿Ü°¡ 󸮵Ǿú½À´Ï´Ù."); + e.printStackTrace(); + } + } // method1ÀÇ ³¡ +} diff --git a/workspace/ch08/src/ExceptionEx14.java b/workspace/ch08/src/ExceptionEx14.java new file mode 100644 index 0000000..954a16f --- /dev/null +++ b/workspace/ch08/src/ExceptionEx14.java @@ -0,0 +1,14 @@ +class ExceptionEx14 { + public static void main(String[] args) { + try { + method1(); + } catch (Exception e) { + System.out.println("main¸Þ¼­µå¿¡¼­ ¿¹¿Ü°¡ 󸮵Ǿú½À´Ï´Ù."); + e.printStackTrace(); + } + } // main¸Þ¼­µåÀÇ ³¡ + + static void method1() throws Exception { + throw new Exception(); + } // method1()ÀÇ ³¡ +} // classÀÇ ³¡ diff --git a/workspace/ch08/src/ExceptionEx15.java b/workspace/ch08/src/ExceptionEx15.java new file mode 100644 index 0000000..8477500 --- /dev/null +++ b/workspace/ch08/src/ExceptionEx15.java @@ -0,0 +1,29 @@ +import java.io.*; + +class ExceptionEx15 { + public static void main(String[] args) { + // command line¿¡¼­ ÀԷ¹ÞÀº °ªÀ» À̸§À¸·Î °®´Â ÆÄÀÏÀ» »ý¼ºÇÑ´Ù. + File f = createFile(args[0]); + System.out.println( f.getName() + " ÆÄÀÏÀÌ ¼º°øÀûÀ¸·Î »ý¼ºµÇ¾ú½À´Ï´Ù."); + } // main¸Þ¼­µåÀÇ ³¡ + + static File createFile(String fileName) { + try { + if (fileName==null || fileName.equals("")) + throw new Exception("ÆÄÀÏÀ̸§ÀÌ À¯È¿ÇÏÁö ¾Ê½À´Ï´Ù."); + } catch (Exception e) { + // fileNameÀÌ ºÎÀûÀýÇÑ °æ¿ì, ÆÄÀÏ À̸§À» 'Á¦¸ñ¾øÀ½.txt'·Î ÇÑ´Ù. + fileName = "Á¦¸ñ¾øÀ½.txt"; + } finally { + File f = new File(fileName); // FileŬ·¡½ºÀÇ °´Ã¼¸¦ ¸¸µç´Ù. + createNewFile(f); // »ý¼ºµÈ °´Ã¼¸¦ ÀÌ¿ëÇؼ­ ÆÄÀÏÀ» »ý¼ºÇÑ´Ù. + return f; + } + } // createFile¸Þ¼­µåÀÇ ³¡ + + static void createNewFile(File f) { + try { + f.createNewFile(); // ÆÄÀÏÀ» »ý¼ºÇÑ´Ù. + } catch(Exception e){ } + } // createNewFile¸Þ¼­µåÀÇ ³¡ +} diff --git a/workspace/ch08/src/ExceptionEx16.java b/workspace/ch08/src/ExceptionEx16.java new file mode 100644 index 0000000..e176d16 --- /dev/null +++ b/workspace/ch08/src/ExceptionEx16.java @@ -0,0 +1,22 @@ +import java.io.*; + +class ExceptionEx16 { + public static void main(String[] args) + { + try { + File f = createFile(args[0]); + System.out.println( f.getName()+"ÆÄÀÏÀÌ ¼º°øÀûÀ¸·Î »ý¼ºµÇ¾ú½À´Ï´Ù."); + } catch (Exception e) { + System.out.println(e.getMessage()+" ´Ù½Ã ÀÔ·ÂÇØ Áֽñ⠹ٶø´Ï´Ù."); + } + } // main¸Þ¼­µåÀÇ ³¡ + + static File createFile(String fileName) throws Exception { + if (fileName==null || fileName.equals("")) + throw new Exception("ÆÄÀÏÀ̸§ÀÌ À¯È¿ÇÏÁö ¾Ê½À´Ï´Ù."); + File f = new File(fileName); // FileŬ·¡½ºÀÇ °´Ã¼¸¦ ¸¸µç´Ù. + // File°´Ã¼ÀÇ createNewFile¸Þ¼­µå¸¦ ÀÌ¿ëÇؼ­ ½ÇÁ¦ ÆÄÀÏÀ» »ý¼ºÇÑ´Ù. + f.createNewFile(); + return f; // »ý¼ºµÈ °´Ã¼ÀÇ ÂüÁ¶¸¦ ¹ÝȯÇÑ´Ù. + } // createFile¸Þ¼­µåÀÇ ³¡ +} // Ŭ·¡½ºÀÇ ³¡ diff --git a/workspace/ch08/src/ExceptionEx17.java b/workspace/ch08/src/ExceptionEx17.java new file mode 100644 index 0000000..a5a775b --- /dev/null +++ b/workspace/ch08/src/ExceptionEx17.java @@ -0,0 +1,19 @@ +class ExceptionEx17 { + public static void main(String[] args) + { + try { + method1(); + } catch (Exception e) { + System.out.println("main¸Þ¼­µå¿¡¼­ ¿¹¿Ü°¡ 󸮵Ǿú½À´Ï´Ù."); + } + } // main¸Þ¼­µåÀÇ ³¡ + + static void method1() throws Exception { + try { + throw new Exception(); + } catch (Exception e) { + System.out.println("method1¸Þ¼­µå¿¡¼­ ¿¹¿Ü°¡ 󸮵Ǿú½À´Ï´Ù."); + throw e; // ´Ù½Ã ¿¹¿Ü¸¦ ¹ß»ý½ÃŲ´Ù. + } + } // method1¸Þ¼­µåÀÇ ³¡ +} diff --git a/workspace/ch08/src/FinallyTest.java b/workspace/ch08/src/FinallyTest.java new file mode 100644 index 0000000..4d9359f --- /dev/null +++ b/workspace/ch08/src/FinallyTest.java @@ -0,0 +1,18 @@ +class FinallyTest { + public static void main(String args[]) { + try { + startInstall(); // ÇÁ·Î±×·¥ ¼³Ä¡¿¡ ÇÊ¿äÇÑ Áغñ¸¦ ÇÑ´Ù. + copyFiles(); // ÆÄÀϵéÀ» º¹»çÇÑ´Ù. + deleteTempFiles(); // ÇÁ·Î±×·¥ ¼³Ä¡¿¡ »ç¿ëµÈ ÀÓ½ÃÆÄÀϵéÀ» »èÁ¦ÇÑ´Ù. + } catch (Exception e) { + e.printStackTrace(); + deleteTempFiles(); // ÇÁ·Î±×·¥ ¼³Ä¡¿¡ »ç¿ëµÈ ÀÓ½ÃÆÄÀϵéÀ» »èÁ¦ÇÑ´Ù. + } // try-catchÀÇ ³¡ + } // mainÀÇ ³¡ + + static void startInstall() { + /* ÇÁ·Î±×·¥ ¼³Ä¡¿¡ ÇÊ¿äÇÑ Áغñ¸¦ ÇÏ´Â Äڵ带 Àû´Â´Ù.*/ + } + static void copyFiles() { /* ÆÄÀϵéÀ» º¹»çÇÏ´Â Äڵ带 Àû´Â´Ù. */ } + static void deleteTempFiles() { /* ÀÓ½ÃÆÄÀϵéÀ» »èÁ¦ÇÏ´Â Äڵ带 Àû´Â´Ù.*/ } +} diff --git a/workspace/ch08/src/FinallyTest2.java b/workspace/ch08/src/FinallyTest2.java new file mode 100644 index 0000000..9da1c3d --- /dev/null +++ b/workspace/ch08/src/FinallyTest2.java @@ -0,0 +1,18 @@ +class FinallyTest2 { + public static void main(String args[]) { + try { + startInstall(); // ÇÁ·Î±×·¥ ¼³Ä¡¿¡ ÇÊ¿äÇÑ Áغñ¸¦ ÇÑ´Ù. + copyFiles(); // ÆÄÀϵéÀ» º¹»çÇÑ´Ù. + } catch (Exception e) { + e.printStackTrace(); + } finally { + deleteTempFiles(); // ÇÁ·Î±×·¥ ¼³Ä¡¿¡ »ç¿ëµÈ ÀÓ½ÃÆÄÀϵéÀ» »èÁ¦ÇÑ´Ù. + } // try-catchÀÇ ³¡ + } // mainÀÇ ³¡ + + static void startInstall() { + /* ÇÁ·Î±×·¥ ¼³Ä¡¿¡ ÇÊ¿äÇÑ Áغñ¸¦ ÇÏ´Â Äڵ带 Àû´Â´Ù.*/ + } + static void copyFiles() { /* ÆÄÀϵéÀ» º¹»çÇÏ´Â Äڵ带 Àû´Â´Ù. */ } + static void deleteTempFiles() { /* ÀÓ½ÃÆÄÀϵéÀ» »èÁ¦ÇÏ´Â Äڵ带 Àû´Â´Ù.*/} +} diff --git a/workspace/ch08/src/FinallyTest3.java b/workspace/ch08/src/FinallyTest3.java new file mode 100644 index 0000000..1aaecb8 --- /dev/null +++ b/workspace/ch08/src/FinallyTest3.java @@ -0,0 +1,18 @@ +class FinallyTest3 { + public static void main(String args[]) { + // method1()Àº static¸Þ¼­µåÀ̹ǷΠÀνºÅϽº »ý¼º¾øÀÌ Á÷Á¢ È£ÃâÀÌ °¡´ÉÇÏ´Ù. + FinallyTest3.method1(); + System.out.println("method1()ÀÇ ¼öÇàÀ» ¸¶Ä¡°í main¸Þ¼­µå·Î µ¹¾Æ¿Ô½À´Ï´Ù."); + } // main¸Þ¼­µåÀÇ ³¡ + + static void method1() { + try { + System.out.println("method1()ÀÌ È£ÃâµÇ¾ú½À´Ï´Ù."); + return; // ÇöÀç ½ÇÇà ÁßÀÎ ¸Þ¼­µå¸¦ Á¾·áÇÑ´Ù. + } catch (Exception e) { + e.printStackTrace(); + } finally { + System.out.println("method1()ÀÇ finallyºí·°ÀÌ ½ÇÇàµÇ¾ú½À´Ï´Ù."); + } + } // method1¸Þ¼­µåÀÇ ³¡ +} diff --git a/workspace/ch08/src/NewExceptionTest.java b/workspace/ch08/src/NewExceptionTest.java new file mode 100644 index 0000000..2513b65 --- /dev/null +++ b/workspace/ch08/src/NewExceptionTest.java @@ -0,0 +1,50 @@ +class NewExceptionTest { + public static void main(String args[]) { + try { + startInstall(); // ÇÁ·Î±×·¥ ¼³Ä¡¿¡ ÇÊ¿äÇÑ Áغñ¸¦ ÇÑ´Ù. + copyFiles(); // ÆÄÀϵéÀ» º¹»çÇÑ´Ù. + } catch (SpaceException e) { + System.out.println("¿¡·¯ ¸Þ½ÃÁö : " + e.getMessage()); + e.printStackTrace(); + System.out.println("°ø°£À» È®º¸ÇÑ ÈÄ¿¡ ´Ù½Ã ¼³Ä¡ÇϽñ⠹ٶø´Ï´Ù."); + } catch (MemoryException me) { + System.out.println("¿¡·¯ ¸Þ½ÃÁö : " + me.getMessage()); + me.printStackTrace(); + System.gc(); // Garbage CollectionÀ» ¼öÇàÇÏ¿© ¸Þ¸ð¸®¸¦ ´Ã·ÁÁØ´Ù. + System.out.println("´Ù½Ã ¼³Ä¡¸¦ ½ÃµµÇϼ¼¿ä."); + } finally { + deleteTempFiles(); // ÇÁ·Î±×·¥ ¼³Ä¡¿¡ »ç¿ëµÈ ÀÓ½ÃÆÄÀϵéÀ» »èÁ¦ÇÑ´Ù. + } // tryÀÇ ³¡ + } // mainÀÇ ³¡ + + static void startInstall() throws SpaceException, MemoryException { + if(!enoughSpace()) // ÃæºÐÇÑ ¼³Ä¡ °ø°£ÀÌ ¾øÀ¸¸é... + throw new SpaceException("¼³Ä¡ÇÒ °ø°£ÀÌ ºÎÁ·ÇÕ´Ï´Ù."); + if (!enoughMemory()) // ÃæºÐÇÑ ¸Þ¸ð¸®°¡ ¾øÀ¸¸é... + throw new MemoryException("¸Þ¸ð¸®°¡ ºÎÁ·ÇÕ´Ï´Ù."); + } // startInstall¸Þ¼­µåÀÇ ³¡ + + static void copyFiles() { /* ÆÄÀϵéÀ» º¹»çÇÏ´Â Äڵ带 Àû´Â´Ù. */ } + static void deleteTempFiles() { /* ÀÓ½ÃÆÄÀϵéÀ» »èÁ¦ÇÏ´Â Äڵ带 Àû´Â´Ù.*/} + + static boolean enoughSpace() { + // ¼³Ä¡Çϴµ¥ ÇÊ¿äÇÑ °ø°£ÀÌ ÀÖ´ÂÁö È®ÀÎÇÏ´Â Äڵ带 Àû´Â´Ù. + return false; + } + static boolean enoughMemory() { + // ¼³Ä¡Çϴµ¥ ÇÊ¿äÇÑ ¸Þ¸ð¸®°ø°£ÀÌ ÀÖ´ÂÁö È®ÀÎÇÏ´Â Äڵ带 Àû´Â´Ù. + return true; + } +} // ExceptionTestŬ·¡½ºÀÇ ³¡ + +class SpaceException extends Exception { + SpaceException(String msg) { + super(msg); + } +} + +class MemoryException extends Exception { + MemoryException(String msg) { + super(msg); + } +} diff --git a/workspace/ch08/src/TryWithResourceEx.java b/workspace/ch08/src/TryWithResourceEx.java new file mode 100644 index 0000000..bd83c10 --- /dev/null +++ b/workspace/ch08/src/TryWithResourceEx.java @@ -0,0 +1,43 @@ +class TryWithResourceEx { + public static void main(String args[]) { + + try (CloseableResource cr = new CloseableResource()) { + cr.exceptionWork(false); // ¿¹¿Ü°¡ ¹ß»ýÇÏÁö ¾Ê´Â´Ù. + } catch(WorkException e) { + e.printStackTrace(); + } catch(CloseException e) { + e.printStackTrace(); + } + System.out.println(); + + try (CloseableResource cr = new CloseableResource()) { + cr.exceptionWork(true); // ¿¹¿Ü°¡ ¹ß»ýÇÑ´Ù. + } catch(WorkException e) { + e.printStackTrace(); + } catch(CloseException e) { + e.printStackTrace(); + } + } // mainÀÇ ³¡ +} + +class CloseableResource implements AutoCloseable { + public void exceptionWork(boolean exception) throws WorkException { + System.out.println("exceptionWork("+exception+")°¡ È£ÃâµÊ"); + + if(exception) + throw new WorkException("WorkException¹ß»ý!!!"); + } + + public void close() throws CloseException { + System.out.println("close()°¡ È£ÃâµÊ"); + throw new CloseException("CloseException¹ß»ý!!!"); + } +} + +class WorkException extends Exception { + WorkException(String msg) { super(msg); } +} + +class CloseException extends Exception { + CloseException(String msg) { super(msg); } +} diff --git a/workspace/ch09/.classpath b/workspace/ch09/.classpath new file mode 100644 index 0000000..fceb480 --- /dev/null +++ b/workspace/ch09/.classpath @@ -0,0 +1,6 @@ + + + + + + diff --git a/workspace/ch09/.project b/workspace/ch09/.project new file mode 100644 index 0000000..347e3a5 --- /dev/null +++ b/workspace/ch09/.project @@ -0,0 +1,17 @@ + + + ch09 + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/workspace/ch09/.settings/org.eclipse.jdt.core.prefs b/workspace/ch09/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..3a21537 --- /dev/null +++ b/workspace/ch09/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,11 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/workspace/ch09/src/BigDecimalEx.java b/workspace/ch09/src/BigDecimalEx.java new file mode 100644 index 0000000..e26ea7f --- /dev/null +++ b/workspace/ch09/src/BigDecimalEx.java @@ -0,0 +1,34 @@ +import java.math.*; +import static java.math.BigDecimal.*; +import static java.math.RoundingMode.*; + +class BigDecimalEx { + public static void main(String[] args) throws Exception { + BigDecimal bd1 = new BigDecimal("123.456"); + BigDecimal bd2 = new BigDecimal("1.0"); + + System.out.print("bd1="+bd1); + System.out.print(",\tvalue="+bd1.unscaledValue()); + System.out.print(",\tscale="+bd1.scale()); + System.out.print(",\tprecision="+bd1.precision()); + System.out.println(); + + System.out.print("bd2="+bd2); + System.out.print(",\tvalue="+bd2.unscaledValue()); + System.out.print(",\tscale="+bd2.scale()); + System.out.print(",\tprecision="+bd2.precision()); + System.out.println(); + + + BigDecimal bd3 = bd1.multiply(bd2); + System.out.print("bd3="+bd3); + System.out.print(",\tvalue="+bd3.unscaledValue()); + System.out.print(",\tscale="+bd3.scale()); + System.out.print(",\tprecision="+bd3.precision()); + System.out.println(); + + System.out.println(bd1.divide(bd2, 2, HALF_UP)); // 123.46 + System.out.println(bd1.setScale(2, HALF_UP)); // 123.46 + System.out.println(bd1.divide(bd2, new MathContext(2, HALF_UP))); + } +} diff --git a/workspace/ch09/src/BigIntegerEx.java b/workspace/ch09/src/BigIntegerEx.java new file mode 100644 index 0000000..f619328 --- /dev/null +++ b/workspace/ch09/src/BigIntegerEx.java @@ -0,0 +1,24 @@ +import java.math.*; + +class BigIntegerEx { + public static void main(String[] args) throws Exception { +// BigInteger big = BigInteger.ONE; + + for(int i=1; i<100;i++) { // 1!ºÎÅÍ 99!±îÁö Ãâ·Â + System.out.printf("%d!=%s%n", i, calcFactorial(i)); + Thread.sleep(300); // 0.3ÃÊÀÇ Áö¿¬ + } + } + + static String calcFactorial(int n) { + return factorial(BigInteger.valueOf(n)).toString(); + } + + static BigInteger factorial(BigInteger n) { + if(n.equals(BigInteger.ZERO)) { + return BigInteger.ONE; + } else { // return n * factorial(n-1); + return n.multiply(factorial(n.subtract(BigInteger.ONE))); + } + } +} diff --git a/workspace/ch09/src/CardToString.java b/workspace/ch09/src/CardToString.java new file mode 100644 index 0000000..c781550 --- /dev/null +++ b/workspace/ch09/src/CardToString.java @@ -0,0 +1,23 @@ +class Card { + String kind; + int number; + + Card() { + this("SPADE", 1); + } + + Card(String kind, int number) { + this.kind = kind; + this.number = number; + } +} + +class CardToString { + public static void main(String[] args) { + Card2 c1 = new Card2(); + Card2 c2 = new Card2(); + + System.out.println(c1.toString()); + System.out.println(c2.toString()); + } +} diff --git a/workspace/ch09/src/CardToString2.java b/workspace/ch09/src/CardToString2.java new file mode 100644 index 0000000..2c60b44 --- /dev/null +++ b/workspace/ch09/src/CardToString2.java @@ -0,0 +1,27 @@ +class Card2 { + String kind; + int number; + + Card2() { + this("SPADE", 1); // Card(String kind, int number)¸¦ È£Ãâ + } + + Card2(String kind, int number) { + this.kind = kind; + this.number = number; + } + + public String toString() { + // CardÀνºÅϽºÀÇ kind¿Í number¸¦ ¹®ÀÚ¿­·Î ¹ÝȯÇÑ´Ù. + return "kind : " + kind + ", number : " + number; + } +} + +class CardToString2 { + public static void main(String[] args) { + Card2 c1 = new Card2(); + Card2 c2 = new Card2("HEART", 10); + System.out.println(c1.toString()); + System.out.println(c2.toString()); + } +} diff --git a/workspace/ch09/src/ClassEx1.java b/workspace/ch09/src/ClassEx1.java new file mode 100644 index 0000000..8008313 --- /dev/null +++ b/workspace/ch09/src/ClassEx1.java @@ -0,0 +1,32 @@ +final class Card3 { + String kind; + int num; + + Card3() { + this("SPADE", 1); + } + + Card3(String kind, int num) { + this.kind = kind; + this.num = num; + } + + public String toString() { + return kind + ":" + num; + } +} + +class ClassEx1 { + public static void main(String[] args) throws Exception { + Card3 c = new Card3("HEART", 3); // new¿¬»êÀÚ·Î °´Ã¼ »ý¼º + Card3 c2 = Card3.class.newInstance(); // Class°´Ã¼¸¦ ÅëÇؼ­ °´Ã¼ »ý¼º + + Class cObj = c.getClass(); + + System.out.println(c); + System.out.println(c2); + System.out.println(cObj.getName()); + System.out.println(cObj.toGenericString()); + System.out.println(cObj.toString()); + } +} diff --git a/workspace/ch09/src/CloneEx1.java b/workspace/ch09/src/CloneEx1.java new file mode 100644 index 0000000..fb35c11 --- /dev/null +++ b/workspace/ch09/src/CloneEx1.java @@ -0,0 +1,30 @@ +class Point implements Cloneable { + int x; + int y; + + Point(int x, int y) { + this.x = x; + this.y = y; + } + + public String toString() { + return "x="+x +", y="+y; + } + + public Object clone() { + Object obj = null; + try { + obj = super.clone(); // clone()Àº ¹Ýµå½Ã ¿¹¿Ü󸮸¦ ÇØÁÖ¾î¾ß ÇÑ´Ù. + } catch(CloneNotSupportedException e) {} + return obj; + } +} + +class CloneEx1 { + public static void main(String[] args){ + Point original = new Point(3, 5); + Point copy = (Point)original.clone(); // º¹Á¦(clone)Çؼ­ »õ·Î¿î °´Ã¼¸¦ »ý¼º + System.out.println(original); + System.out.println(copy); + } +} diff --git a/workspace/ch09/src/CloneEx2.java b/workspace/ch09/src/CloneEx2.java new file mode 100644 index 0000000..13ac2cf --- /dev/null +++ b/workspace/ch09/src/CloneEx2.java @@ -0,0 +1,14 @@ +import java.util.*; + +class CloneEx2 { + public static void main(String[] args){ + int[] arr = {1,2,3,4,5}; + + // ¹è¿­ arrÀ» º¹Á¦Çؼ­ °°Àº ³»¿ëÀÇ »õ·Î¿î ¹è¿­À» ¸¸µç´Ù. + int[] arrClone = arr.clone(); + arrClone[0]= 6; + + System.out.println(Arrays.toString(arr)); + System.out.println(Arrays.toString(arrClone)); + } +} diff --git a/workspace/ch09/src/EqualsEx1.java b/workspace/ch09/src/EqualsEx1.java new file mode 100644 index 0000000..d7e7007 --- /dev/null +++ b/workspace/ch09/src/EqualsEx1.java @@ -0,0 +1,28 @@ +class EqualsEx1 { + public static void main(String[] args) { + Value v1 = new Value(10); + Value v2 = new Value(10); + + if (v1.equals(v2)) { + System.out.println("v1°ú v2´Â °°½À´Ï´Ù."); + } else { + System.out.println("v1°ú v2´Â ´Ù¸¨´Ï´Ù."); + } + + v2 = v1; + + if (v1.equals(v2)) { + System.out.println("v1°ú v2´Â °°½À´Ï´Ù."); + } else { + System.out.println("v1°ú v2´Â ´Ù¸¨´Ï´Ù."); + } + } // main +} + +class Value { + int value; + + Value(int value) { + this.value = value; + } +} diff --git a/workspace/ch09/src/EqualsEx2.java b/workspace/ch09/src/EqualsEx2.java new file mode 100644 index 0000000..178e26c --- /dev/null +++ b/workspace/ch09/src/EqualsEx2.java @@ -0,0 +1,33 @@ +class Person { + long id; + + public boolean equals(Object obj) { + if(obj!=null && obj instanceof Person) { + return id ==((Person)obj).id; + } else { + return false; + } + } + + Person(long id) { + this.id = id; + } +} + +class EqualsEx2 { + public static void main(String[] args) { + Person p1 = new Person(8011081111222L); + Person p2 = new Person(8011081111222L); + + if(p1==p2) + System.out.println("p1°ú p2´Â °°Àº »ç¶÷ÀÔ´Ï´Ù."); + else + System.out.println("p1°ú p2´Â ´Ù¸¥ »ç¶÷ÀÔ´Ï´Ù."); + + if(p1.equals(p2)) + System.out.println("p1°ú p2´Â °°Àº »ç¶÷ÀÔ´Ï´Ù."); + else + System.out.println("p1°ú p2´Â ´Ù¸¥ »ç¶÷ÀÔ´Ï´Ù."); + + } +} diff --git a/workspace/ch09/src/HashCodeEx1.java b/workspace/ch09/src/HashCodeEx1.java new file mode 100644 index 0000000..af94b2d --- /dev/null +++ b/workspace/ch09/src/HashCodeEx1.java @@ -0,0 +1,12 @@ +class HashCodeEx1 { + public static void main(String[] args) { + String str1 = new String("abc"); + String str2 = new String("abc"); + + System.out.println(str1.equals(str2)); + System.out.println(str1.hashCode()); + System.out.println(str2.hashCode()); + System.out.println(System.identityHashCode(str1)); + System.out.println(System.identityHashCode(str2)); + } +} diff --git a/workspace/ch09/src/MathEx1.java b/workspace/ch09/src/MathEx1.java new file mode 100644 index 0000000..a8f914c --- /dev/null +++ b/workspace/ch09/src/MathEx1.java @@ -0,0 +1,25 @@ +import static java.lang.Math.*; +import static java.lang.System.*; + +class MathEx1 { + public static void main(String args[]) { + double val = 90.7552; + out.println("round("+ val +")=" + round(val)); // ¹Ý¿Ã¸² + + val *= 100; + out.println("round("+ val +")=" + round(val)); // ¹Ý¿Ã¸² + + out.println("round("+ val +")/100 =" + round(val)/100); // ¹Ý¿Ã¸² + out.println("round("+ val +")/100.0=" + round(val)/100.0); // ¹Ý¿Ã¸² + out.println(); + out.printf("ceil(%3.1f)=%3.1f%n", 1.1, ceil(1.1)); // ¿Ã¸² + out.printf("floor(%3.1f)=%3.1f%n", 1.5, floor(1.5)); // ¹ö¸² + out.printf("round(%3.1f)=%d%n", 1.1, round(1.1)); // ¹Ý¿Ã¸² + out.printf("round(%3.1f)=%d%n", 1.5, round(1.5)); // ¹Ý¿Ã¸² + out.printf("rint(%3.1f)=%f%n", 1.5, rint(1.5)); // ¹Ý¿Ã¸² + out.printf("round(%3.1f)=%d%n", -1.5, round(-1.5)); // ¹Ý¿Ã¸² + out.printf("rint(%3.1f)=%f%n", -1.5, rint(-1.5)); // ¹Ý¿Ã¸² + out.printf("ceil(%3.1f)=%f%n", -1.5, ceil(-1.5)); // ¿Ã¸² + out.printf("floor(%3.1f)=%f%n", -1.5, floor(-1.5)); // ¹ö¸² + } +} diff --git a/workspace/ch09/src/MathEx2.java b/workspace/ch09/src/MathEx2.java new file mode 100644 index 0000000..3b7d623 --- /dev/null +++ b/workspace/ch09/src/MathEx2.java @@ -0,0 +1,21 @@ +import static java.lang.Math.*; +import static java.lang.System.*; + +class MathEx2 { + public static void main(String args[]) { + int i = Integer.MIN_VALUE; + + out.println("i ="+i); + out.println("-i="+(-i)); + + try { + out.printf("negateExact(%d)= %d%n", 10, negateExact(10)); + out.printf("negateExact(%d)= %d%n", -10, negateExact(-10)); + + out.printf("negateExact(%d)= %d%n", i, negateExact(i)); // ¿¹¿Ü¹ß»ý + } catch(ArithmeticException e) { + // i¸¦ longŸÀÔÀ¸·Î Çüº¯È¯ ´ÙÀ½¿¡ negateExact(long a)¸¦ È£Ãâ + out.printf("negateExact(%d)= %d%n",(long)i,negateExact((long)i)); + } + } // mainÀÇ ³¡ +} diff --git a/workspace/ch09/src/MathEx3.java b/workspace/ch09/src/MathEx3.java new file mode 100644 index 0000000..5a01830 --- /dev/null +++ b/workspace/ch09/src/MathEx3.java @@ -0,0 +1,24 @@ +import static java.lang.Math.*; +import static java.lang.System.*; + +class MathEx3 { + public static void main(String args[]) { + int x1=1, y1=1; // (1, 1) + int x2=2, y2=2; // (2, 2) + + double c = sqrt(pow(x2-x1, 2) + pow(y2-y1, 2)); + double a = c * sin(PI/4); // PI/4 rad = 45 degree + double b = c * cos(PI/4); +// double b = c * cos(toRadians(45)); + + out.printf("a=%f%n", a); + out.printf("b=%f%n", b); + out.printf("c=%f%n", c); + out.printf("angle=%f rad%n", atan2(a,b)); + out.printf("angle=%f degree%n%n", atan2(a,b) * 180 / PI); +// out.printf("angle=%f degree%n%n", toDegrees(atan2(a,b))); + + out.printf("24 * log10(2)=%f%n", 24 * log10(2)); // 7.224720 + out.printf("53 * log10(2)=%f%n%n", 53 * log10(2)); // 15.954590 + } +} diff --git a/workspace/ch09/src/ObjectsTest.java b/workspace/ch09/src/ObjectsTest.java new file mode 100644 index 0000000..79b7191 --- /dev/null +++ b/workspace/ch09/src/ObjectsTest.java @@ -0,0 +1,34 @@ +import java.util.*; +import static java.util.Objects.*; // ObjectsŬ·¡½ºÀÇ ¸Þ¼­µå¸¦ static import + +class ObjectsTest { + public static void main(String[] args) { + String[][] str2D = new String[][]{{"aaa","bbb"},{"AAA","BBB"}}; + String[][] str2D_2 = new String[][]{{"aaa","bbb"},{"AAA","BBB"}}; + + System.out.print("str2D ={"); + for(String[] tmp : str2D) + System.out.print(Arrays.toString(tmp)); + System.out.println("}"); + + System.out.print("str2D_2={"); + for(String[] tmp : str2D_2) + System.out.print(Arrays.toString(tmp)); + System.out.println("}"); + + System.out.println("equals(str2D, str2D_2)="+Objects.equals(str2D, str2D_2)); + System.out.println("deepEquals(str2D, str2D_2)="+Objects.deepEquals(str2D, str2D_2)); + + System.out.println("isNull(null) ="+isNull(null)); + System.out.println("nonNull(null)="+nonNull(null)); + System.out.println("hashCode(null)="+Objects.hashCode(null)); + System.out.println("toString(null)="+Objects.toString(null)); + System.out.println("toString(null, \"\")="+Objects.toString(null, "")); + + Comparator c = String.CASE_INSENSITIVE_ORDER; + + System.out.println("compare(\"aa\",\"bb\")="+compare("aa","bb",c)); + System.out.println("compare(\"bb\",\"aa\")="+compare("bb","aa",c)); + System.out.println("compare(\"ab\",\"AB\")="+compare("ab","AB",c)); + } +} diff --git a/workspace/ch09/src/RandomEx1.java b/workspace/ch09/src/RandomEx1.java new file mode 100644 index 0000000..0e9b597 --- /dev/null +++ b/workspace/ch09/src/RandomEx1.java @@ -0,0 +1,17 @@ +import java.util.*; + +class RandomEx1 { + public static void main(String args[]) { + Random rand = new Random(1); + Random rand2 = new Random(1); + + System.out.println("= rand ="); + for(int i=0; i < 5; i++) + System.out.println(i + ":" + rand.nextInt()); + + System.out.println(); + System.out.println("= rand2 ="); + for(int i=0; i < 5; i++) + System.out.println(i + ":" + rand2.nextInt()); + } +} diff --git a/workspace/ch09/src/RandomEx2.java b/workspace/ch09/src/RandomEx2.java new file mode 100644 index 0000000..921676f --- /dev/null +++ b/workspace/ch09/src/RandomEx2.java @@ -0,0 +1,33 @@ +import java.util.*; + +class RandomEx2 { + public static void main(String[] args) { + Random rand = new Random(); + int[] number = new int[100]; + int[] counter = new int[10]; + + for (int i=0; i < number.length ; i++ ) { +// System.out.print(number[i] = (int)(Math.random() * 10)); +// 0<=x<10 ¹üÀ§ÀÇ Á¤¼ö x¸¦ ¹ÝȯÇÑ´Ù. + System.out.print(number[i] = rand.nextInt(10)); + } + System.out.println(); + + for (int i=0; i < number.length ; i++ ) { + counter[number[i]]++; + } + + for (int i=0; i < counter.length ; i++ ) { + System.out.println( i +"ÀÇ °³¼ö :"+ printGraph('#',counter[i]) + " " + counter[i]); + } + } + + public static String printGraph(char ch, int value) { + char[] bar = new char[value]; + + for(int i=0; i < bar.length; i++) { + bar[i] = ch; + } + return new String(bar); + } +} diff --git a/workspace/ch09/src/RandomEx3.java b/workspace/ch09/src/RandomEx3.java new file mode 100644 index 0000000..7beedcc --- /dev/null +++ b/workspace/ch09/src/RandomEx3.java @@ -0,0 +1,33 @@ +import java.util.*; + +class RandomEx3 { + public static void main(String[] args) { + for(int i=0; i < 10;i++) + System.out.print(getRand(5, 10)+","); + System.out.println(); + + int[] result = fillRand(new int[10], new int[]{ 2, 3, 7, 5}); + + System.out.println(Arrays.toString(result)); + } + + public static int[] fillRand(int[] arr, int from, int to) { + for(int i=0; i < arr.length; i++) { + arr[i] = getRand(from, to); + } + + return arr; + } + + public static int[] fillRand(int[] arr, int[] data) { + for(int i=0; i < arr.length; i++) { + arr[i] = data[getRand(0, data.length-1)]; + } + + return arr; + } + + public static int getRand(int from, int to) { + return (int)(Math.random() * (Math.abs(to-from)+1)) + Math.min(from, to); + } +} diff --git a/workspace/ch09/src/RandomEx4.java b/workspace/ch09/src/RandomEx4.java new file mode 100644 index 0000000..a7e9553 --- /dev/null +++ b/workspace/ch09/src/RandomEx4.java @@ -0,0 +1,33 @@ +import java.util.*; + +class RandomEx4 { + final static int RECORD_NUM = 10; // »ý¼ºÇÒ ·¹ÄÚµåÀÇ ¼ö¸¦ Á¤ÇÑ´Ù. + final static String TABLE_NAME = "TEST_TABLE"; + final static String[] CODE1 = {"010","011","017","018","019"}; + final static String[] CODE2 = {"³²ÀÚ", "¿©ÀÚ"}; + final static String[] CODE3 = {"10´ë","20´ë","30´ë","40´ë","50´ë"}; + + public static void main(String[] args) { + for(int i=0; i < RECORD_NUM; i++) { + System.out.println(" INSERT INTO "+TABLE_NAME + + " VALUES (" + + " '" + getRandArr(CODE1) + "'" + + ", '" + getRandArr(CODE2) + "'" + + ", '" + getRandArr(CODE3) + "'" + + ", " + getRand(100, 200) // 100~200 »çÀÌÀÇ °ªÀ» ¾ò´Â´Ù. + + "); "); + } + } + + public static String getRandArr(String[] arr) { + return arr[getRand(arr.length-1)]; // ¹è¿­¿¡ ÀúÀåµÈ °ª Áß Çϳª¸¦ ¹ÝȯÇÑ´Ù. + } + + public static int getRand(int n) { + return getRand(0, n); + } + + public static int getRand(int from, int to) { + return (int)(Math.random()*(Math.abs(to-from)+1))+Math.min(from, to); + } +} diff --git a/workspace/ch09/src/RegularEx1.java b/workspace/ch09/src/RegularEx1.java new file mode 100644 index 0000000..08021ee --- /dev/null +++ b/workspace/ch09/src/RegularEx1.java @@ -0,0 +1,17 @@ +import java.util.regex.*; // Pattern°ú Matcher°¡ ¼ÓÇÑ ÆÐÅ°Áö + +class RegularEx1 { + public static void main(String[] args) + { + String[] data = {"bat", "baby", "bonus", + "cA","ca", "co", "c.", "c0", "car","combat","count", + "date", "disc"}; + Pattern p = Pattern.compile("c[a-z]*"); // c·Î ½ÃÀÛÇÏ´Â ¼Ò¹®ÀÚ¿µ´Ü¾î + + for(int i=0; i < data.length; i++) { + Matcher m = p.matcher(data[i]); + if(m.matches()) + System.out.print(data[i] + ","); + } + } +} diff --git a/workspace/ch09/src/RegularEx2.java b/workspace/ch09/src/RegularEx2.java new file mode 100644 index 0000000..ea5835e --- /dev/null +++ b/workspace/ch09/src/RegularEx2.java @@ -0,0 +1,26 @@ +import java.util.regex.*; // Pattern°ú Matcher°¡ ¼ÓÇÑ ÆÐÅ°Áö + +class RegularEx2 { + public static void main(String[] args) { + String[] data = {"bat", "baby", "bonus", "c", "cA", + "ca", "co", "c.", "c0", "c#", + "car","combat","count", "date", "disc" + }; + String[] pattern = {".*","c[a-z]*","c[a-z]", "c[a-zA-Z]", + "c[a-zA-Z0-9]","c.","c.*","c\\.","c\\w", + "c\\d","c.*t", "[b|c].*", ".*a.*", ".*a.+", + "[b|c].{2}" + }; + + for(int x=0; x < pattern.length; x++) { + Pattern p = Pattern.compile(pattern[x]); + System.out.print("Pattern : " + pattern[x] + " °á°ú: "); + for(int i=0; i < data.length; i++) { + Matcher m = p.matcher(data[i]); + if(m.matches()) + System.out.print(data[i] + ","); + } + System.out.println(); + } + } // public static void main(String[] args) +} diff --git a/workspace/ch09/src/RegularEx3.java b/workspace/ch09/src/RegularEx3.java new file mode 100644 index 0000000..00adde0 --- /dev/null +++ b/workspace/ch09/src/RegularEx3.java @@ -0,0 +1,17 @@ +import java.util.regex.*; // Pattern°ú Matcher°¡ ¼ÓÇÑ ÆÐÅ°Áö + +class RegularEx3{ + public static void main(String[] args) { + String source = "HP:011-1111-1111, HOME:02-999-9999 "; + String pattern = "(0\\d{1,2})-(\\d{3,4})-(\\d{4})"; + + Pattern p = Pattern.compile(pattern); + Matcher m = p.matcher(source); + + int i=0; + + while(m.find()) { + System.out.println( ++i + ": " + m.group() + " -> "+ m.group(1) +", "+ m.group(2)+", "+ m.group(3)); + } + } // mainÀÇ ³¡ +} diff --git a/workspace/ch09/src/RegularEx4.java b/workspace/ch09/src/RegularEx4.java new file mode 100644 index 0000000..ffd1d3b --- /dev/null +++ b/workspace/ch09/src/RegularEx4.java @@ -0,0 +1,27 @@ +import java.util.regex.*; // Pattern°ú Matcher°¡ ¼ÓÇÑ ÆÐÅ°Áö + +class RegularEx4 { + public static void main(String[] args) { + String source = "A broken hand works, but not a broken heart."; + String pattern = "broken"; + + StringBuffer sb = new StringBuffer(); + + Pattern p = Pattern.compile(pattern); + Matcher m = p.matcher(source); + System.out.println("source:"+source); + + int i=0; + + while(m.find()) { + System.out.println(++i + "¹ø° ¸ÅĪ:" + m.start() + "~"+ m.end()); + + // brokenÀ» drunkenÀ¸·Î ġȯÇÏ¿© sb¿¡ ÀúÀåÇÑ´Ù. + m.appendReplacement(sb, "drunken"); + } + + m.appendTail(sb); + System.out.println("Replacement count : " + i); + System.out.println("result:"+sb.toString()); + } +} diff --git a/workspace/ch09/src/ScannerEx1.java b/workspace/ch09/src/ScannerEx1.java new file mode 100644 index 0000000..2d504de --- /dev/null +++ b/workspace/ch09/src/ScannerEx1.java @@ -0,0 +1,34 @@ +import java.util.*; + +class ScannerEx1 { + public static void main(String[] args) { + Scanner s = new Scanner(System.in); + String[] argArr = null; + + while(true) { + String prompt = ">>"; + System.out.print(prompt); + + // È­¸éÀ¸·ÎºÎÅÍ ¶óÀδÜÀ§·Î ÀԷ¹޴´Ù. + String input = s.nextLine(); + + input = input.trim(); // ÀԷ¹ÞÀº °ª¿¡¼­ ºÒÇÊ¿äÇÑ ¾ÕµÚ °ø¹éÀ» Á¦°ÅÇÑ´Ù. + argArr = input.split(" +"); // ÀԷ¹ÞÀº ³»¿ëÀ» °ø¹éÀ» ±¸ºÐÀÚ·Î ÀÚ¸¥´Ù. + + String command = argArr[0].trim(); + + if("".equals(command)) continue; + + // ¸í·É¾î¸¦ ¼Ò¹®ÀÚ·Î ¹Ù²Û´Ù. + command = command.toLowerCase(); + + // q ¶Ç´Â Q¸¦ ÀÔ·ÂÇÏ¸é ½ÇÇàÁ¾·áÇÑ´Ù. + if(command.equals("q")) { + System.exit(0); + } else { + for(int i=0; i < argArr.length;i++) + System.out.println(argArr[i]); + } + } // while(true) + } // main +} diff --git a/workspace/ch09/src/ScannerEx2.java b/workspace/ch09/src/ScannerEx2.java new file mode 100644 index 0000000..bb1e373 --- /dev/null +++ b/workspace/ch09/src/ScannerEx2.java @@ -0,0 +1,18 @@ +import java.util.Scanner; +import java.io.File; + +class ScannerEx2 { + public static void main(String[] args) throws Exception { + Scanner sc = new Scanner(new File("data2.txt")); + int sum = 0; + int cnt = 0; + + while (sc.hasNextInt()) { + sum += sc.nextInt(); + cnt++; + } + + System.out.println("sum="+sum); + System.out.println("average="+ (double)sum/cnt); + } +} diff --git a/workspace/ch09/src/ScannerEx3.java b/workspace/ch09/src/ScannerEx3.java new file mode 100644 index 0000000..a928ca6 --- /dev/null +++ b/workspace/ch09/src/ScannerEx3.java @@ -0,0 +1,24 @@ +import java.util.Scanner; +import java.io.File; + +class ScannerEx3 { + public static void main(String[] args) throws Exception { + Scanner sc = new Scanner(new File("data3.txt")); + int cnt = 0; + int totalSum = 0; + + while (sc.hasNextLine()) { + String line = sc.nextLine(); + Scanner sc2 = new Scanner(line).useDelimiter(","); + int sum = 0; + + while(sc2.hasNextInt()) { + sum += sc2.nextInt(); + } + System.out.println(line + ", sum = "+ sum); + totalSum += sum; + cnt++; + } + System.out.println("Line: " + cnt + ", Total: " + totalSum); + } +} diff --git a/workspace/ch09/src/ShallowCopy.java b/workspace/ch09/src/ShallowCopy.java new file mode 100644 index 0000000..dc7548c --- /dev/null +++ b/workspace/ch09/src/ShallowCopy.java @@ -0,0 +1,70 @@ +import java.util.*; + +class Circle implements Cloneable { + Point2 p; // ¿øÁ¡ + double r; // ¹ÝÁö¸§ + + Circle(Point2 p, double r) { + this.p = p; + this.r = r; + } + + public Circle shallowCopy() { // ¾èÀº º¹»ç + Object obj = null; + + try { + obj = super.clone(); + } catch (CloneNotSupportedException e) {} + + return (Circle)obj; + } + + public Circle deepCopy() { // ±íÀº º¹»ç + Object obj = null; + + try { + obj = super.clone(); + } catch (CloneNotSupportedException e) {} + + Circle c = (Circle)obj; + c.p = new Point2(this.p.x, this.p.y); + + return c; + } + + public String toString() { + return "[p=" + p + ", r="+ r +"]"; + } +} + +class Point2 { + int x; + int y; + + Point2(int x, int y) { + this.x = x; + this.y = y; + } + + public String toString() { + return "("+x +", "+y+")"; + } +} + +class ShallowCopy { + public static void main(String[] args) { + Circle c1 = new Circle(new Point2(1, 1), 2.0); + Circle c2 = c1.shallowCopy(); + Circle c3 = c1.deepCopy(); + + System.out.println("c1="+c1); + System.out.println("c2="+c2); + System.out.println("c3="+c3); + c1.p.x = 9; + c1.p.y = 9; + System.out.println("= c1ÀÇ º¯°æ ÈÄ ="); + System.out.println("c1="+c1); + System.out.println("c2="+c2); + System.out.println("c3="+c3); + } +} diff --git a/workspace/ch09/src/StringBufferEx1.java b/workspace/ch09/src/StringBufferEx1.java new file mode 100644 index 0000000..7c97c2d --- /dev/null +++ b/workspace/ch09/src/StringBufferEx1.java @@ -0,0 +1,15 @@ +class StringBufferEx1 { + public static void main(String[] args) { + StringBuffer sb = new StringBuffer("abc"); + StringBuffer sb2 = new StringBuffer("abc"); + + System.out.println("sb == sb2 ? " + (sb == sb2)); + System.out.println("sb.equals(sb2) ? " + sb.equals(sb2)); + + // StringBufferÀÇ ³»¿ëÀ» StringÀ¸·Î º¯È¯ÇÑ´Ù. + String s = sb.toString(); // String s = new String(sb);¿Í °°´Ù. + String s2 = sb2.toString(); + + System.out.println("s.equals(s2) ? " + s.equals(s2)); + } +} diff --git a/workspace/ch09/src/StringBufferEx2.java b/workspace/ch09/src/StringBufferEx2.java new file mode 100644 index 0000000..f3c321f --- /dev/null +++ b/workspace/ch09/src/StringBufferEx2.java @@ -0,0 +1,22 @@ +class StringBufferEx2 { + public static void main(String[] args) { + StringBuffer sb = new StringBuffer("01"); + StringBuffer sb2 = sb.append(23); + sb.append('4').append(56); + + StringBuffer sb3 = sb.append(78); + sb3.append(9.0); + + System.out.println("sb ="+sb); + System.out.println("sb2="+sb2); + System.out.println("sb3="+sb3); + + System.out.println("sb ="+sb.deleteCharAt(10)); + System.out.println("sb ="+sb.delete(3,6)); + System.out.println("sb ="+sb.insert(3,"abc")); + System.out.println("sb ="+sb.replace(6, sb.length(), "END")); + + System.out.println("capacity="+sb.capacity()); + System.out.println("length="+sb.length()); + } +} diff --git a/workspace/ch09/src/StringEx1.java b/workspace/ch09/src/StringEx1.java new file mode 100644 index 0000000..bc691eb --- /dev/null +++ b/workspace/ch09/src/StringEx1.java @@ -0,0 +1,22 @@ +class StringEx1 { + public static void main(String[] args) { + String str1 = "abc"; + String str2 = "abc"; + + System.out.println("String str1 = \"abc\";"); + System.out.println("String str2 = \"abc\";"); + + System.out.println("str1 == str2 ? " + (str1 == str2)); + System.out.println("str1.equals(str2) ? " + str1.equals(str2)); + System.out.println(); + + String str3 = new String("\"abc\""); + String str4 = new String("\"abc\""); + + System.out.println("String str3 = new String(\"abc\");"); + System.out.println("String str4 = new String(\"abc\");"); + + System.out.println("str3 == str4 ? " + (str3 == str4)); + System.out.println("str3.equals(str4) ? " + str3.equals(str4)); + } +} diff --git a/workspace/ch09/src/StringEx2.java b/workspace/ch09/src/StringEx2.java new file mode 100644 index 0000000..d9070f6 --- /dev/null +++ b/workspace/ch09/src/StringEx2.java @@ -0,0 +1,8 @@ +class StringEx2 { + public static void main(String args[]) { + String s1 = "AAA"; + String s2 = "AAA"; + String s3 = "AAA"; + String s4 = "BBB"; + } +} diff --git a/workspace/ch09/src/StringEx3.java b/workspace/ch09/src/StringEx3.java new file mode 100644 index 0000000..a4a4bb3 --- /dev/null +++ b/workspace/ch09/src/StringEx3.java @@ -0,0 +1,10 @@ +class StringEx3 { + public static void main(String[] args) { + // ±æÀÌ°¡ 0ÀÎ char¹è¿­À» »ý¼ºÇÑ´Ù. + char[] cArr = new char[0]; // char[] cArr = {};¿Í °°´Ù. + String s = new String(cArr); // String s = new String("");¿Í °°´Ù. + + System.out.println("cArr.length="+cArr.length); + System.out.println("@@@"+s+"@@@"); + } +} diff --git a/workspace/ch09/src/StringEx4.java b/workspace/ch09/src/StringEx4.java new file mode 100644 index 0000000..7e3e865 --- /dev/null +++ b/workspace/ch09/src/StringEx4.java @@ -0,0 +1,16 @@ +import java.util.StringJoiner; + +class StringEx4 { + public static void main(String[] args) { + String animals = "dog,cat,bear"; + String[] arr = animals.split(","); + + System.out.println(String.join("-", arr)); + + StringJoiner sj = new StringJoiner("/","[","]"); + for(String s : arr) + sj.add(s); + + System.out.println(sj.toString()); + } +} diff --git a/workspace/ch09/src/StringEx5.java b/workspace/ch09/src/StringEx5.java new file mode 100644 index 0000000..491651c --- /dev/null +++ b/workspace/ch09/src/StringEx5.java @@ -0,0 +1,25 @@ +import java.util.StringJoiner; + +class StringEx5 { + public static void main(String[] args) throws Exception { + String str = "°¡"; + + byte[] bArr = str.getBytes("UTF-8"); + byte[] bArr2 = str.getBytes("CP949"); + + System.out.println("UTF-8:" + joinByteArr(bArr)); + System.out.println("CP949:" + joinByteArr(bArr2)); + + System.out.println("UTF-8:" + new String(bArr, "UTF-8")); + System.out.println("CP949:" + new String(bArr2, "CP949")); + } + + static String joinByteArr(byte[] bArr) { + StringJoiner sj = new StringJoiner(":", "[", "]"); + + for(byte b : bArr) + sj.add(String.format("%02X",b)); + + return sj.toString(); + } +} diff --git a/workspace/ch09/src/StringEx6.java b/workspace/ch09/src/StringEx6.java new file mode 100644 index 0000000..885351f --- /dev/null +++ b/workspace/ch09/src/StringEx6.java @@ -0,0 +1,15 @@ +class StringEx6 { + public static void main(String[] args) { + int iVal = 100; + String strVal = String.valueOf(iVal); // int¸¦ StringÀ¸·Î º¯È¯ÇÑ´Ù. + + double dVal = 200.0; + String strVal2 = dVal + ""; // int¸¦ StringÀ¸·Î º¯È¯ÇÏ´Â ¶Ç ´Ù¸¥ ¹æ¹ý + + double sum = Integer.parseInt("+"+strVal)+Double.parseDouble(strVal2); + double sum2 = Integer.valueOf(strVal) + Double.valueOf(strVal2); + + System.out.println(String.join("",strVal,"+",strVal2,"=")+sum); + System.out.println(strVal+"+"+strVal2+"="+sum2); + } +} diff --git a/workspace/ch09/src/StringEx7.java b/workspace/ch09/src/StringEx7.java new file mode 100644 index 0000000..6a91255 --- /dev/null +++ b/workspace/ch09/src/StringEx7.java @@ -0,0 +1,18 @@ +class StringEx7 { + public static void main(String[] args) { + String fullName = "Hello.java"; + + // fullName¿¡¼­ '.'ÀÇ À§Ä¡¸¦ ã´Â´Ù. + int index = fullName.indexOf('.'); + + // fullNameÀÇ Ã¹¹ø° ±ÛÀÚºÎÅÍ '.'ÀÌ ÀÖ´Â °÷±îÁö ¹®ÀÚ¿­À» ÃßÃâÇÑ´Ù. + String fileName = fullName.substring(0, index); + + // '.'ÀÇ ´ÙÀ½ ¹®ÀÚ ºÎÅÍ ½ÃÀÛÇؼ­ ¹®ÀÚ¿­ÀÇ ³¡±îÁö ÃßÃâÇÑ´Ù. + // fullName.substring(index+1, fullName.length());ÀÇ °á°ú¿Í °°´Ù. + String ext = fullName.substring(index+1); + + System.out.println(fullName + "ÀÇ È®ÀåÀÚ¸¦ Á¦¿ÜÇÑ À̸§Àº " + fileName); + System.out.println(fullName + "ÀÇ È®ÀåÀÚ´Â " + ext); + } +} diff --git a/workspace/ch09/src/StringTokenizerEx1.java b/workspace/ch09/src/StringTokenizerEx1.java new file mode 100644 index 0000000..5d0392b --- /dev/null +++ b/workspace/ch09/src/StringTokenizerEx1.java @@ -0,0 +1,12 @@ +import java.util.*; + +class StringTokenizerEx1 { + public static void main(String[] args){ + String source = "100,200,300,400"; + StringTokenizer st = new StringTokenizer(source, ","); + + while(st.hasMoreTokens()){ + System.out.println(st.nextToken()); + } + } // mainÀÇ ³¡ +} diff --git a/workspace/ch09/src/StringTokenizerEx2.java b/workspace/ch09/src/StringTokenizerEx2.java new file mode 100644 index 0000000..66ecd15 --- /dev/null +++ b/workspace/ch09/src/StringTokenizerEx2.java @@ -0,0 +1,12 @@ +import java.util.*; + +class StringTokenizerEx2 { + public static void main(String[] args) { + String expression = "x=100*(200+300)/2"; + StringTokenizer st = new StringTokenizer(expression, "+-*/=()", true); + + while(st.hasMoreTokens()){ + System.out.println(st.nextToken()); + } + } // mainÀÇ ³¡ +} diff --git a/workspace/ch09/src/StringTokenizerEx3.java b/workspace/ch09/src/StringTokenizerEx3.java new file mode 100644 index 0000000..56b30e7 --- /dev/null +++ b/workspace/ch09/src/StringTokenizerEx3.java @@ -0,0 +1,18 @@ +import java.util.*; + +class StringTokenizerEx3 { + public static void main(String args[]) { + String source = "1,±èõÀç,100,100,100|2,¹Ú¼öÀç,95,80,90|3,ÀÌÀÚ¹Ù,80,90,90"; + StringTokenizer st = new StringTokenizer(source, "|"); + + while(st.hasMoreTokens()) { + String token = st.nextToken(); + + StringTokenizer st2 = new StringTokenizer(token, ","); + while(st2.hasMoreTokens()) { + System.out.println(st2.nextToken()); + } + System.out.println("------"); + } + } // mainÀÇ ³¡ +} diff --git a/workspace/ch09/src/StringTokenizerEx4.java b/workspace/ch09/src/StringTokenizerEx4.java new file mode 100644 index 0000000..8ed77f4 --- /dev/null +++ b/workspace/ch09/src/StringTokenizerEx4.java @@ -0,0 +1,44 @@ +import java.util.*; + +class StringTokenizerEx4 { + public static void main(String args[]) { + String input = "»ï½Ê¸¸»ïõ¹é½Ê¿À"; + + System.out.println(input); + System.out.println(hangulToNum(input)); + } + + // ÇѱÛÀ» ¼ýÀÚ·Î ¹Ù²Ù´Â ¸Þ¼­µå + public static long hangulToNum(String input) { + long result = 0; // ÃÖÁ¾ º¯È¯°á°ú¸¦ ÀúÀåÇϱâ À§ÇÑ º¯¼ö + long tmpResult = 0; // ½Ê¹éõ ´ÜÀ§ÀÇ °ªÀ» ÀúÀåÇϱâ À§ÇÑ Àӽú¯¼ö + long num = 0; + + final String NUMBER = "¿µÀÏÀÌ»ï»ç¿ÀÀ°Ä¥Æȱ¸"; + final String UNIT = "½Ê¹éõ¸¸¾ïÁ¶"; + final long[] UNIT_NUM = {10,100,1000,10000,(long)1e8,(long)1e12}; + + StringTokenizer st = new StringTokenizer(input, UNIT, true); + + while(st.hasMoreTokens()) { + String token = st.nextToken(); + // ¼ýÀÚÀÎÁö, ´ÜÀ§(UNIT)ÀÎÁö È®ÀÎÇÑ´Ù. + int check = NUMBER.indexOf(token); + + if(check==-1) { // ´ÜÀ§ÀÎ °æ¿ì + if("¸¸¾ïÁ¶".indexOf(token)==-1) { + tmpResult += ( num!=0 ? num : 1) * UNIT_NUM[UNIT.indexOf(token)]; + } else { + tmpResult += num; + result += (tmpResult!=0 ? tmpResult : 1) * UNIT_NUM[UNIT.indexOf(token)]; + tmpResult = 0; + } + num = 0; + } else { // ¼ýÀÚÀÎ °æ¿ì + num = check; + } + } // end of while + + return result + tmpResult + num; + } +} diff --git a/workspace/ch09/src/StringTokenizerEx5.java b/workspace/ch09/src/StringTokenizerEx5.java new file mode 100644 index 0000000..9265ddd --- /dev/null +++ b/workspace/ch09/src/StringTokenizerEx5.java @@ -0,0 +1,21 @@ +import java.util.*; + +class StringTokenizerEx5 { + public static void main(String[] args) { + String data = "100,,,200,300"; + + String[] result = data.split(","); + StringTokenizer st = new StringTokenizer(data, ","); + + for(int i=0; i < result.length;i++) + System.out.print(result[i]+"|"); + + System.out.println("°³¼ö:"+result.length); + + int i=0; + for(;st.hasMoreTokens();i++) + System.out.print(st.nextToken()+"|"); + + System.out.println("°³¼ö:"+i); + } // main +} diff --git a/workspace/ch09/src/ToStringTest.java b/workspace/ch09/src/ToStringTest.java new file mode 100644 index 0000000..4f971c8 --- /dev/null +++ b/workspace/ch09/src/ToStringTest.java @@ -0,0 +1,11 @@ +class ToStringTest { + public static void main(String args[]) { + String str = new String("KOREA"); + java.util.Date today = new java.util.Date(); + + System.out.println(str); + System.out.println(str.toString()); + System.out.println(today); + System.out.println(today.toString()); + } +} diff --git a/workspace/ch09/src/WrapperEx1.java b/workspace/ch09/src/WrapperEx1.java new file mode 100644 index 0000000..36e7961 --- /dev/null +++ b/workspace/ch09/src/WrapperEx1.java @@ -0,0 +1,17 @@ +class WrapperEx1 { + public static void main(String[] args) { + Integer i = new Integer(100); + Integer i2 = new Integer(100); + + System.out.println("i==i2 ? "+(i==i2)); + System.out.println("i.equals(i2) ? "+i.equals(i2)); + System.out.println("i.compareTo(i2)="+i.compareTo(i2)); + System.out.println("i.toString()="+i.toString()); + + System.out.println("MAX_VALUE="+Integer.MAX_VALUE); + System.out.println("MIN_VALUE="+Integer.MIN_VALUE); + System.out.println("SIZE=" +Integer.SIZE+" bits"); + System.out.println("BYTES="+Integer.BYTES+" bytes"); + System.out.println("TYPE=" +Integer.TYPE); + } +} diff --git a/workspace/ch09/src/WrapperEx2.java b/workspace/ch09/src/WrapperEx2.java new file mode 100644 index 0000000..d6bde82 --- /dev/null +++ b/workspace/ch09/src/WrapperEx2.java @@ -0,0 +1,32 @@ +class WrapperEx2 { + public static void main(String[] args) { + int i = new Integer("100").intValue(); + int i2 = Integer.parseInt("100"); + Integer i3 = Integer.valueOf("100"); + + int i4 = Integer.parseInt("100",2); + int i5 = Integer.parseInt("100",8); + int i6 = Integer.parseInt("100",16); + int i7 = Integer.parseInt("FF", 16); +// int i8 = Integer.parseInt("FF"); // NumberFormatException¹ß»ý + + Integer i9 = Integer.valueOf("100",2); + Integer i10 = Integer.valueOf("100",8); + Integer i11 = Integer.valueOf("100",16); + Integer i12 = Integer.valueOf("FF",16); +// Integer i13 = Integer.valueOf("FF"); // NumberFormatException¹ß»ý + + System.out.println(i); + System.out.println(i2); + System.out.println(i3); + System.out.println("100(2) -> "+i4); + System.out.println("100(8) -> "+i5); + System.out.println("100(16)-> "+i6); + System.out.println("FF(16) -> "+i7); + + System.out.println("100(2) -> "+i9); + System.out.println("100(8) -> "+i10); + System.out.println("100(16)-> "+i11); + System.out.println("FF(16) -> "+i12); + } +} diff --git a/workspace/ch09/src/WrapperEx3.java b/workspace/ch09/src/WrapperEx3.java new file mode 100644 index 0000000..be3aec2 --- /dev/null +++ b/workspace/ch09/src/WrapperEx3.java @@ -0,0 +1,29 @@ +class WrapperEx3 { + public static void main(String[] args) { + int i = 10; + + // ±âº»ÇüÀ» ÂüÁ¶ÇüÀ¸·Î Çüº¯È¯(Çüº¯È¯ »ý·«°¡´É) + Integer intg = (Integer)i; // Integer intg = Integer.valueOf(i); + Object obj = (Object)i; // Object obj = (Object)Integer.valueOf(i); + + Long lng = 100L; // Long lng = new Long(100L); + + int i2 = intg + 10; // ÂüÁ¶Çü°ú ±âº»Çü°£ÀÇ ¿¬»ê °¡´É + long l = intg + lng; // ÂüÁ¶Çü °£ÀÇ µ¡¼Àµµ °¡´É + + Integer intg2 = new Integer(20); + int i3 = (int)intg2; // ÂüÁ¶ÇüÀ» ±âº»ÇüÀ¸·Î Çüº¯È¯µµ °¡´É(Çüº¯È¯ »ý·«°¡´É) + + Integer intg3 = intg2 + i3; + + System.out.println("i ="+i); + System.out.println("intg ="+intg); + System.out.println("obj ="+obj); + System.out.println("lng ="+lng); + System.out.println("intg + 10 ="+i2); + System.out.println("intg + lng ="+l); + System.out.println("intg2 ="+intg2); + System.out.println("i3 ="+i3); + System.out.println("intg2 + i3 ="+intg3); + } +} diff --git a/workspace/ch10/.classpath b/workspace/ch10/.classpath new file mode 100644 index 0000000..fceb480 --- /dev/null +++ b/workspace/ch10/.classpath @@ -0,0 +1,6 @@ + + + + + + diff --git a/workspace/ch10/.project b/workspace/ch10/.project new file mode 100644 index 0000000..fe0733f --- /dev/null +++ b/workspace/ch10/.project @@ -0,0 +1,17 @@ + + + ch10 + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/workspace/ch10/.settings/org.eclipse.jdt.core.prefs b/workspace/ch10/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..3a21537 --- /dev/null +++ b/workspace/ch10/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,11 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/workspace/ch10/src/CalendarEx1.java b/workspace/ch10/src/CalendarEx1.java new file mode 100644 index 0000000..ca90502 --- /dev/null +++ b/workspace/ch10/src/CalendarEx1.java @@ -0,0 +1,28 @@ +import java.util.*; + +class CalendarEx1 { + public static void main(String[] args) + { // ±âº»ÀûÀ¸·Î ÇöÀ糯¥¿Í ½Ã°£À¸·Î ¼³Á¤µÈ´Ù. + Calendar today = Calendar.getInstance(); + System.out.println("ÀÌ ÇØÀÇ ³âµµ : " + today.get(Calendar.YEAR)); + System.out.println("¿ù(0~11, 0:1¿ù): " + today.get(Calendar.MONTH)); + System.out.println("ÀÌ ÇØÀÇ ¸î ° ÁÖ: " + today.get(Calendar.WEEK_OF_YEAR)); + System.out.println("ÀÌ ´ÞÀÇ ¸î ° ÁÖ: " + today.get(Calendar.WEEK_OF_MONTH)); + // DATE¿Í DAY_OF_MONTH´Â °°´Ù. + System.out.println("ÀÌ ´ÞÀÇ ¸î ÀÏ: " + today.get(Calendar.DATE)); + System.out.println("ÀÌ ´ÞÀÇ ¸î ÀÏ: " + today.get(Calendar.DAY_OF_MONTH)); + System.out.println("ÀÌ ÇØÀÇ ¸î ÀÏ: " + today.get(Calendar.DAY_OF_YEAR)); + System.out.println("¿äÀÏ(1~7, 1:ÀÏ¿äÀÏ): " + today.get(Calendar.DAY_OF_WEEK)); // 1:ÀÏ¿äÀÏ, 2:¿ù¿äÀÏ, ... 7:Åä¿äÀÏ + System.out.println("ÀÌ ´ÞÀÇ ¸î ° ¿äÀÏ: " + today.get(Calendar.DAY_OF_WEEK_IN_MONTH)); + System.out.println("¿ÀÀü_¿ÀÈÄ(0:¿ÀÀü, 1:¿ÀÈÄ): " + today.get(Calendar.AM_PM)); + System.out.println("½Ã°£(0~11): " + today.get(Calendar.HOUR)); + System.out.println("½Ã°£(0~23): " + today.get(Calendar.HOUR_OF_DAY)); + System.out.println("ºÐ(0~59): " + today.get(Calendar.MINUTE)); + System.out.println("ÃÊ(0~59): " + today.get(Calendar.SECOND)); + System.out.println("1000ºÐÀÇ 1ÃÊ(0~999): " + today.get(Calendar.MILLISECOND)); + + // õºÐÀÇ 1Ãʸ¦ ½Ã°£À¸·Î Ç¥½ÃÇϱâ À§ÇØ 3600000À¸·Î ³ª´©¾ú´Ù.(1½Ã°£ = 60 * 60ÃÊ) + System.out.println("TimeZone(-12~+12): " + (today.get(Calendar.ZONE_OFFSET)/(60*60*1000))); + System.out.println("ÀÌ ´ÞÀÇ ¸¶Áö¸· ³¯: " + today.getActualMaximum(Calendar.DATE) ); // ÀÌ ´ÞÀÇ ¸¶Áö¸· ÀÏÀ» ã´Â´Ù. + } +} diff --git a/workspace/ch10/src/CalendarEx2.java b/workspace/ch10/src/CalendarEx2.java new file mode 100644 index 0000000..55ab4c2 --- /dev/null +++ b/workspace/ch10/src/CalendarEx2.java @@ -0,0 +1,26 @@ +import java.util.*; + +class CalendarEx2 { + public static void main(String[] args) { + // ¿äÀÏÀº 1ºÎÅÍ ½ÃÀÛÇϱ⠶§¹®¿¡, DAY_OF_WEEK[0]Àº ºñ¿öµÎ¾ú´Ù. + final String[] DAY_OF_WEEK = {"", "ÀÏ", "¿ù", "È­", "¼ö", "¸ñ", "±Ý", "Åä"}; + + Calendar date1 = Calendar.getInstance(); + Calendar date2 = Calendar.getInstance(); + + // monthÀÇ °æ¿ì 0ºÎÅÍ ½ÃÀÛÇϱ⠶§¹®¿¡ 8¿ùÀÎ °æ¿ì, 7·Î ÁöÁ¤ÇؾßÇÑ´Ù. + // date1.set(2015, Calendar.AUGUST, 15);¿Í °°ÀÌ ÇÒ ¼öµµ ÀÖ´Ù. + date1.set(2015, 7, 15); // 2015³â 8¿ù 15ÀÏ·Î ³¯Â¥¸¦ ¼³Á¤ÇÑ´Ù. + System.out.println("date1Àº "+ toString(date1) + DAY_OF_WEEK[date1.get(Calendar.DAY_OF_WEEK)]+"¿äÀÏÀÌ°í,"); + System.out.println("¿À´Ã(date2)Àº " + toString(date2) + DAY_OF_WEEK[date2.get(Calendar.DAY_OF_WEEK)]+"¿äÀÏÀÔ´Ï´Ù."); + + // µÎ ³¯Â¥°£ÀÇ Â÷À̸¦ ¾òÀ¸·Á¸é, getTimeInMillis() õºÐÀÇ ÀÏÃÊ ´ÜÀ§·Î º¯È¯ÇؾßÇÑ´Ù. + long difference = (date2.getTimeInMillis() - date1.getTimeInMillis())/1000; + System.out.println("±× ³¯(date1)ºÎÅÍ Áö±Ý(date2)±îÁö " + difference +"ÃÊ°¡ Áö³µ½À´Ï´Ù."); + System.out.println("ÀÏ(day)·Î °è»êÇϸé " + difference/(24*60*60) +"ÀÏÀÔ´Ï´Ù."); // 1ÀÏ = 24 * 60 * 60 + } + + public static String toString(Calendar date) { + return date.get(Calendar.YEAR)+"³â "+ (date.get(Calendar.MONTH)+1) +"¿ù " + date.get(Calendar.DATE) + "ÀÏ "; + } +} diff --git a/workspace/ch10/src/CalendarEx3.java b/workspace/ch10/src/CalendarEx3.java new file mode 100644 index 0000000..c03f9c5 --- /dev/null +++ b/workspace/ch10/src/CalendarEx3.java @@ -0,0 +1,36 @@ +import java.util.*; + +class CalendarEx3 { + public static void main(String[] args) { + final int[] TIME_UNIT = {3600, 60, 1}; // Å« ´ÜÀ§¸¦ ¾Õ¿¡ ³õ´Â´Ù. + final String[] TIME_UNIT_NAME = {"½Ã°£ ", "ºÐ ", "ÃÊ "}; + + Calendar time1 = Calendar.getInstance(); + Calendar time2 = Calendar.getInstance(); + + // time1ÀÇ ½Ã°£À» 10½Ã 20ºÐ 30ÃÊ·Î ¼³Á¤ÇÑ´Ù. + time1.set(Calendar.HOUR_OF_DAY, 10); + time1.set(Calendar.MINUTE, 20); + time1.set(Calendar.SECOND, 30); + + // time2ÀÇ ½Ã°£À» 20½Ã 30ºÐ 10ÃÊ·Î ¼³Á¤ÇÑ´Ù. + time2.set(Calendar.HOUR_OF_DAY, 20); + time2.set(Calendar.MINUTE, 30); + time2.set(Calendar.SECOND, 10); + + System.out.println("time1 :"+time1.get(Calendar.HOUR_OF_DAY)+"½Ã " + time1.get(Calendar.MINUTE) +"ºÐ " + time1.get(Calendar.SECOND) + "ÃÊ"); + System.out.println("time2 :"+time2.get(Calendar.HOUR_OF_DAY)+"½Ã " + time2.get(Calendar.MINUTE) +"ºÐ " + time2.get(Calendar.SECOND) + "ÃÊ"); + + long difference = Math.abs(time2.getTimeInMillis() - time1.getTimeInMillis())/1000; + System.out.println("time1°ú time2ÀÇ Â÷ÀÌ´Â "+ difference +"ÃÊ ÀÔ´Ï´Ù."); + + String tmp = ""; + + for(int i=0; i < TIME_UNIT.length;i++) { + tmp += difference/TIME_UNIT[i]+ TIME_UNIT_NAME[i]; + difference %= TIME_UNIT[i]; + } + + System.out.println("½ÃºÐÃÊ·Î º¯È¯Çϸé " + tmp + "ÀÔ´Ï´Ù."); + } +} diff --git a/workspace/ch10/src/CalendarEx4.java b/workspace/ch10/src/CalendarEx4.java new file mode 100644 index 0000000..264d48d --- /dev/null +++ b/workspace/ch10/src/CalendarEx4.java @@ -0,0 +1,30 @@ +import java.util.*; + +class CalendarEx4 { + public static void main(String[] args) { + Calendar date = Calendar.getInstance(); + + date.set(2005, 7, 31); // 2005³â 8¿ù 31ÀÏ + + System.out.println(toString(date)); + System.out.println("= 1ÀÏ ÈÄ ="); + date.add(Calendar.DATE, 1); + System.out.println(toString(date)); + + System.out.println("= 6´Þ Àü ="); + date.add(Calendar.MONTH, -6); + System.out.println(toString(date)); + + System.out.println("= 31ÀÏ ÈÄ(roll) ="); + date.roll(Calendar.DATE, 31); + System.out.println(toString(date)); + + System.out.println("= 31ÀÏ ÈÄ(add) ="); + date.add(Calendar.DATE, 31); + System.out.println(toString(date)); + } + + public static String toString(Calendar date) { + return date.get(Calendar.YEAR)+"³â "+ (date.get(Calendar.MONTH)+1) +"¿ù " + date.get(Calendar.DATE) + "ÀÏ"; + } +} diff --git a/workspace/ch10/src/CalendarEx5.java b/workspace/ch10/src/CalendarEx5.java new file mode 100644 index 0000000..6983705 --- /dev/null +++ b/workspace/ch10/src/CalendarEx5.java @@ -0,0 +1,16 @@ +import java.util.*; + +class CalendarEx5 { + public static void main(String[] args) { + Calendar date = Calendar.getInstance(); + + date.set(2015, 0, 31); // 2005³â 1¿ù 31ÀÏ + System.out.println(toString(date)); + date.roll(Calendar.MONTH, 1); + System.out.println(toString(date)); + } + + public static String toString(Calendar date) { + return date.get(Calendar.YEAR)+"³â "+ (date.get(Calendar.MONTH)+1) +"¿ù " + date.get(Calendar.DATE) + "ÀÏ"; + } +} diff --git a/workspace/ch10/src/CalendarEx6.java b/workspace/ch10/src/CalendarEx6.java new file mode 100644 index 0000000..7301406 --- /dev/null +++ b/workspace/ch10/src/CalendarEx6.java @@ -0,0 +1,46 @@ +import java.util.*; + +class CalendarEx6 { + public static void main(String[] args) { + if(args.length !=2) { + System.out.println("Usage : java CalendarEx6 2015 9"); + return; + } + int year = Integer.parseInt(args[0]); + int month = Integer.parseInt(args[1]); + + int START_DAY_OF_WEEK = 0; + int END_DAY = 0; + + Calendar sDay = Calendar.getInstance(); // ½ÃÀÛÀÏ + Calendar eDay = Calendar.getInstance(); // ³¡ÀÏ + + // ¿ùÀÇ °æ¿ì 0 ºÎÅÍ 11±îÁöÀÇ °ªÀ» °¡Áö¹Ç·Î 1À» »©ÁÖ¾î¾ß ÇÑ´Ù. + // ¿¹¸¦ µé¾î, 2004³â 11¿ù 1ÀÏÀº sDay.set(2004, 10, 1);°ú °°ÀÌ ÇØÁà¾ß ÇÑ´Ù. + sDay.set(year, month-1, 1); + eDay.set(year, month, 1); + + // ´ÙÀ½´ÞÀÇ Ã¹³¯¿¡¼­ ÇϷ縦 »©¸é ÇöÀç´ÞÀÇ ¸¶Áö¸· ³¯ÀÌ µÈ´Ù. + // 12¿ù 1ÀÏ¿¡¼­ ÇϷ縦 »©¸é 11¿ù 30ÀÏÀÌ µÈ´Ù. + eDay.add(Calendar.DATE, -1); + + // ù ¹ø° ¿äÀÏÀÌ ¹«½¼ ¿äÀÏÀÎÁö ¾Ë¾Æ³½´Ù. + START_DAY_OF_WEEK = sDay.get(Calendar.DAY_OF_WEEK); + // eDay¿¡ ÁöÁ¤µÈ ³¯Â¥¸¦ ¾ò¾î¿Â´Ù. + END_DAY = eDay.get(Calendar.DATE); + + System.out.println(" " + args[0] +"³â " + args[1] +"¿ù"); + System.out.println(" SU MO TU WE TH FR SA"); + + // ÇØ´ç ¿ùÀÇ 1ÀÏÀÌ ¾î´À ¿äÀÏÀÎÁö¿¡ µû¶ó¼­ °ø¹éÀ» Ãâ·ÂÇÑ´Ù. + // ¸¸ÀÏ 1ÀÏÀÌ ¼ö¿äÀÏÀ̶ó¸é °ø¹éÀ» ¼¼ ¹ø Âï´Â´Ù.(ÀÏ¿äÀϺÎÅÍ ½ÃÀÛ) + for(int i=1; i < START_DAY_OF_WEEK; i++) { + System.out.print(" "); + } + + for(int i=1, n=START_DAY_OF_WEEK ; i <= END_DAY; i++, n++) { + System.out.print((i < 10)? " "+i : " "+i ); + if(n%7==0) System.out.println(); + } + } +} diff --git a/workspace/ch10/src/CalendarEx7.java b/workspace/ch10/src/CalendarEx7.java new file mode 100644 index 0000000..d1fd22b --- /dev/null +++ b/workspace/ch10/src/CalendarEx7.java @@ -0,0 +1,37 @@ +import java.util.*; + +class CalendarEx7 { + public static void main(String[] args) { + if(args.length !=2) { + System.out.println("Usage : java CalendarEx7 2015 11"); + return; + } + + int year = Integer.parseInt(args[0]); + int month = Integer.parseInt(args[1]); + + Calendar sDay = Calendar.getInstance(); // ½ÃÀÛÀÏ + Calendar eDay = Calendar.getInstance(); // ³¡ÀÏ + + // ¿ùÀÇ °æ¿ì 0 ºÎÅÍ 11±îÁöÀÇ °ªÀ» °¡Áö¹Ç·Î 1À» »©Áà¾ßÇÑ´Ù. + // ¿¹¸¦ µé¾î, 2004³â 11¿ù 1ÀÏÀº sDay.set(2004, 10, 1);°ú °°ÀÌ ÇØÁà¾ß ÇÑ´Ù. + sDay.set(year, month-1, 1); // ÀԷ¿ùÀÇ 1ÀÏ·Î ¼³Á¤ÇÑ´Ù. + // ÀԷ¿ùÀÇ ¸»ÀÏ·Î ¼³Á¤ÇÑ´Ù. + eDay.set(year, month-1, sDay.getActualMaximum(Calendar.DATE)); + // 1ÀÏÀÌ ¼ÓÇÑ ÁÖÀÇ ÀÏ¿äÀÏ·Î ³¯Â¥¼³Á¤. + sDay.add(Calendar.DATE, -sDay.get(Calendar.DAY_OF_WEEK) + 1); + // ¸»ÀÏÀÌ ¼ÓÇÑ ÁÖÀÇ Åä¿äÀÏ·Î ³¯Â¥¼³Á¤ + eDay.add(Calendar.DATE, 7 - eDay.get(Calendar.DAY_OF_WEEK)); + + System.out.println(" " + year +"³â " + month +"¿ù"); + System.out.println(" SU MO TU WE TH FR SA"); + + //½ÃÀÛ ÀϺÎÅÍ ¸¶Áö¸· ÀϱîÁö(sDay <= eDay) 1ÀϾ¿ Áõ°¡½ÃÅ°¸é¼­ ÀÏ(Calendar.DATE)À» Ãâ·Â + for(int n=1; sDay.before(eDay) || sDay.equals(eDay); sDay.add(Calendar.DATE, 1)) { + int day = sDay.get(Calendar.DATE); + System.out.print((day < 10)? " "+day : " "+day ); + + if(n++%7==0) System.out.println(); // 7ÀÏÄ¡¸¦ Âï°í ³ª¼­ ÁÙÀ» ¹Ù²Û´Ù. + } + } // main +} diff --git a/workspace/ch10/src/CalendarEx8.java b/workspace/ch10/src/CalendarEx8.java new file mode 100644 index 0000000..f571a9d --- /dev/null +++ b/workspace/ch10/src/CalendarEx8.java @@ -0,0 +1,13 @@ +class CalendarEx8 { + public static void main(String[] args){ + String date1 = "201508"; + String date2 = "201405"; + + // ³â°ú ¿ùÀ» substringÀ¸·Î Àß¶ó¼­ Á¤¼ö·Î º¯È¯ÇÑ´Ù. + // ³â¿¡ 12¸¦ °öÇؼ­ ¿ù·Î º¯È¯ÇÑ ´ÙÀ½¿¡ »¬¼ÀÀ» ÇÏ¸é °³¿ùÂ÷¸¦ ±¸ÇÒ ¼ö ÀÖ´Ù. + int month1 = Integer.parseInt(date1.substring(0,4))* 12 + Integer.parseInt(date1.substring(4)); + int month2 = Integer.parseInt(date2.substring(0,4))* 12 + Integer.parseInt(date2.substring(4)); + + System.out.println(date1 +"°ú " + date2 + "ÀÇ Â÷ÀÌ´Â " + Math.abs(month1-month2) + "°³¿ù ÀÔ´Ï´Ù."); + } +} diff --git a/workspace/ch10/src/CalendarEx9.java b/workspace/ch10/src/CalendarEx9.java new file mode 100644 index 0000000..78f92c0 --- /dev/null +++ b/workspace/ch10/src/CalendarEx9.java @@ -0,0 +1,83 @@ +class CalendarEx9 { + public static void main(String[] args) { + System.out.println("2014. 5. 31 :" + getDayOfWeek(2014, 5, 31)); + System.out.println("2012. 6. 1 :" + getDayOfWeek(2012, 6, 1)); + System.out.println("2014. 5. 1 - 2014.4.28 :" + dayDiff(2014,5,1,2014,4,28)); + System.out.println("2015. 6. 29 : "+convertDateToDay(2015, 6, 29)); + System.out.println("735778 : "+convertDayToDate(735778)); + } + + // °¢ ´ÞÀÇ ¸¶Áö¸·ÀÏ + public static int[] endOfMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + + public static boolean isLeapYear(int year) { + return ((year%4==0)&&(year%100!=0)||(year%400==0)); + } + + public static int dayDiff(int y1, int m1, int d1, int y2, int m2, int d2) { + return convertDateToDay(y1, m1, d1) - convertDateToDay(y2, m2, d2); + } + + public static int getDayOfWeek(int year, int month, int day) { + // 1~7ÀÇ °ªÀ» ¹ÝȯÇÑ´Ù. °á°ú°¡ 1À̸é ÀÏ¿äÀÏÀÌ´Ù. + return convertDateToDay(year, month, day)%7 + 1; + } + + public static String convertDayToDate(int day) { + int year=1; + int month=0; + + while(true) { + int aYear = isLeapYear(year)? 366 :365; + if (day > aYear ) { + day-= aYear; + year++; + } else { + break; + } + } + + while(true) { + int endDay = endOfMonth[month]; + // À±³âÀÌ°í À±´ÞÀÌ Æ÷ÇԵǾî ÀÖÀ¸¸é, 1ÀÏÀ» ´õ »«´Ù. + if(isLeapYear(year) && month == 1) endDay++; + + if(day > endDay) { + day -= endDay; + month++; + } else { + break; + } + } + + return year+"-"+(month+1)+"-"+day; + } + + public static int convertDateToDay(int year, int month, int day) { + int numOfLeapYear =0; // À±³âÀÇ ¼ö + + // Àü³âµµ±îÁöÀÇ À±³âÀÇ ¼ö¸¦ ±¸ÇÑ´Ù. + for(int i=1;i < year; i++) { + if(isLeapYear(i)) + numOfLeapYear++; + } + + // Àü³âµµ±îÁöÀÇ ÀÏ ¼ö¸¦ ±¸ÇÑ´Ù. + int toLastYearDaySum = (year-1) * 365 + numOfLeapYear; + + // ¿ÃÇØÀÇ ÇöÀç ¿ù±îÁöÀÇ Àϼö °è»ê + int thisYearDaySum =0; + + for(int i=0; i < month-1; i++) { + thisYearDaySum+=endOfMonth[i]; + } + + // À±³âÀÌ°í, 2¿ùÀÌ Æ÷ÇԵǾî ÀÖÀ¸¸é 1ÀÏÀ» Áõ°¡½ÃŲ´Ù. + if (month > 2 && isLeapYear(year)) + thisYearDaySum++; + + thisYearDaySum+=day; + + return toLastYearDaySum+thisYearDaySum; + } +} diff --git a/workspace/ch10/src/ChoiceFormatEx1.java b/workspace/ch10/src/ChoiceFormatEx1.java new file mode 100644 index 0000000..c84c2c3 --- /dev/null +++ b/workspace/ch10/src/ChoiceFormatEx1.java @@ -0,0 +1,17 @@ +import java.text.*; + +class ChoiceFormatEx1 { + public static void main(String[] args) { + double[] limits = {60, 70, 80, 90}; // ³·Àº °ªºÎÅÍ Å« °ªÀÇ ¼ø¼­·Î Àû¾î¾ßÇÑ´Ù. + // limits, grades°£ÀÇ ¼ø¼­¿Í °³¼ö¸¦ ¸ÂÃß¾î¾ß ÇÑ´Ù. + String[] grades = {"D", "C", "B", "A"}; + + int[] scores = { 100, 95, 88, 70, 52, 60, 70}; + + ChoiceFormat form = new ChoiceFormat(limits, grades); + + for(int i=0;i "); + + double d = num.doubleValue(); + System.out.print(d + " -> "); + + System.out.println(df2.format(num)); + } catch(Exception e) {} + } // main +} diff --git a/workspace/ch10/src/MessageFormatEx1.java b/workspace/ch10/src/MessageFormatEx1.java new file mode 100644 index 0000000..1869d32 --- /dev/null +++ b/workspace/ch10/src/MessageFormatEx1.java @@ -0,0 +1,14 @@ +import java.text.*; + +class MessageFormatEx1 { + public static void main(String[] args) { + String msg = "Name: {0} \nTel: {1} \nAge:{2} \nBirthday:{3}"; + + Object[] arguments = { + "ÀÌÀÚ¹Ù","02-123-1234", "27", "07-09" + }; + + String result = MessageFormat.format(msg, arguments); + System.out.println(result); + } +} diff --git a/workspace/ch10/src/MessageFormatEx2.java b/workspace/ch10/src/MessageFormatEx2.java new file mode 100644 index 0000000..a4b723c --- /dev/null +++ b/workspace/ch10/src/MessageFormatEx2.java @@ -0,0 +1,18 @@ +import java.text.*; + +class MessageFormatEx2 { + public static void main(String[] args) { + String tableName = "CUST_INFO"; + String msg = "INSERT INTO "+ tableName +" VALUES (''{0}'',''{1}'',{2},''{3}'');"; + + Object[][] arguments = { + {"ÀÌÀÚ¹Ù","02-123-1234", "27", "07-09"}, + {"±èÇÁ·Î","032-333-1234", "33", "10-07"}, + }; + + for(int i=0; i < arguments.length;i++) { + String result = MessageFormat.format(msg, arguments[i]); + System.out.println(result); + } + } // main +} diff --git a/workspace/ch10/src/MessageFormatEx3.java b/workspace/ch10/src/MessageFormatEx3.java new file mode 100644 index 0000000..b2e546a --- /dev/null +++ b/workspace/ch10/src/MessageFormatEx3.java @@ -0,0 +1,21 @@ +import java.text.*; + +class MessageFormatEx3 { + public static void main(String[] args) throws Exception { + String[] data = { + "INSERT INTO CUST_INFO VALUES ('ÀÌÀÚ¹Ù','02-123-1234',27,'07-09');", + "INSERT INTO CUST_INFO VALUES ('±èÇÁ·Î','032-333-1234',33,'10-07');" + }; + + String pattern = "INSERT INTO CUST_INFO VALUES ({0},{1},{2},{3});"; + MessageFormat mf = new MessageFormat(pattern); + + for(int i=0; i < data.length;i++) { + Object[] objs = mf.parse(data[i]); + for(int j=0; j < objs.length; j++) { + System.out.print(objs[j] + ","); + } + System.out.println(); + } + } // main +} diff --git a/workspace/ch10/src/MessageFormatEx4.java b/workspace/ch10/src/MessageFormatEx4.java new file mode 100644 index 0000000..a580f98 --- /dev/null +++ b/workspace/ch10/src/MessageFormatEx4.java @@ -0,0 +1,23 @@ +import java.util.*; +import java.text.*; +import java.io.*; + +class MessageFormatEx4 { + public static void main(String[] args) throws Exception { + String tableName = "CUST_INFO"; + String fileName = "data4.txt"; + String msg = "INSERT INTO "+ tableName + " VALUES ({0},{1},{2},{3});"; + Scanner s = new Scanner(new File(fileName)); + + String pattern = "{0},{1},{2},{3}"; + MessageFormat mf = new MessageFormat(pattern); + + while(s.hasNextLine()) { + String line = s.nextLine(); + Object[] objs = mf.parse(line); + System.out.println(MessageFormat.format(msg, objs)); + } + + s.close(); // ÀÛ¾÷ÀÌ ³¡³µÀ¸´Ï Scanner¿¡¼­ »ç¿ëÇÑ ÆÄÀÏÀ» ´Ý¾Æ ÁØ´Ù. + } // main +} diff --git a/workspace/ch10/src/NewTimeEx1.java b/workspace/ch10/src/NewTimeEx1.java new file mode 100644 index 0000000..b09c5a4 --- /dev/null +++ b/workspace/ch10/src/NewTimeEx1.java @@ -0,0 +1,27 @@ +import java.time.*; +import java.time.temporal.*; + +class NewTimeEx1 { + public static void main(String[] args) { + LocalDate today = LocalDate.now(); // ¿À´ÃÀÇ ³¯Â¥ + LocalTime now = LocalTime.now(); // ÇöÀç ½Ã°£ + + LocalDate birthDate = LocalDate.of(1999, 12, 31); // 1999³â 12¿ù 31ÀÏ + LocalTime birthTime = LocalTime.of(23, 59, 59); // 23½Ã 59ºÐ 59ÃÊ + + System.out.println("today="+today); + System.out.println("now="+now); + System.out.println("birthDate="+birthDate); // 1999-12-31 + System.out.println("birthTime="+birthTime); // 23:59:59 + + System.out.println(birthDate.withYear(2000)); // 2000-12-31 + System.out.println(birthDate.plusDays(1)); // 2001-01-01 + System.out.println(birthDate.plus(1,ChronoUnit.DAYS)); //2001-01-02 + + // 23:59:59 -> 23:00 + System.out.println(birthTime.truncatedTo(ChronoUnit.HOURS)); + // ƯÁ¤ ChronoFieldÀÇ ¹üÀ§¸¦ ¾Ë¾Æ³»´Â ¹æ¹ý + System.out.println(ChronoField.CLOCK_HOUR_OF_DAY.range()); // 1-24 + System.out.println(ChronoField.HOUR_OF_DAY.range()); // 0-23 + } +} diff --git a/workspace/ch10/src/NewTimeEx2.java b/workspace/ch10/src/NewTimeEx2.java new file mode 100644 index 0000000..e96f78b --- /dev/null +++ b/workspace/ch10/src/NewTimeEx2.java @@ -0,0 +1,29 @@ +import java.time.*; + +class NewTimeEx2 { + public static void main(String[] args) { + LocalDate date = LocalDate.of(2015, 12, 31); // 2015³â 12¿ù 31ÀÏ + LocalTime time = LocalTime.of(12,34,56); // 12½Ã 23ºÐ 56ÃÊ + + // 2015³â 12¿ù 31ÀÏ 12½Ã 23ºÐ 56ÃÊ + LocalDateTime dt = LocalDateTime.of(date, time); + + ZoneId zid = ZoneId.of("Asia/Seoul"); + ZonedDateTime zdt = dt.atZone(zid); +// String strZid = zdt.getZone().getId(); + + ZonedDateTime seoulTime = ZonedDateTime.now(); + ZoneId nyId = ZoneId.of("America/New_York"); + ZonedDateTime nyTime = ZonedDateTime.now().withZoneSameInstant(nyId); + + // ZonedDatetime -> OffsetDateTime + OffsetDateTime odt = zdt.toOffsetDateTime(); + + System.out.println(dt); + System.out.println(zid); + System.out.println(zdt); + System.out.println(seoulTime); + System.out.println(nyTime); + System.out.println(odt); + } +} diff --git a/workspace/ch10/src/NewTimeEx3.java b/workspace/ch10/src/NewTimeEx3.java new file mode 100644 index 0000000..facc952 --- /dev/null +++ b/workspace/ch10/src/NewTimeEx3.java @@ -0,0 +1,36 @@ +import java.time.*; +import java.time.temporal.*; +import static java.time.DayOfWeek.*; +import static java.time.temporal.TemporalAdjusters.*; + +class DayAfterTomorrow implements TemporalAdjuster { + @Override + public Temporal adjustInto(Temporal temporal) { + return temporal.plus(2, ChronoUnit.DAYS); + } +} + +class NewTimeEx3 { + public static void main(String[] args) { + LocalDate today = LocalDate.now(); + LocalDate date = today.with(new DayAfterTomorrow()); + + p(today); // System.out.println(today); + p(date); + + p(today.with(firstDayOfNextMonth())); // ´ÙÀ½ ´ÞÀÇ Ã¹ ³¯ + p(today.with(firstDayOfMonth())); // ÀÌ ´ÞÀÇ Ã¹ ³¯ + p(today.with(lastDayOfMonth())); // ÀÌ ´ÞÀÇ ¸¶Áö¸· ³¯ + p(today.with(firstInMonth(TUESDAY))); // ÀÌ ´ÞÀÇ Ã¹¹ø° È­¿äÀÏ + p(today.with(lastInMonth(TUESDAY))); // ÀÌ ´ÞÀÇ ¸¶Áö¸· È­¿äÀÏ + p(today.with(previous(TUESDAY))); // Áö³­ ÁÖ È­¿äÀÏ + p(today.with(previousOrSame(TUESDAY))); // Áö³­ ÁÖ È­¿äÀÏ(¿À´Ã Æ÷ÇÔ) + p(today.with(next(TUESDAY))); // ´ÙÀ½ ÁÖ È­¿äÀÏ + p(today.with(nextOrSame(TUESDAY))); // ´ÙÀ½ ÁÖ È­¿äÀÏ(¿À´Ã Æ÷ÇÔ) + p(today.with(dayOfWeekInMonth(4, TUESDAY))); // ÀÌ ´ÞÀÇ 4¹ø° È­¿äÀÏ + } + + static void p(Object obj) { // ¶óÀÎÀÇ ±æÀ̸¦ ÁÙÀ̱â À§ÇØ »õ·Î Á¤ÀÇÇÑ ¸Þ¼­µå + System.out.println(obj); + } +} diff --git a/workspace/ch10/src/NewTimeEx4.java b/workspace/ch10/src/NewTimeEx4.java new file mode 100644 index 0000000..020e93b --- /dev/null +++ b/workspace/ch10/src/NewTimeEx4.java @@ -0,0 +1,35 @@ +import java.time.*; +import java.time.temporal.*; + +class NewTimeEx4 { + public static void main(String[] args) { + LocalDate date1 = LocalDate.of(2014, 1, 1); + LocalDate date2 = LocalDate.of(2015, 12, 31); + + Period pe = Period.between(date1, date2); + + System.out.println("date1="+date1); + System.out.println("date2="+date2); + System.out.println("pe="+pe); + + System.out.println("YEAR=" +pe.get(ChronoUnit.YEARS)); + System.out.println("MONTH="+pe.get(ChronoUnit.MONTHS)); + System.out.println("DAY=" +pe.get(ChronoUnit.DAYS)); + + LocalTime time1 = LocalTime.of( 0, 0, 0); + LocalTime time2 = LocalTime.of(12,34,56); // 12½Ã°£ 23ºÐ 56ÃÊ + + Duration du = Duration.between(time1, time2); + + System.out.println("time1="+time1); + System.out.println("time2="+time2); + System.out.println("du="+du); + + LocalTime tmpTime = LocalTime.of(0,0).plusSeconds(du.getSeconds()); + + System.out.println("HOUR=" +tmpTime.getHour()); + System.out.println("MINUTE="+tmpTime.getMinute()); + System.out.println("SECOND="+tmpTime.getSecond()); + System.out.println("NANO=" +tmpTime.getNano()); + } +} diff --git a/workspace/ch11/.classpath b/workspace/ch11/.classpath new file mode 100644 index 0000000..fceb480 --- /dev/null +++ b/workspace/ch11/.classpath @@ -0,0 +1,6 @@ + + + + + + diff --git a/workspace/ch11/.project b/workspace/ch11/.project new file mode 100644 index 0000000..05345e3 --- /dev/null +++ b/workspace/ch11/.project @@ -0,0 +1,17 @@ + + + ch11 + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/workspace/ch11/.settings/org.eclipse.jdt.core.prefs b/workspace/ch11/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..3a21537 --- /dev/null +++ b/workspace/ch11/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,11 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/workspace/ch11/src/ArrayListEx1.java b/workspace/ch11/src/ArrayListEx1.java new file mode 100644 index 0000000..db431fe --- /dev/null +++ b/workspace/ch11/src/ArrayListEx1.java @@ -0,0 +1,47 @@ +import java.util.*; + +class ArrayListEx1{ + public static void main(String[] args) { + ArrayList list1 = new ArrayList(10); + list1.add(new Integer(5)); + list1.add(new Integer(4)); + list1.add(new Integer(2)); + list1.add(new Integer(0)); + list1.add(new Integer(1)); + list1.add(new Integer(3)); + + ArrayList list2 = new ArrayList(list1.subList(1,4)); + print(list1, list2); + + Collections.sort(list1); // list1°ú list2¸¦ Á¤·ÄÇÑ´Ù. + Collections.sort(list2); // Collections.sort(List l) + print(list1, list2); + + System.out.println("list1.containsAll(list2):" + list1.containsAll(list2)); + + list2.add("B"); + list2.add("C"); + list2.add(3, "A"); + print(list1, list2); + + list2.set(3, "AA"); + print(list1, list2); + + // list1¿¡¼­ list2¿Í °ãÄ¡´Â ºÎºÐ¸¸ ³²±â°í ³ª¸ÓÁö´Â »èÁ¦ÇÑ´Ù. + System.out.println("list1.retainAll(list2):" + list1.retainAll(list2)); + print(list1, list2); + + // list2¿¡¼­ list1¿¡ Æ÷ÇÔµÈ °´Ã¼µéÀ» »èÁ¦ÇÑ´Ù. + for(int i= list2.size()-1; i >= 0; i--) { + if(list1.contains(list2.get(i))) + list2.remove(i); + } + print(list1, list2); + } // mainÀÇ ³¡ + + static void print(ArrayList list1, ArrayList list2) { + System.out.println("list1:"+list1); + System.out.println("list2:"+list2); + System.out.println(); + } +} // class diff --git a/workspace/ch11/src/ArrayListEx2.java b/workspace/ch11/src/ArrayListEx2.java new file mode 100644 index 0000000..b2b9c15 --- /dev/null +++ b/workspace/ch11/src/ArrayListEx2.java @@ -0,0 +1,22 @@ +import java.util.*; + +class ArrayListEx2 { + public static void main(String[] args) { + final int LIMIT = 10; // ÀÚ¸£°íÀÚ ÇÏ´Â ±ÛÀÚÀÇ °³¼ö¸¦ ÁöÁ¤ÇÑ´Ù. + String source = "0123456789abcdefghijABCDEFGHIJ!@#$%^&*()ZZZ"; + int length = source.length(); + + List list = new ArrayList(length/LIMIT + 10); // Å©±â¸¦ ¾à°£ ¿©À¯ ÀÖ°Ô Àâ´Â´Ù. + + for(int i=0; i < length; i+=LIMIT) { + if(i+LIMIT < length ) + list.add(source.substring(i, i+LIMIT)); + else + list.add(source.substring(i)); + } + + for(int i=0; i < list.size(); i++) { + System.out.println(list.get(i)); + } + } // main() +} diff --git a/workspace/ch11/src/ArrayListLinkedListTest.java b/workspace/ch11/src/ArrayListLinkedListTest.java new file mode 100644 index 0000000..ba64aac --- /dev/null +++ b/workspace/ch11/src/ArrayListLinkedListTest.java @@ -0,0 +1,53 @@ +import java.util.*; + +public class ArrayListLinkedListTest { + public static void main(String args[]) { + // Ãß°¡ÇÒ µ¥ÀÌÅÍÀÇ °³¼ö¸¦ °í·ÁÇÏ¿© ÃæºÐÈ÷ Àâ¾Æ¾ßÇÑ´Ù. + ArrayList al = new ArrayList(2000000); + LinkedList ll = new LinkedList(); + + System.out.println("= ¼øÂ÷ÀûÀ¸·Î Ãß°¡Çϱâ ="); + System.out.println("ArrayList :"+add1(al)); + System.out.println("LinkedList :"+add1(ll)); + System.out.println(); + System.out.println("= Áß°£¿¡ Ãß°¡Çϱâ ="); + System.out.println("ArrayList :"+add2(al)); + System.out.println("LinkedList :"+add2(ll)); + System.out.println(); + System.out.println("= Áß°£¿¡¼­ »èÁ¦Çϱâ ="); + System.out.println("ArrayList :"+remove2(al)); + System.out.println("LinkedList :"+remove2(ll)); + System.out.println(); + System.out.println("= ¼øÂ÷ÀûÀ¸·Î »èÁ¦Çϱâ ="); + System.out.println("ArrayList :"+remove1(al)); + System.out.println("LinkedList :"+remove1(ll)); + } + + public static long add1(List list) { + long start = System.currentTimeMillis(); + for(int i=0; i<1000000;i++) list.add(i+""); + long end = System.currentTimeMillis(); + return end - start; + } + + public static long add2(List list) { + long start = System.currentTimeMillis(); + for(int i=0; i<10000;i++) list.add(500, "X"); + long end = System.currentTimeMillis(); + return end - start; + } + + public static long remove1(List list) { + long start = System.currentTimeMillis(); + for(int i=list.size()-1; i >= 0;i--) list.remove(i); + long end = System.currentTimeMillis(); + return end - start; + } + + public static long remove2(List list) { + long start = System.currentTimeMillis(); + for(int i=0; i<10000;i++) list.remove(i); + long end = System.currentTimeMillis(); + return end - start; + } +} diff --git a/workspace/ch11/src/ArrayListLinkedListTest2.java b/workspace/ch11/src/ArrayListLinkedListTest2.java new file mode 100644 index 0000000..7da4011 --- /dev/null +++ b/workspace/ch11/src/ArrayListLinkedListTest2.java @@ -0,0 +1,28 @@ +import java.util.*; + +public class ArrayListLinkedListTest2 { + public static void main(String args[]) { + ArrayList al = new ArrayList(1000000); + LinkedList ll = new LinkedList(); + add(al); + add(ll); + + System.out.println("= Á¢±Ù½Ã°£Å×½ºÆ® ="); + System.out.println("ArrayList :"+access(al)); + System.out.println("LinkedList :"+access(ll)); + } + + public static void add(List list) { + for(int i=0; i<100000;i++) list.add(i+""); + } + + public static long access(List list) { + long start = System.currentTimeMillis(); + + for(int i=0; i<10000;i++) list.get(i); + + long end = System.currentTimeMillis(); + + return end - start; + } +} diff --git a/workspace/ch11/src/ArraysEx.java b/workspace/ch11/src/ArraysEx.java new file mode 100644 index 0000000..9bcbd30 --- /dev/null +++ b/workspace/ch11/src/ArraysEx.java @@ -0,0 +1,52 @@ +import java.util.*; + +class ArraysEx { + public static void main(String[] args) { + int[] arr = {0,1,2,3,4}; + int[][] arr2D = {{11,12,13}, {21,22,23}}; + + System.out.println("arr="+Arrays.toString(arr)); + System.out.println("arr2D="+Arrays.deepToString(arr2D)); + + int[] arr2 = Arrays.copyOf(arr, arr.length); + int[] arr3 = Arrays.copyOf(arr, 3); + int[] arr4 = Arrays.copyOf(arr, 7); + int[] arr5 = Arrays.copyOfRange(arr, 2, 4); + int[] arr6 = Arrays.copyOfRange(arr, 0, 7); + + System.out.println("arr2="+ Arrays.toString(arr2)); + System.out.println("arr3="+ Arrays.toString(arr3)); + System.out.println("arr4="+ Arrays.toString(arr4)); + System.out.println("arr5="+ Arrays.toString(arr5)); + System.out.println("arr6="+ Arrays.toString(arr6)); + + int[] arr7 = new int[5]; + Arrays.fill(arr7, 9); // arr=[9,9,9,9,9] + System.out.println("arr7="+Arrays.toString(arr7)); + + Arrays.setAll(arr7, i -> (int)(Math.random()*6)+1); + System.out.println("arr7="+Arrays.toString(arr7)); + + for(int i : arr7) { + char[] graph = new char[i]; + Arrays.fill(graph, '*'); + System.out.println(new String(graph)+i); + } + + String[][] str2D = new String[][]{{"aaa","bbb"},{"AAA","BBB"}}; + String[][] str2D2 = new String[][]{{"aaa","bbb"},{"AAA","BBB"}}; + + System.out.println(Arrays.equals(str2D, str2D2)); // false + System.out.println(Arrays.deepEquals(str2D, str2D2)); // true + + char[] chArr = { 'A', 'D', 'C', 'B', 'E' }; + + int idx = Arrays.binarySearch(chArr, 'B'); + System.out.println("chArr="+Arrays.toString(chArr)); + System.out.println("index of B ="+Arrays.binarySearch(chArr, 'B')); + System.out.println("= After sorting ="); + Arrays.sort(chArr); + System.out.println("chArr="+Arrays.toString(chArr)); + System.out.println("index of B ="+Arrays.binarySearch(chArr, 'B')); + } +} diff --git a/workspace/ch11/src/AsciiPrint.java b/workspace/ch11/src/AsciiPrint.java new file mode 100644 index 0000000..f25b857 --- /dev/null +++ b/workspace/ch11/src/AsciiPrint.java @@ -0,0 +1,7 @@ +class AsciiPrint{ + public static void main(String[] args) { + char ch = ' '; + for(int i=0; i < 95; i++) // °ø¹é(' ')ÀÌÈÄÀÇ ¹®ÀÚµéÀ» Ãâ·ÂÇÑ´Ù. + System.out.print(ch++); + } +} diff --git a/workspace/ch11/src/Bingo.java b/workspace/ch11/src/Bingo.java new file mode 100644 index 0000000..9a807ba --- /dev/null +++ b/workspace/ch11/src/Bingo.java @@ -0,0 +1,23 @@ +import java.util.*; + +class Bingo { + public static void main(String[] args) { + Set set = new HashSet(); +// Set set = new LinkedHashSet(); + int[][] board = new int[5][5]; + + for(int i=0; set.size() < 25; i++) { + set.add((int)(Math.random()*50)+1+""); + } + + Iterator it = set.iterator(); + + for(int i=0; i < board.length; i++) { + for(int j=0; j < board[i].length; j++) { + board[i][j] = Integer.parseInt((String)it.next()); + System.out.print((board[i][j] < 10 ? " " : " ") + board[i][j]); + } + System.out.println(); + } + } // main +} diff --git a/workspace/ch11/src/ComparatorEx.java b/workspace/ch11/src/ComparatorEx.java new file mode 100644 index 0000000..168b244 --- /dev/null +++ b/workspace/ch11/src/ComparatorEx.java @@ -0,0 +1,29 @@ +import java.util.*; + +class ComparatorEx { + public static void main(String[] args) { + String[] strArr = {"cat", "Dog", "lion", "tiger"}; + + Arrays.sort(strArr); // StringÀÇ Comparable±¸Çö¿¡ ÀÇÇÑ Á¤·Ä + System.out.println("strArr=" + Arrays.toString(strArr)); + + Arrays.sort(strArr, String.CASE_INSENSITIVE_ORDER); // ´ë¼Ò¹®ÀÚ ±¸ºÐ¾ÈÇÔ + System.out.println("strArr=" + Arrays.toString(strArr)); + + Arrays.sort(strArr, new Descending()); // ¿ª¼ø Á¤·Ä + System.out.println("strArr=" + Arrays.toString(strArr)); + } +} + +class Descending implements Comparator { + public int compare(Object o1, Object o2){ + if( o1 instanceof Comparable && o2 instanceof Comparable) { + Comparable c1 = (Comparable)o1; + Comparable c2 = (Comparable)o2; + return c1.compareTo(c2) * -1 ; // -1À» °öÇؼ­ ±âº» Á¤·Ä¹æ½ÄÀÇ ¿ªÀ¸·Î º¯°æÇÑ´Ù. + // ¶Ç´Â c2.compareTo(c1)¿Í °°ÀÌ ¼ø¼­¸¦ ¹Ù²ãµµ µÈ´Ù. + + } + return -1; + } +} diff --git a/workspace/ch11/src/ExpValidCheck.java b/workspace/ch11/src/ExpValidCheck.java new file mode 100644 index 0000000..edb3198 --- /dev/null +++ b/workspace/ch11/src/ExpValidCheck.java @@ -0,0 +1,36 @@ +import java.util.*; + +public class ExpValidCheck { + public static void main(String[] args) { + if(args.length!=1){ + System.out.println("Usage : java ExpValidCheck \"EXPRESSION\""); + System.out.println("Example : java ExpValidCheck \"((2+3)*1)+3\""); + System.exit(0); + } + + Stack st = new Stack(); + String expression = args[0]; + + System.out.println("expression:"+expression); + + try { + for(int i=0; i < expression.length();i++){ + char ch = expression.charAt(i); + + if(ch=='('){ + st.push(ch+""); + } else if(ch==')') { + st.pop(); + } + } + + if(st.isEmpty()){ + System.out.println("°ýÈ£°¡ ÀÏÄ¡ÇÕ´Ï´Ù."); + } else { + System.out.println("°ýÈ£°¡ ÀÏÄ¡ÇÏÁö ¾Ê½À´Ï´Ù."); + } + } catch (EmptyStackException e) { + System.out.println("°ýÈ£°¡ ÀÏÄ¡ÇÏÁö ¾Ê½À´Ï´Ù."); + } // try + } +} diff --git a/workspace/ch11/src/HashMapEx1.java b/workspace/ch11/src/HashMapEx1.java new file mode 100644 index 0000000..1b605a9 --- /dev/null +++ b/workspace/ch11/src/HashMapEx1.java @@ -0,0 +1,34 @@ +import java.util.*; + +class HashMapEx1 { + public static void main(String[] args) { + HashMap map = new HashMap(); + map.put("myId", "1234"); + map.put("asdf", "1111"); + map.put("asdf", "1234"); + + Scanner s = new Scanner(System.in); // È­¸éÀ¸·ÎºÎÅÍ ¶óÀδÜÀ§·Î ÀԷ¹޴´Ù. + + while(true) { + System.out.println("id¿Í password¸¦ ÀÔ·ÂÇØÁÖ¼¼¿ä."); + System.out.print("id :"); + String id = s.nextLine().trim(); + + System.out.print("password :"); + String password = s.nextLine().trim(); + System.out.println(); + + if(!map.containsKey(id)) { + System.out.println("ÀÔ·ÂÇϽŠid´Â Á¸ÀçÇÏÁö ¾Ê½À´Ï´Ù. ´Ù½Ã ÀÔ·ÂÇØÁÖ¼¼¿ä."); + continue; + } else { + if(!(map.get(id)).equals(password)) { + System.out.println("ºñ¹Ð¹øÈ£°¡ ÀÏÄ¡ÇÏÁö ¾Ê½À´Ï´Ù. ´Ù½Ã ÀÔ·ÂÇØÁÖ¼¼¿ä."); + } else { + System.out.println("id¿Í ºñ¹Ð¹øÈ£°¡ ÀÏÄ¡ÇÕ´Ï´Ù."); + break; + } + } + } // while + } // mainÀÇ ³¡ +} diff --git a/workspace/ch11/src/HashMapEx2.java b/workspace/ch11/src/HashMapEx2.java new file mode 100644 index 0000000..d538dfa --- /dev/null +++ b/workspace/ch11/src/HashMapEx2.java @@ -0,0 +1,38 @@ +import java.util.*; + +class HashMapEx2 { + public static void main(String[] args) { + HashMap map = new HashMap(); + map.put("±èÀÚ¹Ù", new Integer(90)); + map.put("±èÀÚ¹Ù", new Integer(100)); + map.put("ÀÌÀÚ¹Ù", new Integer(100)); + map.put("°­ÀÚ¹Ù", new Integer(80)); + map.put("¾ÈÀÚ¹Ù", new Integer(90)); + + Set set = map.entrySet(); + Iterator it = set.iterator(); + + while(it.hasNext()) { + Map.Entry e = (Map.Entry)it.next(); + System.out.println("À̸§ : "+ e.getKey() + ", Á¡¼ö : " + e.getValue()); + } + + set = map.keySet(); + System.out.println("Âü°¡ÀÚ ¸í´Ü : " + set); + + Collection values = map.values(); + it = values.iterator(); + + int total = 0; + + while(it.hasNext()) { + Integer i = (Integer)it.next(); + total += i.intValue(); + } + + System.out.println("ÃÑÁ¡ : " + total); + System.out.println("Æò±Õ : " + (float)total/set.size()); + System.out.println("ÃÖ°íÁ¡¼ö : " + Collections.max(values)); + System.out.println("ÃÖÀúÁ¡¼ö : " + Collections.min(values)); + } +} diff --git a/workspace/ch11/src/HashMapEx3.java b/workspace/ch11/src/HashMapEx3.java new file mode 100644 index 0000000..8fdcf76 --- /dev/null +++ b/workspace/ch11/src/HashMapEx3.java @@ -0,0 +1,58 @@ +import java.util.*; + +class HashMapEx3 { + static HashMap phoneBook = new HashMap(); + + public static void main(String[] args) { + addPhoneNo("Ä£±¸", "ÀÌÀÚ¹Ù", "010-111-1111"); + addPhoneNo("Ä£±¸", "±èÀÚ¹Ù", "010-222-2222"); + addPhoneNo("Ä£±¸", "±èÀÚ¹Ù", "010-333-3333"); + addPhoneNo("ȸ»ç", "±è´ë¸®", "010-444-4444"); + addPhoneNo("ȸ»ç", "±è´ë¸®", "010-555-5555"); + addPhoneNo("ȸ»ç", "¹Ú´ë¸®", "010-666-6666"); + addPhoneNo("ȸ»ç", "ÀÌ°úÀå", "010-777-7777"); + addPhoneNo("¼¼Å¹", "010-888-8888"); + + printList(); + } // main + + // ±×·ìÀ» Ãß°¡ÇÏ´Â ¸Þ¼­µå + static void addGroup(String groupName) { + if(!phoneBook.containsKey(groupName)) + phoneBook.put(groupName, new HashMap()); + } + + // ±×·ì¿¡ ÀüÈ­¹øÈ£¸¦ Ãß°¡ÇÏ´Â ¸Þ¼­µå + static void addPhoneNo(String groupName, String name, String tel) { + addGroup(groupName); + HashMap group = (HashMap)phoneBook.get(groupName); + group.put(tel, name); // À̸§Àº Áߺ¹µÉ ¼ö ÀÖÀ¸´Ï ÀüÈ­¹øÈ£¸¦ key·Î ÀúÀåÇÑ´Ù. + } + + static void addPhoneNo(String name, String tel) { + addPhoneNo("±âŸ", name, tel); + } + + // ÀüÈ­¹øÈ£ºÎ Àüü¸¦ Ãâ·ÂÇÏ´Â ¸Þ¼­µå + static void printList() { + Set set = phoneBook.entrySet(); + Iterator it = set.iterator(); + + while(it.hasNext()) { + Map.Entry e = (Map.Entry)it.next(); + + Set subSet = ((HashMap)e.getValue()).entrySet(); + Iterator subIt = subSet.iterator(); + + System.out.println(" * "+e.getKey()+"["+subSet.size()+"]"); + + while(subIt.hasNext()) { + Map.Entry subE = (Map.Entry)subIt.next(); + String telNo = (String)subE.getKey(); + String name = (String)subE.getValue(); + System.out.println(name + " " + telNo ); + } + System.out.println(); + } + } // printList() +} // class diff --git a/workspace/ch11/src/HashMapEx4.java b/workspace/ch11/src/HashMapEx4.java new file mode 100644 index 0000000..1e4bb9d --- /dev/null +++ b/workspace/ch11/src/HashMapEx4.java @@ -0,0 +1,36 @@ +import java.util.*; + +class HashMapEx4 { + public static void main(String[] args) { + String[] data = { "A","K","A","K","D","K","A","K","K","K","Z","D" }; + + HashMap map = new HashMap(); + + for(int i=0; i < data.length; i++) { + if(map.containsKey(data[i])) { + Integer value = (Integer)map.get(data[i]); + map.put(data[i], new Integer(value.intValue() + 1)); + } else { + map.put(data[i], new Integer(1)); + } + } + + Iterator it = map.entrySet().iterator(); + + while(it.hasNext()) { + Map.Entry entry = (Map.Entry)it.next(); + int value = ((Integer)entry.getValue()).intValue(); + System.out.println(entry.getKey() + " : " + printBar('#', value) + " " + value ); + } + } // main + + public static String printBar(char ch, int value) { + char[] bar = new char[value]; + + for(int i=0; i < bar.length; i++) { + bar[i] = ch; + } + + return new String(bar); // String(char[] chArr) + } +} diff --git a/workspace/ch11/src/HashSetEx1.java b/workspace/ch11/src/HashSetEx1.java new file mode 100644 index 0000000..9e1ba1f --- /dev/null +++ b/workspace/ch11/src/HashSetEx1.java @@ -0,0 +1,14 @@ +import java.util.*; + +class HashSetEx1 { + public static void main(String[] args) { + Object[] objArr = {"1",new Integer(1),"2","2","3","3","4","4","4"}; + Set set = new HashSet(); + + for(int i=0; i < objArr.length; i++) { + set.add(objArr[i]); // HashSet¿¡ objArrÀÇ ¿ä¼ÒµéÀ» ÀúÀåÇÑ´Ù. + } + // HashSet¿¡ ÀúÀåµÈ ¿ä¼ÒµéÀ» Ãâ·ÂÇÑ´Ù. + System.out.println(set); + } +} diff --git a/workspace/ch11/src/HashSetEx3.java b/workspace/ch11/src/HashSetEx3.java new file mode 100644 index 0000000..d80cafb --- /dev/null +++ b/workspace/ch11/src/HashSetEx3.java @@ -0,0 +1,28 @@ +import java.util.*; + +class HashSetEx3 { + public static void main(String[] args) { + HashSet set = new HashSet(); + + set.add("abc"); + set.add("abc"); + set.add(new Person("David",10)); + set.add(new Person("David",10)); + + System.out.println(set); + } +} + +class Person { + String name; + int age; + + Person(String name, int age) { + this.name = name; + this.age = age; + } + + public String toString() { + return name +":"+ age; + } +} diff --git a/workspace/ch11/src/HashSetEx4.java b/workspace/ch11/src/HashSetEx4.java new file mode 100644 index 0000000..2b46388 --- /dev/null +++ b/workspace/ch11/src/HashSetEx4.java @@ -0,0 +1,41 @@ +import java.util.*; + +class HashSetEx4 { + public static void main(String[] args) { + HashSet set = new HashSet(); + + set.add(new String("abc")); + set.add(new String("abc")); + set.add(new Person2("David",10)); + set.add(new Person2("David",10)); + + System.out.println(set); + } +} + +class Person2 { + String name; + int age; + + Person2(String name, int age) { + this.name = name; + this.age = age; + } + + public boolean equals(Object obj) { + if(obj instanceof Person2) { + Person2 tmp = (Person2)obj; + return name.equals(tmp.name) && age==tmp.age; + } + + return false; + } + + public int hashCode() { + return (name+age).hashCode(); + } + + public String toString() { + return name +":"+ age; + } +} diff --git a/workspace/ch11/src/HashSetEx5.java b/workspace/ch11/src/HashSetEx5.java new file mode 100644 index 0000000..22d2293 --- /dev/null +++ b/workspace/ch11/src/HashSetEx5.java @@ -0,0 +1,47 @@ +import java.util.*; + +class HashSetEx5 { + public static void main(String args[]) { + HashSet setA = new HashSet(); + HashSet setB = new HashSet(); + HashSet setHab = new HashSet(); + HashSet setKyo = new HashSet(); + HashSet setCha = new HashSet(); + + setA.add("1"); setA.add("2"); + setA.add("3"); setA.add("4"); + setA.add("5"); + System.out.println("A = "+setA); + + setB.add("4"); setB.add("5"); + setB.add("6"); setB.add("7"); + setB.add("8"); + System.out.println("B = "+setB); + + Iterator it = setB.iterator(); + while(it.hasNext()) { + Object tmp = it.next(); + if(setA.contains(tmp)) + setKyo.add(tmp); + } + + it = setA.iterator(); + while(it.hasNext()) { + Object tmp = it.next(); + if(!setB.contains(tmp)) + setCha.add(tmp); + } + + it = setA.iterator(); + while(it.hasNext()) + setHab.add(it.next()); + + it = setB.iterator(); + while(it.hasNext()) + setHab.add(it.next()); + + System.out.println("A ¡û B = "+setKyo); // ÇÑ±Û ¤§À» ´©¸£°í ÇÑÀÚÅ° + System.out.println("A ¡ú B = "+setHab); // ÇÑ±Û ¤§À» ´©¸£°í ÇÑÀÚÅ° + System.out.println("A - B = "+setCha); + } +} diff --git a/workspace/ch11/src/HashSetLotto.java b/workspace/ch11/src/HashSetLotto.java new file mode 100644 index 0000000..c2a4aa1 --- /dev/null +++ b/workspace/ch11/src/HashSetLotto.java @@ -0,0 +1,16 @@ +import java.util.*; + +class HashSetLotto { + public static void main(String[] args) { + Set set = new HashSet(); + + for (int i = 0; set.size() < 6 ; i++) { + int num = (int)(Math.random()*45) + 1; + set.add(new Integer(num)); + } + + List list = new LinkedList(set); // LinkedList(Collection c) + Collections.sort(list); // Collections.sort(List list) + System.out.println(list); + } +} diff --git a/workspace/ch11/src/IteratorEx1.java b/workspace/ch11/src/IteratorEx1.java new file mode 100644 index 0000000..226e56e --- /dev/null +++ b/workspace/ch11/src/IteratorEx1.java @@ -0,0 +1,18 @@ +import java.util.*; + +class IteratorEx1 { + public static void main(String[] args) { + ArrayList list = new ArrayList(); + list.add("1"); + list.add("2"); + list.add("3"); + list.add("4"); + list.add("5"); + + Iterator it = list.iterator(); + while(it.hasNext()) { + Object obj = it.next(); + System.out.println(obj); + } + } // main +} diff --git a/workspace/ch11/src/IteratorEx2.java b/workspace/ch11/src/IteratorEx2.java new file mode 100644 index 0000000..f02906e --- /dev/null +++ b/workspace/ch11/src/IteratorEx2.java @@ -0,0 +1,33 @@ +import java.util.*; + +public class IteratorEx2 { + public static void main(String[] args) { + ArrayList original = new ArrayList(10); + ArrayList copy1 = new ArrayList(10); + ArrayList copy2 = new ArrayList(10); + + for(int i=0; i < 10; i++) + original.add(i+""); + + Iterator it = original.iterator(); + + while(it.hasNext()) + copy1.add(it.next()); + + System.out.println("= Original¿¡¼­ copy1·Î º¹»ç(copy) ="); + System.out.println("original:"+original); + System.out.println("copy1:"+copy1); + System.out.println(); + + it = original.iterator(); // Iterator´Â Àç»ç¿ëÀÌ ¾ÈµÇ¹Ç·Î, ´Ù½Ã ¾ò¾î¿Í¾ß ÇÑ´Ù. + + while(it.hasNext()){ + copy2.add(it.next()); + it.remove(); + } + + System.out.println("= Original¿¡¼­ copy2·Î À̵¿(move) ="); + System.out.println("original:"+original); + System.out.println("copy2:"+copy2); + } // main +} // class diff --git a/workspace/ch11/src/ListIteratorEx1.java b/workspace/ch11/src/ListIteratorEx1.java new file mode 100644 index 0000000..f4b0a7c --- /dev/null +++ b/workspace/ch11/src/ListIteratorEx1.java @@ -0,0 +1,24 @@ +import java.util.*; + +class ListIteratorEx1 { + public static void main(String[] args) { + ArrayList list = new ArrayList(); + list.add("1"); + list.add("2"); + list.add("3"); + list.add("4"); + list.add("5"); + + ListIterator it = list.listIterator(); + + while(it.hasNext()) { + System.out.print(it.next()); // ¼ø¹æÇâÀ¸·Î ÁøÇàÇϸ鼭 Àоî¿Â´Ù. + } + System.out.println(); + + while(it.hasPrevious()) { + System.out.print(it.previous()); // ¿ª¹æÇâÀ¸·Î ÁøÇàÇϸ鼭 Àоî¿Â´Ù. + } + System.out.println(); + } +} diff --git a/workspace/ch11/src/MyStack.java b/workspace/ch11/src/MyStack.java new file mode 100644 index 0000000..03971d5 --- /dev/null +++ b/workspace/ch11/src/MyStack.java @@ -0,0 +1,41 @@ +import java.util.*; + +class MyStack extends Vector { + public Object push(Object item) { + addElement(item); + return item; + } + + public Object pop() { + Object obj = peek(); // Stack¿¡ ÀúÀåµÈ ¸¶Áö¸· ¿ä¼Ò¸¦ Àоî¿Â´Ù. + // ¸¸ÀÏ StackÀÌ ºñ¾îÀÖÀ¸¸é peek()¸Þ¼­µå°¡ EmptyStackExceptionÀ» ¹ß»ý½ÃŲ´Ù. + // ¸¶Áö¸· ¿ä¼Ò¸¦ »èÁ¦ÇÑ´Ù. ¹è¿­ÀÇ index°¡ 0 ºÎÅÍ ½ÃÀÛÇϹǷΠ1À» »©ÁØ´Ù. + removeElementAt(size() - 1); + + return obj; + } + + public Object peek() { + int len = size(); + + if (len == 0) + throw new EmptyStackException(); + // ¸¶Áö¸· ¿ä¼Ò¸¦ ¹ÝȯÇÑ´Ù. ¹è¿­ÀÇ index°¡ 0 ºÎÅÍ ½ÃÀÛÇϹǷΠ1À» »©ÁØ´Ù. + return elementAt(len - 1); + } + + public boolean empty() { + return size() == 0; + } + + public int search(Object o) { + int i = lastIndexOf(o); // ³¡¿¡¼­ºÎÅÍ °´Ã¼¸¦ ã´Â´Ù. + // ¹Ýȯ°ªÀº ÀúÀåµÈ À§Ä¡(¹è¿­ÀÇ index)ÀÌ´Ù. + if (i >= 0) { // °´Ã¼¸¦ ãÀº °æ¿ì + return size() - i; // StackÀº ¸Ç À§¿¡ ÀúÀåµÈ °´Ã¼ÀÇ index¸¦ 1·Î Á¤ÀÇÇϱ⠶§¹®¿¡ + // °è»êÀ» ÅëÇؼ­ ±¸ÇÑ´Ù. + } + + return - 1; // ÇØ´ç °´Ã¼¸¦ ãÁö ¸øÇϸé -1¸¦ ¹ÝȯÇÑ´Ù. + } +} diff --git a/workspace/ch11/src/MyVector.java b/workspace/ch11/src/MyVector.java new file mode 100644 index 0000000..51d9016 --- /dev/null +++ b/workspace/ch11/src/MyVector.java @@ -0,0 +1,130 @@ +import java.util.*; + +public class MyVector implements List { + Object[] data = null; // °´Ã¼¸¦ ´ã±â À§ÇÑ °´Ã¼¹è¿­À» ¼±¾ðÇÑ´Ù. + int capacity = 0; // ¿ë·® + int size = 0; // Å©±â + + public MyVector(int capacity) { + if (capacity < 0) + throw new IllegalArgumentException("À¯È¿ÇÏÁö ¾ÊÀº °ªÀÔ´Ï´Ù. :"+ capacity); + + this.capacity = capacity; + data = new Object[capacity]; + } + + public MyVector() { + this(10); // Å©±â¸¦ ÁöÁ¤ÇÏÁö ¾ÊÀ¸¸é Å©±â¸¦ 10À¸·Î ÇÑ´Ù. + } + + // ÃÖ¼ÒÇÑÀÇ ÀúÀå°ø°£(capacity)¸¦ È®º¸ÇÏ´Â ¸Þ¼­µå + public void ensureCapacity(int minCapacity) { + if (minCapacity - data.length > 0) + setCapacity(minCapacity); + } + + public boolean add(Object obj) { + // »õ·Î¿î °´Ã¼¸¦ ÀúÀåÇϱâ Àü¿¡ ÀúÀåÇÒ °ø°£À» È®º¸ÇÑ´Ù. + ensureCapacity(size+1); + data[size++] = obj; + return true; + } + + public Object get(int index) { + if(index < 0 || index >= size) + throw new IndexOutOfBoundsException("¹üÀ§¸¦ ¹þ¾î³µ½À´Ï´Ù."); + + return data[index]; + } + + public Object remove(int index) { + Object oldObj = null; + + if(index < 0 || index >= size) + throw new IndexOutOfBoundsException("¹üÀ§¸¦ ¹þ¾î³µ½À´Ï´Ù."); + + oldObj = data[index]; + + // »èÁ¦ÇÏ°íÀÚ ÇÏ´Â °´Ã¼°¡ ¸¶Áö¸· °´Ã¼°¡ ¾Æ´Ï¶ó¸é, ¹è¿­º¹»ç¸¦ ÅëÇØ ºóÀÚ¸®¸¦ ä¿öÁà¾ß ÇÑ´Ù. + if(index != size-1) { + System.arraycopy(data, index+1, data, index, size-index-1); + } + + // ¸¶Áö¸· µ¥ÀÌÅ͸¦ null·Î ÇÑ´Ù. ¹è¿­Àº 0 ºÎÅÍ ½ÃÀÛÇϹǷΠ¸¶Áö¸· ¿ä¼Ò´Â index°¡ size-1ÀÌ´Ù. + data[size-1] = null; + size--; + return oldObj; + } + + public boolean remove(Object obj) { + for(int i=0; i< size; i++) { + if(obj.equals(data[i])) { + remove(i); + return true; + } + } + return false; + } + + public void trimToSize() { + setCapacity(size); + } + + private void setCapacity(int capacity) { + if(this.capacity==capacity) return; // Å©±â°¡ °°À¸¸é º¯°æÇÏÁö ¾Ê´Â´Ù. + + Object[] tmp = new Object[capacity]; + System.arraycopy(data,0, tmp, 0, size); + data = tmp; + this.capacity = capacity; + } + + public void clear(){ + for (int i = 0; i < size; i++) + data[i] = null; + size = 0; + } + + public Object[] toArray(){ + Object[] result = new Object[size]; + System.arraycopy(data, 0, result, 0, size); + + return result; + } + + public boolean isEmpty() { return size==0;} + public int capacity() { return capacity; } + public int size() { return size; } +/****************************************/ +/* ListÀÎÅÍÆäÀ̽º·ÎºÎÅÍ »ó¼Ó¹ÞÀº ¸Þ¼­µåµé */ +/****************************************/ +// public int size(); +// public boolean isEmpty(); + public boolean contains(Object o){ return false;} + public Iterator iterator(){ return null; } +// public Object[] toArray(); + public Object[] toArray(Object a[]){ return null;} +// public boolean add(Object o); +// public boolean remove(Object o); + public boolean containsAll(Collection c){ return false; } + public boolean addAll(Collection c){ return false; } + public boolean addAll(int index, Collection c){ return false; } + public boolean removeAll(Collection c){ return false; } + public boolean retainAll(Collection c){ return false; } +// public void clear(); + public boolean equals(Object o){ return false; } +// public int hashCode(); +// public Object get(int index); + public Object set(int index, Object element){ return null;} + public void add(int index, Object element){} +// public Object remove(int index); + public int indexOf(Object o){ return -1;} + public int lastIndexOf(Object o){ return -1;} + public ListIterator listIterator(){ return null; } + public ListIterator listIterator(int index){ return null; } + public List subList(int fromIndex, int toIndex){ return null; } + +// default void sort(Comparator c) { /* ³»¿ë»ý·« */ } // JDK1.8ºÎÅÍ +// default Spliterator spliterator() { /* ³»¿ë»ý·« */ } // JDK1.8ºÎÅÍ +// default void replaceAll(UnaryOperator operator){/* ³»¿ë»ý·« */} //JDK1.8ºÎÅÍ +} diff --git a/workspace/ch11/src/MyVector2.java b/workspace/ch11/src/MyVector2.java new file mode 100644 index 0000000..0d95af7 --- /dev/null +++ b/workspace/ch11/src/MyVector2.java @@ -0,0 +1,53 @@ +import java.util.*; + +public class MyVector2 extends MyVector implements Iterator { + int cursor = 0; + int lastRet = -1; + + public MyVector2(int capacity) { + super(capacity); + } + + public MyVector2() { + this(10); + } + + public String toString() { + String tmp = ""; + Iterator it = iterator(); + + for(int i=0; it.hasNext();i++) { + if(i!=0) tmp+=", "; + tmp += it.next(); // tmp += next().toString(); + } + + return "["+ tmp +"]"; + } + + public Iterator iterator() { + cursor=0; // cursor¿Í lastRet¸¦ ÃʱâÈ­ ÇÑ´Ù. + lastRet = -1; + return this; + } + + public boolean hasNext() { + return cursor != size(); + } + + public Object next(){ + Object next = get(cursor); + lastRet = cursor++; + return next; + } + + public void remove() { + // ´õÀÌ»ó »èÁ¦ÇÒ °ÍÀÌ ¾øÀ¸¸é IllegalStateException¸¦ ¹ß»ý½ÃŲ´Ù. + if(lastRet==-1) { + throw new IllegalStateException(); + } else { + remove(lastRet); + cursor--; // »èÁ¦ ÈÄ¿¡ cursorÀÇ À§Ä¡¸¦ °¨¼Ò½ÃŲ´Ù. + lastRet = -1; // lastRetÀÇ °ªÀ» ÃʱâÈ­ ÇÑ´Ù. + } + } +} // class diff --git a/workspace/ch11/src/MyVector2Test.java b/workspace/ch11/src/MyVector2Test.java new file mode 100644 index 0000000..09910c0 --- /dev/null +++ b/workspace/ch11/src/MyVector2Test.java @@ -0,0 +1,21 @@ +import java.util.*; + +class MyVector2Test { + public static void main(String args[]) { + MyVector2 v = new MyVector2(); + v.add("0"); + v.add("1"); + v.add("2"); + v.add("3"); + v.add("4"); + + System.out.println("»èÁ¦ Àü : " + v); + Iterator it = v.iterator(); + it.next(); + it.remove(); + it.next(); + it.remove(); + + System.out.println("»èÁ¦ ÈÄ : " + v); + } +} diff --git a/workspace/ch11/src/PriorityQueueEx.java b/workspace/ch11/src/PriorityQueueEx.java new file mode 100644 index 0000000..dcb2e76 --- /dev/null +++ b/workspace/ch11/src/PriorityQueueEx.java @@ -0,0 +1,20 @@ +import java.util.*; + +class PriorityQueueEx { + public static void main(String[] args) { + Queue pq = new PriorityQueue(); + pq.offer(3); // pq.offer(new Integer(3)); ¿ÀÅä¹Ú½Ì + pq.offer(1); + pq.offer(5); + pq.offer(2); + pq.offer(4); + + System.out.println(pq); // pqÀÇ ³»ºÎ ¹è¿­À» Ãâ·Â + + Object obj = null; + + // PriorityQueue¿¡ ÀúÀåµÈ ¿ä¼Ò¸¦ Çϳª¾¿ ²¨³½´Ù. + while((obj = pq.poll())!=null) + System.out.println(obj); + } +} diff --git a/workspace/ch11/src/PropertiesEx1.java b/workspace/ch11/src/PropertiesEx1.java new file mode 100644 index 0000000..928c4f5 --- /dev/null +++ b/workspace/ch11/src/PropertiesEx1.java @@ -0,0 +1,30 @@ +import java.util.*; + +class PropertiesEx1 { + public static void main(String[] args) { + Properties prop = new Properties(); + + // prop¿¡ Å°¿Í °ª(key, value)À» ÀúÀåÇÑ´Ù. + prop.setProperty("timeout","30"); + prop.setProperty("language","kr"); + prop.setProperty("size","10"); + prop.setProperty("capacity","10"); + + // prop¿¡ ÀúÀåµÈ ¿ä¼ÒµéÀ» EnumerationÀ» ÀÌ¿ëÇؼ­ Ãâ·ÂÇÑ´Ù. + Enumeration e = prop.propertyNames(); + + while(e.hasMoreElements()) { + String element = (String)e.nextElement(); + System.out.println(element + "="+ prop.getProperty(element)); + } + + System.out.println(); + prop.setProperty("size","20"); // sizeÀÇ °ªÀ» 20À¸·Î º¯°æÇÑ´Ù. + System.out.println("size=" + prop.getProperty("size")); + System.out.println("capacity=" + prop.getProperty("capacity", "20")); + System.out.println("loadfactor=" + prop.getProperty("loadfactor", "0.75")); + + System.out.println(prop); // prop¿¡ ÀúÀåµÈ ¿ä¼ÒµéÀ» Ãâ·ÂÇÑ´Ù. + prop.list(System.out); // prop¿¡ ÀúÀåµÈ ¿ä¼ÒµéÀ» È­¸é(System.out)¿¡ Ãâ·ÂÇÑ´Ù. + } +} diff --git a/workspace/ch11/src/PropertiesEx2.java b/workspace/ch11/src/PropertiesEx2.java new file mode 100644 index 0000000..f9e5b64 --- /dev/null +++ b/workspace/ch11/src/PropertiesEx2.java @@ -0,0 +1,48 @@ +import java.io.*; +import java.util.*; + +class PropertiesEx2 { + public static void main(String[] args) { + // commandline¿¡¼­ inputfileÀ» ÁöÁ¤ÇØÁÖÁö ¾ÊÀ¸¸é ÇÁ·Î±×·¥À» Á¾·áÇÑ´Ù. + if(args.length != 1) { + System.out.println("USAGE: java PropertiesEx2 INPUTFILENAME"); + System.exit(0); + } + + Properties prop = new Properties(); + + String inputFile = args[0]; + + try { + prop.load(new FileInputStream(inputFile)); + } catch(IOException e) { + System.out.println("ÁöÁ¤µÈ ÆÄÀÏÀ» ãÀ» ¼ö ¾ø½À´Ï´Ù."); + System.exit(0); + } + + String name = prop.getProperty("name"); + String[] data = prop.getProperty("data").split(","); + int max = 0; + int min = 0; + int sum = 0; + + for(int i=0; i < data.length; i++) { + int intValue = Integer.parseInt(data[i]); + if (i==0) max = min = intValue; + + if (max < intValue) { + max = intValue; + } else if (min > intValue) { + min = intValue; + } + + sum += intValue; + } + + System.out.println("À̸§ :" + name); + System.out.println("ÃÖ´ë°ª :" + max); + System.out.println("ÃÖ¼Ò°ª :" + min); + System.out.println("ÇÕ°è :" + sum); + System.out.println("Æò±Õ :" + (sum*100.0/data.length)/100); + } +} diff --git a/workspace/ch11/src/PropertiesEx3.java b/workspace/ch11/src/PropertiesEx3.java new file mode 100644 index 0000000..1d90ec6 --- /dev/null +++ b/workspace/ch11/src/PropertiesEx3.java @@ -0,0 +1,20 @@ +import java.util.*; +import java.io.*; + +class PropertiesEx3 { + public static void main(String[] args) { + Properties prop = new Properties(); + + prop.setProperty("timeout","30"); + prop.setProperty("language","ÇѱÛ"); + prop.setProperty("size","10"); + prop.setProperty("capacity","10"); + + try { + prop.store(new FileOutputStream("output.txt"), "Properties Example"); + prop.storeToXML(new FileOutputStream("output.xml"), "Properties Example"); + } catch(IOException e) { + e.printStackTrace(); + } + } // mainÀÇ ³¡ +} diff --git a/workspace/ch11/src/PropertiesEx4.java b/workspace/ch11/src/PropertiesEx4.java new file mode 100644 index 0000000..2afe6da --- /dev/null +++ b/workspace/ch11/src/PropertiesEx4.java @@ -0,0 +1,10 @@ +import java.util.*; + +class PropertiesEx4{ + public static void main(String[] args) { + Properties sysProp = System.getProperties(); + System.out.println("java.version :" + sysProp.getProperty("java.version")); + System.out.println("user.languag :" + sysProp.getProperty("user.language")); + sysProp.list(System.out); + } +} diff --git a/workspace/ch11/src/QueueEx1.java b/workspace/ch11/src/QueueEx1.java new file mode 100644 index 0000000..95bba8a --- /dev/null +++ b/workspace/ch11/src/QueueEx1.java @@ -0,0 +1,56 @@ +import java.util.*; + +class QueueEx1 { + static Queue q = new LinkedList(); + static final int MAX_SIZE = 5; // Queue¿¡ ÃÖ´ë 5°³±îÁö¸¸ ÀúÀåµÇµµ·Ï ÇÑ´Ù. + + public static void main(String[] args) { + System.out.println("help¸¦ ÀÔ·ÂÇÏ¸é µµ¿ò¸»À» º¼ ¼ö ÀÖ½À´Ï´Ù."); + + while(true) { + System.out.print(">>"); + try { + // È­¸éÀ¸·ÎºÎÅÍ ¶óÀδÜÀ§·Î ÀԷ¹޴´Ù. + Scanner s = new Scanner(System.in); + String input = s.nextLine().trim(); + + if("".equals(input)) continue; + + if(input.equalsIgnoreCase("q")) { + System.exit(0); + } else if(input.equalsIgnoreCase("help")) { + System.out.println(" help - µµ¿ò¸»À» º¸¿©ÁÝ´Ï´Ù."); + System.out.println(" q ¶Ç´Â Q - ÇÁ·Î±×·¥À» Á¾·áÇÕ´Ï´Ù."); + System.out.println(" history - ÃÖ±Ù¿¡ ÀÔ·ÂÇÑ ¸í·É¾î¸¦ " + MAX_SIZE +"°³ º¸¿©ÁÝ´Ï´Ù."); + } else if(input.equalsIgnoreCase("history")) { + int i=0; + // ÀԷ¹ÞÀº ¸í·É¾î¸¦ ÀúÀåÇÏ°í, + save(input); + + // LinkedListÀÇ ³»¿ëÀ» º¸¿©ÁØ´Ù. + LinkedList tmp = (LinkedList)q; + ListIterator it = tmp.listIterator(); + + while(it.hasNext()) { + System.out.println(++i+"."+it.next()); + } + } else { + save(input); + System.out.println(input); + } // if(input.equalsIgnoreCase("q")) { + } catch(Exception e) { + System.out.println("ÀԷ¿À·ùÀÔ´Ï´Ù."); + } + } // while(true) + } // main() + + public static void save(String input) { + // queue¿¡ ÀúÀåÇÑ´Ù. + if(!"".equals(input)) + q.offer(input); + + // queueÀÇ ÃÖ´ëÅ©±â¸¦ ³ÑÀ¸¸é Á¦ÀÏ Ã³À½ ÀÔ·ÂµÈ °ÍÀ» »èÁ¦ÇÑ´Ù. + if(q.size() > MAX_SIZE) // size()´Â CollectionÀÎÅÍÆäÀ̽º¿¡ Á¤ÀÇ + q.remove(); + } +} // end of class diff --git a/workspace/ch11/src/StackEx1.java b/workspace/ch11/src/StackEx1.java new file mode 100644 index 0000000..4854633 --- /dev/null +++ b/workspace/ch11/src/StackEx1.java @@ -0,0 +1,54 @@ +import java.util.*; + +public class StackEx1 { + public static Stack back = new Stack(); + public static Stack forward = new Stack(); + + public static void main(String[] args) { + goURL("1.³×ÀÌÆ®"); + goURL("2.¾ßÈÄ"); + goURL("3.³×À̹ö"); + goURL("4.´ÙÀ½"); + + printStatus(); + + goBack(); + System.out.println("= µÚ·Î°¡±â ¹öÆ°À» ´©¸¥ ÈÄ ="); + printStatus(); + + goBack(); + System.out.println("= 'µÚ·Î' ¹öÆ°À» ´©¸¥ ÈÄ ="); + printStatus(); + + goForward(); + System.out.println("= '¾ÕÀ¸·Î' ¹öÆ°À» ´©¸¥ ÈÄ ="); + printStatus(); + + goURL("codechobo.com"); + System.out.println("= »õ·Î¿î ÁÖ¼Ò·Î À̵¿ ÈÄ ="); + printStatus(); + } + + public static void printStatus() { + System.out.println("back:"+back); + System.out.println("forward:"+forward); + System.out.println("ÇöÀçÈ­¸éÀº '" + back.peek()+"' ÀÔ´Ï´Ù."); + System.out.println(); + } + + public static void goURL(String url){ + back.push(url); + if(!forward.empty()) + forward.clear(); + } + + public static void goForward(){ + if(!forward.empty()) + back.push(forward.pop()); + } + + public static void goBack(){ + if(!back.empty()) + forward.push(back.pop()); + } +} diff --git a/workspace/ch11/src/StackQueueEx.java b/workspace/ch11/src/StackQueueEx.java new file mode 100644 index 0000000..0af44b6 --- /dev/null +++ b/workspace/ch11/src/StackQueueEx.java @@ -0,0 +1,26 @@ +import java.util.*; + +class StackQueueEx { + public static void main(String[] args) { + Stack st = new Stack(); + Queue q = new LinkedList(); // QueueÀÎÅÍÆäÀ̽ºÀÇ ±¸ÇöüÀÎ LinkedList¸¦ »ç¿ë + + st.push("0"); + st.push("1"); + st.push("2"); + + q.offer("0"); + q.offer("1"); + q.offer("2"); + + System.out.println("= Stack ="); + while(!st.empty()) { + System.out.println(st.pop()); + } + + System.out.println("= Queue ="); + while(!q.isEmpty()) { + System.out.println(q.poll()); + } + } +} diff --git a/workspace/ch11/src/TreeMapEx1.java b/workspace/ch11/src/TreeMapEx1.java new file mode 100644 index 0000000..64b19e7 --- /dev/null +++ b/workspace/ch11/src/TreeMapEx1.java @@ -0,0 +1,70 @@ +import java.util.*; + +class TreeMapEx1 { + public static void main(String[] args) { + String[] data = { "A","K","A","K","D","K","A","K","K","K","Z","D" }; + + TreeMap map = new TreeMap(); + + for(int i=0; i < data.length; i++) { + if(map.containsKey(data[i])) { + Integer value = (Integer)map.get(data[i]); + map.put(data[i], new Integer(value.intValue() + 1)); + } else { + map.put(data[i], new Integer(1)); + } + } + + Iterator it = map.entrySet().iterator(); + + System.out.println("= ±âº»Á¤·Ä ="); + while(it.hasNext()) { + Map.Entry entry = (Map.Entry)it.next(); + int value = ((Integer)entry.getValue()).intValue(); + System.out.println(entry.getKey() + " : " + printBar('#', value) + " " + value ); + } + System.out.println(); + + // mapÀ» ArrayList·Î º¯È¯ÇÑ ´ÙÀ½¿¡ Collectons.sort()·Î Á¤·Ä + Set set = map.entrySet(); + List list = new ArrayList(set); // ArrayList(Collection c) + + // static void sort(List list, Comparator c) + Collections.sort(list, new ValueComparator()); + + it = list.iterator(); + + System.out.println("= °ªÀÇ Å©±â°¡ Å« ¼ø¼­·Î Á¤·Ä ="); + while(it.hasNext()) { + Map.Entry entry = (Map.Entry)it.next(); + int value = ((Integer)entry.getValue()).intValue(); + System.out.println(entry.getKey() + " : " + printBar('#', value) + " " + value ); + } + + } // public static void main(String[] args) + + static class ValueComparator implements Comparator { + public int compare(Object o1, Object o2) { + if(o1 instanceof Map.Entry && o2 instanceof Map.Entry) { + Map.Entry e1 = (Map.Entry)o1; + Map.Entry e2 = (Map.Entry)o2; + + int v1 = ((Integer)e1.getValue()).intValue(); + int v2 = ((Integer)e2.getValue()).intValue(); + + return v2 - v1; + } + return -1; + } + } // static class ValueComparator implements Comparator { + + public static String printBar(char ch, int value) { + char[] bar = new char[value]; + + for(int i=0; i < bar.length; i++) { + bar[i] = ch; + } + + return new String(bar); + } +} diff --git a/workspace/ch11/src/TreeSetEx1.java b/workspace/ch11/src/TreeSetEx1.java new file mode 100644 index 0000000..f44d32c --- /dev/null +++ b/workspace/ch11/src/TreeSetEx1.java @@ -0,0 +1,29 @@ +import java.util.*; + +class TreeSetEx1 { + public static void main(String[] args) { + TreeSet set = new TreeSet(); + + String from = "b"; + String to = "d"; + + set.add("abc"); + set.add("alien"); + set.add("bat"); + set.add("car"); + set.add("Car"); + set.add("disc"); + set.add("dance"); + set.add("dZZZZ"); + set.add("dzzzz"); + set.add("elephant"); + set.add("elevator"); + set.add("fan"); + set.add("flower"); + + System.out.println(set); + System.out.println("range search : from " + from +" to "+ to); + System.out.println("result1 : " + set.subSet(from, to)); + System.out.println("result2 : " + set.subSet(from, to + "zzz")); + } +} diff --git a/workspace/ch11/src/TreeSetEx2.java b/workspace/ch11/src/TreeSetEx2.java new file mode 100644 index 0000000..4f302cb --- /dev/null +++ b/workspace/ch11/src/TreeSetEx2.java @@ -0,0 +1,14 @@ +import java.util.*; + +class TreeSetEx2 { + public static void main(String[] args) { + TreeSet set = new TreeSet(); + int[] score = {80, 95, 50, 35, 45, 65, 10, 100}; + + for(int i=0; i < score.length; i++) + set.add(new Integer(score[i])); + + System.out.println("50º¸´Ù ÀÛÀº °ª :" + set.headSet(new Integer(50))); + System.out.println("50º¸´Ù Å« °ª :" + set.tailSet(new Integer(50))); + } +} diff --git a/workspace/ch11/src/TreeSetLotto.java b/workspace/ch11/src/TreeSetLotto.java new file mode 100644 index 0000000..b7b216c --- /dev/null +++ b/workspace/ch11/src/TreeSetLotto.java @@ -0,0 +1,14 @@ +import java.util.*; + +class TreeSetLotto { + public static void main(String[] args) { + Set set = new TreeSet(); + + for (int i = 0; set.size() < 6 ; i++) { + int num = (int)(Math.random()*45) + 1; + set.add(num); // set.add(new Integer(num)); + } + + System.out.println(set); + } +} diff --git a/workspace/ch11/src/VectorEx1.java b/workspace/ch11/src/VectorEx1.java new file mode 100644 index 0000000..fec88dd --- /dev/null +++ b/workspace/ch11/src/VectorEx1.java @@ -0,0 +1,33 @@ +import java.util.*; + +class VectorEx1 { + public static void main(String[] args) { + Vector v = new Vector(5); // ¿ë·®(capacity)ÀÌ 5ÀÎ Vector¸¦ »ý¼ºÇÑ´Ù. + v.add("1"); + v.add("2"); + v.add("3"); + print(v); + + v.trimToSize(); // ºó °ø°£À» ¾ø¾Ø´Ù.(¿ë·®°ú Å©±â°¡ °°¾ÆÁø´Ù.) + System.out.println("=== After trimToSize() ==="); + print(v); + + v.ensureCapacity(6); + System.out.println("=== After ensureCapacity(6) ==="); + print(v); + + v.setSize(7); + System.out.println("=== After setSize(7) ==="); + print(v); + + v.clear(); + System.out.println("=== After clear() ==="); + print(v); + } + + public static void print(Vector v) { + System.out.println(v); + System.out.println("size :" + v.size()); + System.out.println("capacity :" + v.capacity()); + } +} diff --git a/workspace/ch12/.classpath b/workspace/ch12/.classpath new file mode 100644 index 0000000..fceb480 --- /dev/null +++ b/workspace/ch12/.classpath @@ -0,0 +1,6 @@ + + + + + + diff --git a/workspace/ch12/.project b/workspace/ch12/.project new file mode 100644 index 0000000..225e967 --- /dev/null +++ b/workspace/ch12/.project @@ -0,0 +1,17 @@ + + + ch12 + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/workspace/ch12/.settings/org.eclipse.jdt.core.prefs b/workspace/ch12/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..3a21537 --- /dev/null +++ b/workspace/ch12/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,11 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/workspace/ch12/src/AnnotationEx1.java b/workspace/ch12/src/AnnotationEx1.java new file mode 100644 index 0000000..4ffb19a --- /dev/null +++ b/workspace/ch12/src/AnnotationEx1.java @@ -0,0 +1,8 @@ +class Parent { + void parentMethod() { } +} + +class Child extends Parent { + @Override + void parentmethod() { } // Á¶»ó ¸Þ¼­µåÀÇ À̸§À» À߸øÀû¾úÀ½. +} diff --git a/workspace/ch12/src/AnnotationEx2.java b/workspace/ch12/src/AnnotationEx2.java new file mode 100644 index 0000000..9772a38 --- /dev/null +++ b/workspace/ch12/src/AnnotationEx2.java @@ -0,0 +1,24 @@ +class NewClass { + int newField; + + int getNewField() { + return newField; + } + + @Deprecated + int oldField; + + @Deprecated + int getOldField() { + return oldField; + } +} + +class AnnotationEx2 { + public static void main(String args[]) { + NewClass nc = new NewClass(); + + nc.oldField = 10; //@Depreacted°¡ ºÙÀº ´ë»óÀ» »ç¿ë + System.out.println(nc.getOldField()); //@Depreacted°¡ ºÙÀº ´ë»óÀ» »ç¿ë + } +} diff --git a/workspace/ch12/src/AnnotationEx3.java b/workspace/ch12/src/AnnotationEx3.java new file mode 100644 index 0000000..dfaca45 --- /dev/null +++ b/workspace/ch12/src/AnnotationEx3.java @@ -0,0 +1,33 @@ +import java.util.ArrayList; + +class NewClass2 { + int newField; + + int getNewField() { + return newField; + } + + @Deprecated + int oldField; + + @Deprecated + int getOldField() { + return oldField; + } +} + + +class AnnotationEx3 { + @SuppressWarnings("deprecation") // deprecation°ü·Ã °æ°í¸¦ ¾ïÁ¦ + public static void main(String args[]) { + NewClass2 nc = new NewClass2(); + + nc.oldField = 10; //@Depreacted°¡ ºÙÀº ´ë»óÀ» »ç¿ë + System.out.println(nc.getOldField()); //@Depreacted°¡ ºÙÀº ´ë»óÀ» »ç¿ë + + @SuppressWarnings("unchecked") // Áö³×¸¯½º °ü·Ã °æ°í¸¦ ¾ïÁ¦ + ArrayList list = new ArrayList(); // ŸÀÔÀ» ÁöÁ¤ÇÏÁö ¾ÊÀ½. + list.add(nc); + } +} + diff --git a/workspace/ch12/src/AnnotationEx4.java b/workspace/ch12/src/AnnotationEx4.java new file mode 100644 index 0000000..048d4a2 --- /dev/null +++ b/workspace/ch12/src/AnnotationEx4.java @@ -0,0 +1,30 @@ +import java.util.Arrays; + +class MyArrayList { + T[] arr; + + @SafeVarargs + @SuppressWarnings("varargs") + MyArrayList(T... arr) { + this.arr = arr; + } + + @SafeVarargs +// @SuppressWarnings("unchecked") + public static MyArrayList asList(T... a) { + return new MyArrayList<>(a); + } + + public String toString() { + return Arrays.toString(arr); + } +} + +class AnnotationEx4 { +// @SuppressWarnings("unchecked") + public static void main(String args[]) { + MyArrayList list = MyArrayList.asList("1","2","3"); + + System.out.println(list); + } +} diff --git a/workspace/ch12/src/AnnotationEx5.java b/workspace/ch12/src/AnnotationEx5.java new file mode 100644 index 0000000..6d2e9bf --- /dev/null +++ b/workspace/ch12/src/AnnotationEx5.java @@ -0,0 +1,44 @@ +import java.lang.annotation.*; + +@Deprecated +@SuppressWarnings("1111") // À¯È¿ÇÏÁö ¾ÊÀº ¾Ö³ÊÅ×À̼ÇÀº ¹«½ÃµÈ´Ù. +@TestInfo(testedBy="aaa", testDate=@DateTime(yymmdd="160101", hhmmss="235959")) +class AnnotationEx5 { + public static void main(String args[]) { + // AnnotaionEx5ÀÇ Class°´Ã¼¸¦ ¾ò´Â´Ù. + Class cls = AnnotationEx5.class; + + TestInfo anno = (TestInfo)cls.getAnnotation(TestInfo.class); + System.out.println("anno.testedBy()="+anno.testedBy()); + System.out.println("anno.testDate().yymmdd()="+anno.testDate().yymmdd()); + System.out.println("anno.testDate().hhmmss()="+anno.testDate().hhmmss()); + + for(String str : anno.testTools()) + System.out.println("testTools="+str); + + System.out.println(); + + // AnnotationEx5¿¡ Àû¿ëµÈ ¸ðµç ¾Ö³ÊÅ×À̼ÇÀ» °¡Á®¿Â´Ù. + Annotation[] annoArr = cls.getAnnotations(); + + for(Annotation a : annoArr) + System.out.println(a); + } // mainÀÇ ³¡ +} + +@Retention(RetentionPolicy.RUNTIME) // ½ÇÇà ½Ã¿¡ »ç¿ë°¡´ÉÇϵµ·Ï ÁöÁ¤ +@interface TestInfo { + int count() default 1; + String testedBy(); + String[] testTools() default "JUnit"; + TestType testType() default TestType.FIRST; + DateTime testDate(); +} + +@Retention(RetentionPolicy.RUNTIME) // ½ÇÇà ½Ã¿¡ »ç¿ë°¡´ÉÇϵµ·Ï ÁöÁ¤ +@interface DateTime { + String yymmdd(); + String hhmmss(); +} + +enum TestType { FIRST, FINAL } diff --git a/workspace/ch12/src/EnumEx1.java b/workspace/ch12/src/EnumEx1.java new file mode 100644 index 0000000..ead1a71 --- /dev/null +++ b/workspace/ch12/src/EnumEx1.java @@ -0,0 +1,43 @@ +enum Direction { EAST, SOUTH, WEST, NORTH } + +class EnumEx1 { + public static void main(String[] args) { + Direction d1 = Direction.EAST; + Direction d2 = Direction.valueOf("WEST"); + Direction d3 = Enum.valueOf(Direction.class, "EAST"); + + System.out.println("d1="+d1); + System.out.println("d2="+d2); + System.out.println("d3="+d3); + + System.out.println("d1==d2 ? "+ (d1==d2)); + System.out.println("d1==d3 ? "+ (d1==d3)); + System.out.println("d1.equals(d3) ? "+ d1.equals(d3)); +// System.out.println("d2 > d3 ? "+ (d1 > d3)); // ¿¡·¯ + System.out.println("d1.compareTo(d3) ? "+ (d1.compareTo(d3))); + System.out.println("d1.compareTo(d2) ? "+ (d1.compareTo(d2))); + + switch(d1) { + case EAST: // Direction.EAST¶ó°í ¾µ ¼ö ¾ø´Ù. + System.out.println("The direction is EAST."); + break; + case SOUTH: + System.out.println("The direction is SOUTH."); + break; + case WEST: + System.out.println("The direction is WEST."); + break; + case NORTH: + System.out.println("The direction is NORTH."); + break; + default: + System.out.println("Invalid direction."); +// break; + } + + Direction[] dArr = Direction.values(); + + for(Direction d : dArr) // for(Direction d : Direction.values()) + System.out.printf("%s=%d%n", d.name(), d.ordinal()); + } +} diff --git a/workspace/ch12/src/EnumEx2.java b/workspace/ch12/src/EnumEx2.java new file mode 100644 index 0000000..2865bf8 --- /dev/null +++ b/workspace/ch12/src/EnumEx2.java @@ -0,0 +1,53 @@ +enum Direction2 { + EAST(1, ">"), SOUTH(2,"V"), WEST(3, "<"), NORTH(4,"^"); + + private static final Direction2[] DIR_ARR = Direction2.values(); + private final int value; + private final String symbol; + + Direction2(int value, String symbol) { // private Direction(int value) + this.value = value; + this.symbol = symbol; + } + + public int getValue() { return value; } + public String getSymbol() { return symbol; } + + public static Direction2 of(int dir) { + if (dir < 1 || dir > 4) { + throw new IllegalArgumentException("Invalid value :" + dir); + } + return DIR_ARR[dir - 1]; + } + + // ¹æÇâÀ» ȸÀü½ÃÅ°´Â ¸Þ¼­µå. numÀÇ °ª¸¸Å­ 90µµ¾¿ ½Ã°è¹æÇâÀ¸·Î ȸÀüÇÑ´Ù. + public Direction2 rotate(int num) { + num = num % 4; + + if(num < 0) num +=4; // numÀÌ À½¼öÀÏ ¶§´Â ½Ã°è¹Ý´ë ¹æÇâÀ¸·Î ȸÀü + + return DIR_ARR[(value-1+num) % 4]; + } + + public String toString() { + return name()+getSymbol(); + } +} // enum Direction + +class EnumEx2 { + public static void main(String[] args) { + for(Direction2 d : Direction2.values()) + System.out.printf("%s=%d%n", d.name(), d.getValue()); + + Direction2 d1 = Direction2.EAST; + Direction2 d2 = Direction2.of(1); + + System.out.printf("d1=%s, %d%n", d1.name(), d1.getValue()); + System.out.printf("d2=%s, %d%n", d2.name(), d2.getValue()); + + System.out.println(Direction2.EAST.rotate(1)); + System.out.println(Direction2.EAST.rotate(2)); + System.out.println(Direction2.EAST.rotate(-1)); + System.out.println(Direction2.EAST.rotate(-2)); + } +} diff --git a/workspace/ch12/src/EnumEx3.java b/workspace/ch12/src/EnumEx3.java new file mode 100644 index 0000000..59648ab --- /dev/null +++ b/workspace/ch12/src/EnumEx3.java @@ -0,0 +1,25 @@ +enum Transportation { + BUS(100) { int fare(int distance) { return distance*BASIC_FARE;}}, + TRAIN(150) { int fare(int distance) { return distance*BASIC_FARE;}}, + SHIP(100) { int fare(int distance) { return distance*BASIC_FARE;}}, + AIRPLANE(300) { int fare(int distance) { return distance*BASIC_FARE;}}; + + protected final int BASIC_FARE; // protected·Î ÇØ¾ß °¢ »ó¼ö¿¡¼­ Á¢±Ù°¡´É + + Transportation(int basicFare) { // private Transportation(int basicFare) { + BASIC_FARE = basicFare; + } + + public int getBasicFare() { return BASIC_FARE; } + + abstract int fare(int distance); // °Å¸®¿¡ µû¸¥ ¿ä±Ý °è»ê +} + +class EnumEx3 { + public static void main(String[] args) { + System.out.println("bus fare=" +Transportation.BUS.fare(100)); + System.out.println("train fare=" +Transportation.TRAIN.fare(100)); + System.out.println("ship fare=" +Transportation.SHIP.fare(100)); + System.out.println("airplane fare="+Transportation.AIRPLANE.fare(100)); + } +} diff --git a/workspace/ch12/src/EnumEx4.java b/workspace/ch12/src/EnumEx4.java new file mode 100644 index 0000000..c2f6ec9 --- /dev/null +++ b/workspace/ch12/src/EnumEx4.java @@ -0,0 +1,63 @@ +abstract class MyEnum> implements Comparable { + static int id = 0; + + int ordinal; + String name = ""; + + public int ordinal() { return ordinal; } + + MyEnum(String name) { + this.name = name; + ordinal = id++; + } + + public int compareTo(T t) { + return ordinal - t.ordinal(); + } +} + +abstract class MyTransportation extends MyEnum { + static final MyTransportation BUS = new MyTransportation("BUS", 100) { + int fare(int distance) { return distance * BASIC_FARE; } + }; + static final MyTransportation TRAIN = new MyTransportation("TRAIN", 150) { + int fare(int distance) { return distance * BASIC_FARE; } + }; + static final MyTransportation SHIP = new MyTransportation("SHIP", 100) { + int fare(int distance) { return distance * BASIC_FARE; } + }; + static final MyTransportation AIRPLANE = + new MyTransportation("AIRPLANE", 300) { + int fare(int distance) { return distance * BASIC_FARE; } + }; + + abstract int fare(int distance); // Ãß»ó ¸Þ¼­µå + + protected final int BASIC_FARE; + + private MyTransportation(String name, int basicFare) { + super(name); + BASIC_FARE = basicFare; + } + + public String name() { return name; } + public String toString() { return name; } +} + +class EnumEx4 { + public static void main(String[] args) { + MyTransportation t1 = MyTransportation.BUS; + MyTransportation t2 = MyTransportation.BUS; + MyTransportation t3 = MyTransportation.TRAIN; + MyTransportation t4 = MyTransportation.SHIP; + MyTransportation t5 = MyTransportation.AIRPLANE; + + System.out.printf("t1=%s, %d%n", t1.name(), t1.ordinal()); + System.out.printf("t2=%s, %d%n", t2.name(), t2.ordinal()); + System.out.printf("t3=%s, %d%n", t3.name(), t3.ordinal()); + System.out.printf("t4=%s, %d%n", t4.name(), t4.ordinal()); + System.out.printf("t5=%s, %d%n", t5.name(), t5.ordinal()); + System.out.println("t1==t2 ? "+(t1==t2)); + System.out.println("t1.compareTo(t3)="+ t1.compareTo(t3)); + } +} diff --git a/workspace/ch12/src/FruitBoxEx1.java b/workspace/ch12/src/FruitBoxEx1.java new file mode 100644 index 0000000..b4ce41c --- /dev/null +++ b/workspace/ch12/src/FruitBoxEx1.java @@ -0,0 +1,38 @@ +import java.util.ArrayList; + +class Fruit { public String toString() { return "Fruit";}} +class Apple extends Fruit { public String toString() { return "Apple";}} +class Grape extends Fruit { public String toString() { return "Grape";}} +class Toy { public String toString() { return "Toy" ;}} + +class FruitBoxEx1 { + public static void main(String[] args) { + Box fruitBox = new Box(); + Box appleBox = new Box(); + Box toyBox = new Box(); +// Box grapeBox = new Box(); // ¿¡·¯. ŸÀÔ ºÒÀÏÄ¡ + + fruitBox.add(new Fruit()); + fruitBox.add(new Apple()); // OK. void add(Fruit item) + + + appleBox.add(new Apple()); + appleBox.add(new Apple()); +// appleBox.add(new Toy()); // ¿¡·¯. Box¿¡´Â Apple¸¸ ´ãÀ» ¼ö ÀÖÀ½ + + toyBox.add(new Toy()); +// toyBox.add(new Apple()); // ¿¡·¯. Box¿¡´Â AppleÀ» ´ãÀ» ¼ö ¾øÀ½ + + System.out.println(fruitBox); + System.out.println(appleBox); + System.out.println(toyBox); + } // mainÀÇ ³¡ +} + +class Box { + ArrayList list = new ArrayList(); + void add(T item) { list.add(item); } + T get(int i) { return list.get(i); } + int size() { return list.size(); } + public String toString() { return list.toString();} +} diff --git a/workspace/ch12/src/FruitBoxEx2.java b/workspace/ch12/src/FruitBoxEx2.java new file mode 100644 index 0000000..8a41b4d --- /dev/null +++ b/workspace/ch12/src/FruitBoxEx2.java @@ -0,0 +1,41 @@ +import java.util.ArrayList; + +class Fruit2 implements Eatable { + public String toString() { return "Fruit";} +} +class Apple2 extends Fruit2 { public String toString() { return "Apple";}} +class Grape2 extends Fruit2 { public String toString() { return "Grape";}} +class Toy2 { public String toString() { return "Toy" ;}} + +interface Eatable {} + +class FruitBoxEx2 { + public static void main(String[] args) { + FruitBox2 fruitBox = new FruitBox2(); + FruitBox2 appleBox = new FruitBox2(); + FruitBox2 grapeBox = new FruitBox2(); +// FruitBox2 grapeBox = new FruitBox2(); // ¿¡·¯. ŸÀÔ ºÒÀÏÄ¡ +// FruitBox2 toyBox = new FruitBox2(); // ¿¡·¯. + + fruitBox.add(new Fruit2()); + fruitBox.add(new Apple2()); + fruitBox.add(new Grape2()); + appleBox.add(new Apple2()); +// appleBox.add(new Grape2()); // ¿¡·¯. Grape´Â AppleÀÇ ÀÚ¼ÕÀÌ ¾Æ´Ô + grapeBox.add(new Grape2()); + + System.out.println("fruitBox-"+fruitBox); + System.out.println("appleBox-"+appleBox); + System.out.println("grapeBox-"+grapeBox); + } // main +} + +class FruitBox2 extends Box2 {} + +class Box2 { + ArrayList list = new ArrayList(); + void add(T item) { list.add(item); } + T get(int i) { return list.get(i); } + int size() { return list.size(); } + public String toString() { return list.toString();} +} diff --git a/workspace/ch12/src/FruitBoxEx3.java b/workspace/ch12/src/FruitBoxEx3.java new file mode 100644 index 0000000..0314ff1 --- /dev/null +++ b/workspace/ch12/src/FruitBoxEx3.java @@ -0,0 +1,49 @@ +import java.util.ArrayList; + +class Fruit3 { public String toString() { return "Fruit";}} +class Apple3 extends Fruit3 { public String toString() { return "Apple";}} +class Grape3 extends Fruit3 { public String toString() { return "Grape";}} + +class Juice { + String name; + + Juice(String name) { this.name = name + "Juice"; } + public String toString() { return name; } +} + +class Juicer { + static Juice makeJuice(FruitBox3 box) { + String tmp = ""; + + for(Fruit3 f : box.getList()) + tmp += f + " "; + return new Juice(tmp); + } +} + +class FruitBoxEx3 { + public static void main(String[] args) { + FruitBox3 fruitBox = new FruitBox3(); + FruitBox3 appleBox = new FruitBox3(); + + fruitBox.add(new Apple3()); + fruitBox.add(new Grape3()); + appleBox.add(new Apple3()); + appleBox.add(new Apple3()); + + System.out.println(Juicer.makeJuice(fruitBox)); + System.out.println(Juicer.makeJuice(appleBox)); + } // main +} + +class FruitBox3 extends Box3 {} + +class Box3 { +//class FruitBox { + ArrayList list = new ArrayList(); + void add(T item) { list.add(item); } + T get(int i) { return list.get(i); } + ArrayList getList() { return list; } + int size() { return list.size(); } + public String toString() { return list.toString();} +} diff --git a/workspace/ch12/src/FruitBoxEx4.java b/workspace/ch12/src/FruitBoxEx4.java new file mode 100644 index 0000000..d9ca2bc --- /dev/null +++ b/workspace/ch12/src/FruitBoxEx4.java @@ -0,0 +1,93 @@ +import java.util.*; + +class Fruit4 { + String name; + int weight; + + Fruit4(String name, int weight) { + this.name = name; + this.weight = weight; + } + + public String toString() { return name+"("+weight+")";} + +} + +class Apple4 extends Fruit4 { + Apple4(String name, int weight) { + super(name, weight); + } +} + +class Grape4 extends Fruit4 { + Grape4(String name, int weight) { + super(name, weight); + } +} + +class AppleComp implements Comparator { + public int compare(Apple4 t1, Apple4 t2) { + return t2.weight - t1.weight; + } +} + +class GrapeComp implements Comparator { + public int compare(Grape4 t1, Grape4 t2) { + return t2.weight - t1.weight; + } +} + +class FruitComp implements Comparator { + public int compare(Fruit4 t1, Fruit4 t2) { + return t1.weight - t2.weight; + } +} + +class FruitBoxEx4 { + public static void main(String[] args) { + FruitBox4 appleBox = new FruitBox4(); + FruitBox4 grapeBox = new FruitBox4(); + + appleBox.add(new Apple4("GreenApple", 300)); + appleBox.add(new Apple4("GreenApple", 100)); + appleBox.add(new Apple4("GreenApple", 200)); + + grapeBox.add(new Grape4("GreenGrape", 400)); + grapeBox.add(new Grape4("GreenGrape", 300)); + grapeBox.add(new Grape4("GreenGrape", 200)); + + Collections.sort(appleBox.getList(), new AppleComp()); + Collections.sort(grapeBox.getList(), new GrapeComp()); + System.out.println(appleBox); + System.out.println(grapeBox); + System.out.println(); + Collections.sort(appleBox.getList(), new FruitComp()); + Collections.sort(grapeBox.getList(), new FruitComp()); + System.out.println(appleBox); + System.out.println(grapeBox); + } // main +} + +class FruitBox4 extends Box4 {} + +class Box4 { + ArrayList list = new ArrayList(); + + void add(T item) { + list.add(item); + } + + T get(int i) { + return list.get(i); + } + + ArrayList getList() { return list; } + + int size() { + return list.size(); + } + + public String toString() { + return list.toString(); + } +} diff --git a/workspace/ch13/.classpath b/workspace/ch13/.classpath new file mode 100644 index 0000000..fceb480 --- /dev/null +++ b/workspace/ch13/.classpath @@ -0,0 +1,6 @@ + + + + + + diff --git a/workspace/ch13/.project b/workspace/ch13/.project new file mode 100644 index 0000000..9d90078 --- /dev/null +++ b/workspace/ch13/.project @@ -0,0 +1,17 @@ + + + ch13 + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/workspace/ch13/.settings/org.eclipse.jdt.core.prefs b/workspace/ch13/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..3a21537 --- /dev/null +++ b/workspace/ch13/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,11 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/workspace/ch13/src/ForkJoinEx1.java b/workspace/ch13/src/ForkJoinEx1.java new file mode 100644 index 0000000..12f47f2 --- /dev/null +++ b/workspace/ch13/src/ForkJoinEx1.java @@ -0,0 +1,63 @@ +import java.util.concurrent.*; + +class ForkJoinEx1 { + static final ForkJoinPool pool = new ForkJoinPool(); // ¾²·¹µåÇ®À» »ý¼º + + public static void main(String[] args) { + long from = 1L; + long to = 100_000_000L; + + SumTask task = new SumTask(from, to); + + long start = System.currentTimeMillis(); // ½ÃÀ۽ð£ ÃʱâÈ­ + Long result = pool.invoke(task); + + System.out.println("Elapsed time(4 Core):"+(System.currentTimeMillis()-start)); + System.out.printf("sum of %d~%d=%d%n", from, to, result); + System.out.println(); + + result = 0L; + start = System.currentTimeMillis(); // ½ÃÀ۽ð£ ÃʱâÈ­ + for(long i=from;i<=to;i++) + result += i; + + System.out.println("Elapsed time(1 Core):"+(System.currentTimeMillis()-start)); + System.out.printf("sum of %d~%d=%d%n", from, to, result); + } // mainÀÇ ³¡ +} + +class SumTask extends RecursiveTask { + long from; + long to; + + SumTask(long from, long to) { + this.from = from; + this.to = to; + } + + public Long compute() { + long size = to - from; + + if(size <= 5) // ´õÇÒ ¼ýÀÚ°¡ 5°³ ÀÌÇϸé + return sum(); // ¼ýÀÚÀÇ ÇÕÀ» ¹Ýȯ + + long half = (from+to)/2; + + // ¹üÀ§¸¦ ¹ÝÀ¸·Î ³ª´²¼­ µÎ °³ÀÇ ÀÛ¾÷À» »ý¼º + SumTask leftSum = new SumTask(from, half); + SumTask rightSum = new SumTask(half+1, to); + + leftSum.fork(); + + return rightSum.compute() + leftSum.join(); + } + + long sum() { // from~toÀÇ ¸ðµç ¼ýÀÚ¸¦ ´õÇÑ °á°ú¸¦ ¹Ýȯ + long tmp = 0L; + + for(long i=from;i<=to;i++) + tmp += i; + + return tmp; + } +} diff --git a/workspace/ch13/src/ThreadEx01.java b/workspace/ch13/src/ThreadEx01.java new file mode 100644 index 0000000..0560458 --- /dev/null +++ b/workspace/ch13/src/ThreadEx01.java @@ -0,0 +1,28 @@ +class ThreadEx01 { + public static void main(String args[]) { + ThreadEx1_1 t1 = new ThreadEx1_1(); + + Runnable r = new ThreadEx1_2(); + Thread t2 = new Thread(r); // »ý¼ºÀÚ Thread(Runnable target) + + t1.start(); + t2.start(); + } +} + +class ThreadEx1_1 extends Thread { + public void run() { + for(int i=0; i < 5; i++) { + System.out.println(getName()); // Á¶»óÀÎ ThreadÀÇ getName()À» È£Ãâ + } + } +} + +class ThreadEx1_2 implements Runnable { + public void run() { + for(int i=0; i < 5; i++) { + // Thread.currentThread() - ÇöÀç ½ÇÇàÁßÀÎ Thread¸¦ ¹ÝȯÇÑ´Ù. + System.out.println(Thread.currentThread().getName()); + } + } +} diff --git a/workspace/ch13/src/ThreadEx02.java b/workspace/ch13/src/ThreadEx02.java new file mode 100644 index 0000000..da819fe --- /dev/null +++ b/workspace/ch13/src/ThreadEx02.java @@ -0,0 +1,20 @@ + class ThreadEx02 { + public static void main(String args[]) throws Exception { + ThreadEx2_1 t1 = new ThreadEx2_1(); + t1.start(); + } +} + +class ThreadEx2_1 extends Thread { + public void run() { + throwException(); + } + + public void throwException() { + try { + throw new Exception(); + } catch(Exception e) { + e.printStackTrace(); + } + } +} diff --git a/workspace/ch13/src/ThreadEx03.java b/workspace/ch13/src/ThreadEx03.java new file mode 100644 index 0000000..797e5ed --- /dev/null +++ b/workspace/ch13/src/ThreadEx03.java @@ -0,0 +1,20 @@ +class ThreadEx03 { + public static void main(String args[]) throws Exception { + ThreadEx3_1 t1 = new ThreadEx3_1(); + t1.run(); + } +} + +class ThreadEx3_1 extends Thread { + public void run() { + throwException(); + } + + public void throwException() { + try { + throw new Exception(); + } catch(Exception e) { + e.printStackTrace(); + } + } +} diff --git a/workspace/ch13/src/ThreadEx04.java b/workspace/ch13/src/ThreadEx04.java new file mode 100644 index 0000000..ba573c9 --- /dev/null +++ b/workspace/ch13/src/ThreadEx04.java @@ -0,0 +1,16 @@ + class ThreadEx04 { + public static void main(String args[]) { + long startTime = System.currentTimeMillis(); + + for(int i=0; i < 500; i++) + System.out.printf("%s", new String("-")); + + System.out.print("¼Ò¿ä½Ã°£1:" +(System.currentTimeMillis()- startTime)); + + for(int i=0; i < 500; i++) + System.out.printf("%s", new String("|")); + + System.out.print("¼Ò¿ä½Ã°£2:"+(System.currentTimeMillis() - startTime)); + } +} + diff --git a/workspace/ch13/src/ThreadEx05.java b/workspace/ch13/src/ThreadEx05.java new file mode 100644 index 0000000..76b6a91 --- /dev/null +++ b/workspace/ch13/src/ThreadEx05.java @@ -0,0 +1,25 @@ + class ThreadEx05 { + static long startTime = 0; + + public static void main(String args[]) { + ThreadEx5_1 th1 = new ThreadEx5_1(); + th1.start(); + startTime = System.currentTimeMillis(); + + for(int i=0; i < 300; i++) { + System.out.print("-"); + } + + System.out.print("¼Ò¿ä½Ã°£1:" + (System.currentTimeMillis() - ThreadEx05.startTime)); + } +} + +class ThreadEx5_1 extends Thread { + public void run() { + for(int i=0; i < 300; i++) { + System.out.print("|"); + } + + System.out.print("¼Ò¿ä½Ã°£2:" + (System.currentTimeMillis() - ThreadEx05.startTime)); + } +} diff --git a/workspace/ch13/src/ThreadEx06.java b/workspace/ch13/src/ThreadEx06.java new file mode 100644 index 0000000..830cbca --- /dev/null +++ b/workspace/ch13/src/ThreadEx06.java @@ -0,0 +1,16 @@ +import javax.swing.JOptionPane; + +class ThreadEx06 { + public static void main(String[] args) throws Exception + { + String input = JOptionPane.showInputDialog("¾Æ¹« °ªÀ̳ª ÀÔ·ÂÇϼ¼¿ä."); + System.out.println("ÀÔ·ÂÇϽŠ°ªÀº " + input + "ÀÔ´Ï´Ù."); + + for(int i=10; i > 0; i--) { + System.out.println(i); + try { + Thread.sleep(1000); + } catch(Exception e ) {} + } + } +} diff --git a/workspace/ch13/src/ThreadEx07.java b/workspace/ch13/src/ThreadEx07.java new file mode 100644 index 0000000..49f8150 --- /dev/null +++ b/workspace/ch13/src/ThreadEx07.java @@ -0,0 +1,22 @@ +import javax.swing.JOptionPane; + +class ThreadEx07 { + public static void main(String[] args) throws Exception { + ThreadEx7_1 th1 = new ThreadEx7_1(); + th1.start(); + + String input = JOptionPane.showInputDialog("¾Æ¹« °ªÀ̳ª ÀÔ·ÂÇϼ¼¿ä."); + System.out.println("ÀÔ·ÂÇϽŠ°ªÀº " + input + "ÀÔ´Ï´Ù."); + } +} + +class ThreadEx7_1 extends Thread { + public void run() { + for(int i=10; i > 0; i--) { + System.out.println(i); + try { + sleep(1000); + } catch(Exception e ) {} + } + } +} diff --git a/workspace/ch13/src/ThreadEx08.java b/workspace/ch13/src/ThreadEx08.java new file mode 100644 index 0000000..e619be6 --- /dev/null +++ b/workspace/ch13/src/ThreadEx08.java @@ -0,0 +1,31 @@ +class ThreadEx08 { + public static void main(String args[]) { + ThreadEx8_1 th1 = new ThreadEx8_1(); + ThreadEx8_2 th2 = new ThreadEx8_2(); + + th2.setPriority(7); + + System.out.println("Priority of th1(-) : " + th1.getPriority() ); + System.out.println("Priority of th2(|) : " + th2.getPriority() ); + th1.start(); + th2.start(); + } +} + +class ThreadEx8_1 extends Thread { + public void run() { + for(int i=0; i < 300; i++) { + System.out.print("-"); + for(int x=0; x < 10000000; x++); + } + } +} + +class ThreadEx8_2 extends Thread { + public void run() { + for(int i=0; i < 300; i++) { + System.out.print("|"); + for(int x=0; x < 10000000; x++); + } + } +} diff --git a/workspace/ch13/src/ThreadEx09.java b/workspace/ch13/src/ThreadEx09.java new file mode 100644 index 0000000..061d642 --- /dev/null +++ b/workspace/ch13/src/ThreadEx09.java @@ -0,0 +1,34 @@ + class ThreadEx09 { + public static void main(String args[]) throws Exception { + ThreadGroup main = Thread.currentThread().getThreadGroup(); + ThreadGroup grp1 = new ThreadGroup("Group1"); + ThreadGroup grp2 = new ThreadGroup("Group2"); + + // ThreadGroup(ThreadGroup parent, String name) + ThreadGroup subGrp1 = new ThreadGroup(grp1,"SubGroup1"); + + grp1.setMaxPriority(3); // ¾²·¹µå ±×·ì grp1ÀÇ ÃÖ´ë¿ì¼±¼øÀ§¸¦ 3À¸·Î º¯°æ. + + Runnable r = new Runnable() { + public void run() { + try { + Thread.sleep(1000); // ¾²·¹µå¸¦ 1ÃÊ°£ ¸ØÃß°Ô ÇÑ´Ù. + } catch(InterruptedException e) {} + } + }; + + // Thread(ThreadGroup tg, Runnable r, String name) + Thread th1 = new Thread(grp1, r, "th1"); + Thread th2 = new Thread(subGrp1, r, "th2"); + Thread th3 = new Thread(grp2, r, "th3"); + + th1.start(); + th2.start(); + th3.start(); + + System.out.println(">>List of ThreadGroup : "+ main.getName() + +", Active ThreadGroup: " + main.activeGroupCount() + +", Active Thread: " + main.activeCount()); + main.list(); + } +} diff --git a/workspace/ch13/src/ThreadEx10.java b/workspace/ch13/src/ThreadEx10.java new file mode 100644 index 0000000..5add959 --- /dev/null +++ b/workspace/ch13/src/ThreadEx10.java @@ -0,0 +1,38 @@ + class ThreadEx10 implements Runnable { + static boolean autoSave = false; + + public static void main(String[] args) { + Thread t = new Thread(new ThreadEx10()); + t.setDaemon(true); // ÀÌ ºÎºÐÀÌ ¾øÀ¸¸é Á¾·áµÇÁö ¾Ê´Â´Ù. + t.start(); + + for(int i=1; i <= 10; i++) { + try{ + Thread.sleep(1000); + } catch(InterruptedException e) {} + System.out.println(i); + + if(i==5) + autoSave = true; + } + + System.out.println("ÇÁ·Î±×·¥À» Á¾·áÇÕ´Ï´Ù."); + } + + public void run() { + while(true) { + try { + Thread.sleep(3 * 1000); // 3Ãʸ¶´Ù + } catch(InterruptedException e) {} + + // autoSaveÀÇ °ªÀÌ trueÀ̸é autoSave()¸¦ È£ÃâÇÑ´Ù. + if(autoSave) { + autoSave(); + } + } + } + + public void autoSave() { + System.out.println("ÀÛ¾÷ÆÄÀÏÀÌ ÀÚµ¿ÀúÀåµÇ¾ú½À´Ï´Ù."); + } +} diff --git a/workspace/ch13/src/ThreadEx11.java b/workspace/ch13/src/ThreadEx11.java new file mode 100644 index 0000000..b8930c5 --- /dev/null +++ b/workspace/ch13/src/ThreadEx11.java @@ -0,0 +1,50 @@ + import java.util.*; + +class ThreadEx11 { + public static void main(String args[]) throws Exception { + ThreadEx11_1 t1 = new ThreadEx11_1("Thread1"); + ThreadEx11_2 t2 = new ThreadEx11_2("Thread2"); + t1.start(); + t2.start(); + } +} + +class ThreadEx11_1 extends Thread { + ThreadEx11_1(String name) { + super(name); + } + + public void run() { + try { + sleep(5 * 1000); // 5ÃÊ µ¿¾È ±â´Ù¸°´Ù. + } catch(InterruptedException e) {} + } +} + +class ThreadEx11_2 extends Thread { + ThreadEx11_2(String name) { + super(name); + } + + public void run() { + Map map = getAllStackTraces(); + Iterator it = map.keySet().iterator(); + + int x=0; + while(it.hasNext()) { + Object obj = it.next(); + Thread t = (Thread)obj; + StackTraceElement[] ste = (StackTraceElement[])(map.get(obj)); + + System.out.println( "["+ ++x + "] name : " + t.getName() + + ", group : " + t.getThreadGroup().getName() + + ", daemon : " + t.isDaemon()); + + for(int i=0; i < ste.length; i++) { + System.out.println(ste[i]); + } + + System.out.println(); + } + } +} diff --git a/workspace/ch13/src/ThreadEx12.java b/workspace/ch13/src/ThreadEx12.java new file mode 100644 index 0000000..859a84a --- /dev/null +++ b/workspace/ch13/src/ThreadEx12.java @@ -0,0 +1,33 @@ + class ThreadEx12 { + public static void main(String args[]) { + ThreadEx12_1 th1 = new ThreadEx12_1(); + ThreadEx12_2 th2 = new ThreadEx12_2(); + + th1.start(); + th2.start(); + + try { + th1.sleep(2000); + } catch(InterruptedException e) {} + + System.out.print("<
>"); + } // main +} + +class ThreadEx12_1 extends Thread { + public void run() { + for(int i=0; i < 300; i++) { + System.out.print("-"); + } + System.out.print("<>"); + } // run() +} + +class ThreadEx12_2 extends Thread { + public void run() { + for(int i=0; i < 300; i++) { + System.out.print("|"); + } + System.out.print("<>"); + } // run() +} diff --git a/workspace/ch13/src/ThreadEx13.java b/workspace/ch13/src/ThreadEx13.java new file mode 100644 index 0000000..2e8bad1 --- /dev/null +++ b/workspace/ch13/src/ThreadEx13.java @@ -0,0 +1,26 @@ +import javax.swing.JOptionPane; + +class ThreadEx13_1 { + public static void main(String[] args) throws Exception { + ThreadEx13_2 th1 = new ThreadEx13_2(); + th1.start(); + + String input = JOptionPane.showInputDialog("¾Æ¹« °ªÀ̳ª ÀÔ·ÂÇϼ¼¿ä."); + System.out.println("ÀÔ·ÂÇϽŠ°ªÀº " + input + "ÀÔ´Ï´Ù."); + th1.interrupt(); // interrupt()¸¦ È£ÃâÇϸé, interrupted»óÅ°¡ true°¡ µÈ´Ù. + System.out.println("isInterrupted():"+ th1.isInterrupted()); // true + } +} + +class ThreadEx13_2 extends Thread { + public void run() { + int i = 10; + + while(i!=0 && !isInterrupted()) { + System.out.println(i--); + for(long x=0;x<2500000000L;x++); // ½Ã°£ Áö¿¬ + } + + System.out.println("Ä«¿îÆ®°¡ Á¾·áµÇ¾ú½À´Ï´Ù."); + } // main +} diff --git a/workspace/ch13/src/ThreadEx14.java b/workspace/ch13/src/ThreadEx14.java new file mode 100644 index 0000000..be64900 --- /dev/null +++ b/workspace/ch13/src/ThreadEx14.java @@ -0,0 +1,29 @@ +import javax.swing.JOptionPane; + +class ThreadEx14_1 { + public static void main(String[] args) throws Exception { + ThreadEx14_2 th1 = new ThreadEx14_2(); + th1.start(); + + String input = JOptionPane.showInputDialog("¾Æ¹« °ªÀ̳ª ÀÔ·ÂÇϼ¼¿ä."); + System.out.println("ÀÔ·ÂÇϽŠ°ªÀº " + input + "ÀÔ´Ï´Ù."); + th1.interrupt(); // interrupt()¸¦ È£ÃâÇϸé, interrupted»óÅ°¡ true°¡ µÈ´Ù. + System.out.println("isInterrupted():"+ th1.isInterrupted()); + } +} + +class ThreadEx14_2 extends Thread { + public void run() { + int i = 10; + + while(i!=0 && !isInterrupted()) { + System.out.println(i--); + + try { + Thread.sleep(1000); // 1ÃÊ Áö¿¬ + } catch(InterruptedException e) {} + } + + System.out.println("Ä«¿îÆ®°¡ Á¾·áµÇ¾ú½À´Ï´Ù."); + } // main +} diff --git a/workspace/ch13/src/ThreadEx15.java b/workspace/ch13/src/ThreadEx15.java new file mode 100644 index 0000000..56ad652 --- /dev/null +++ b/workspace/ch13/src/ThreadEx15.java @@ -0,0 +1,37 @@ + class ThreadEx15 { + public static void main(String args[]) { + RunImplEx15 r = new RunImplEx15(); + Thread th1 = new Thread(r, "*"); + Thread th2 = new Thread(r, "**"); + Thread th3 = new Thread(r, "***"); + + th1.start(); + th2.start(); + th3.start(); + + try { + Thread.sleep(2000); + th1.suspend(); // ¾²·¹µå th1À» Àá½Ã ÁߴܽÃŲ´Ù. + Thread.sleep(2000); + th2.suspend(); + Thread.sleep(3000); + th1.resume(); // ¾²·¹µå th1ÀÌ ´Ù½Ã µ¿ÀÛÇϵµ·Ï ÇÑ´Ù. + Thread.sleep(3000); + th1.stop(); // ¾²·¹µå th1À» °­Á¦Á¾·á½ÃŲ´Ù. + th2.stop(); + Thread.sleep(2000); + th3.stop(); + } catch (InterruptedException e) {} + } // main +} + +class RunImplEx15 implements Runnable { + public void run() { + while(true) { + System.out.println(Thread.currentThread().getName()); + try { + Thread.sleep(1000); + } catch(InterruptedException e) {} + } + } // run() +} diff --git a/workspace/ch13/src/ThreadEx16.java b/workspace/ch13/src/ThreadEx16.java new file mode 100644 index 0000000..acc3788 --- /dev/null +++ b/workspace/ch13/src/ThreadEx16.java @@ -0,0 +1,49 @@ + class ThreadEx16 { + public static void main(String args[]) { + RunImplEx16 r1 = new RunImplEx16(); + RunImplEx16 r2 = new RunImplEx16(); + RunImplEx16 r3 = new RunImplEx16(); + Thread th1 = new Thread(r1, "*"); + Thread th2 = new Thread(r2, "**"); + Thread th3 = new Thread(r3, "***"); + + th1.start(); + th2.start(); + th3.start(); + + try { + Thread.sleep(2000); + r1.suspend(); // th1.suspend()ÀÌ ¾Æ´Ô¿¡ ÁÖÀÇ + Thread.sleep(2000); + r2.suspend(); + Thread.sleep(3000); + r1.resume(); + Thread.sleep(3000); + r1.stop(); + r2.stop(); + Thread.sleep(2000); + r3.stop(); + } catch (InterruptedException e) {} + } +} + +class RunImplEx16 implements Runnable { + boolean suspended = false; + boolean stopped = false; + + public void run() { + while(!stopped) { + if(!suspended) { + System.out.println(Thread.currentThread().getName()); + try { + Thread.sleep(1000); + } catch(InterruptedException e) {} + } + } + System.out.println(Thread.currentThread().getName() + " - stopped"); + } + + public void suspend() { suspended = true; } + public void resume() { suspended = false; } + public void stop() { stopped = true; } +} diff --git a/workspace/ch13/src/ThreadEx17.java b/workspace/ch13/src/ThreadEx17.java new file mode 100644 index 0000000..09335b8 --- /dev/null +++ b/workspace/ch13/src/ThreadEx17.java @@ -0,0 +1,52 @@ + class ThreadEx17 { + public static void main(String args[]) { + ThreadEx17_1 th1 = new ThreadEx17_1("*"); + ThreadEx17_1 th2 = new ThreadEx17_1("**"); + ThreadEx17_1 th3 = new ThreadEx17_1("***"); + th1.start(); + th2.start(); + th3.start(); + + try { + Thread.sleep(2000); + th1.suspend(); + Thread.sleep(2000); + th2.suspend(); + Thread.sleep(3000); + th1.resume(); + Thread.sleep(3000); + th1.stop(); + th2.stop(); + Thread.sleep(2000); + th3.stop(); + } catch (InterruptedException e) {} + } +} + +class ThreadEx17_1 implements Runnable { + boolean suspended = false; + boolean stopped = false; + + Thread th; + + ThreadEx17_1(String name) { + th = new Thread(this, name); // Thread(Runnable r, String name) + } + + public void run() { + while(!stopped) { + if(!suspended) { + System.out.println(Thread.currentThread().getName()); + try { + Thread.sleep(1000); + } catch(InterruptedException e) {} + } + } + System.out.println(Thread.currentThread().getName() + " - stopped"); + } + + public void suspend() { suspended = true; } + public void resume() { suspended = false; } + public void stop() { stopped = true; } + public void start() { th.start(); } +} diff --git a/workspace/ch13/src/ThreadEx18.java b/workspace/ch13/src/ThreadEx18.java new file mode 100644 index 0000000..4569bfc --- /dev/null +++ b/workspace/ch13/src/ThreadEx18.java @@ -0,0 +1,73 @@ +class ThreadEx18 { + public static void main(String args[]) { + ThreadEx18_1 th1 = new ThreadEx18_1("*"); + ThreadEx18_1 th2 = new ThreadEx18_1("**"); + ThreadEx18_1 th3 = new ThreadEx18_1("***"); + th1.start(); + th2.start(); + th3.start(); + + try { + Thread.sleep(2000); + th1.suspend(); + Thread.sleep(2000); + th2.suspend(); + Thread.sleep(3000); + th1.resume(); + Thread.sleep(3000); + th1.stop(); + th2.stop(); + Thread.sleep(2000); + th3.stop(); + } catch (InterruptedException e) {} + } +} + +class ThreadEx18_1 implements Runnable { + boolean suspended = false; + boolean stopped = false; + + Thread th; + + ThreadEx18_1(String name) { + th = new Thread(this, name); // Thread(Runnable r, String name) + } + + public void run() { + String name =th.getName(); + + while(!stopped) { + if(!suspended) { + System.out.println(name); + try { + Thread.sleep(1000); + } catch(InterruptedException e) { + System.out.println(name + " - interrupted"); + } + } else { + Thread.yield(); + } + } + System.out.println(name + " - stopped"); + } + + public void suspend() { + suspended = true; + th.interrupt(); + System.out.println(th.getName() + " - interrupt() by suspend()"); + } + + public void resume() { + suspended = false; + } + + public void stop() { + stopped = true; + th.interrupt(); + System.out.println(th.getName() + " - interrupt() by stop()"); + } + + public void start() { + th.start(); + } +} diff --git a/workspace/ch13/src/ThreadEx19.java b/workspace/ch13/src/ThreadEx19.java new file mode 100644 index 0000000..40bc617 --- /dev/null +++ b/workspace/ch13/src/ThreadEx19.java @@ -0,0 +1,35 @@ + class ThreadEx19 { + static long startTime = 0; + + public static void main(String args[]) { + ThreadEx19_1 th1 = new ThreadEx19_1(); + ThreadEx19_2 th2 = new ThreadEx19_2(); + + th1.start(); + th2.start(); + startTime = System.currentTimeMillis(); + + try { + th1.join(); // main¾²·¹µå°¡ th1ÀÇ ÀÛ¾÷ÀÌ ³¡³¯ ¶§±îÁö ±â´Ù¸°´Ù. + th2.join(); // main¾²·¹µå°¡ th2ÀÇ ÀÛ¾÷ÀÌ ³¡³¯ ¶§±îÁö ±â´Ù¸°´Ù. + } catch(InterruptedException e) {} + + System.out.print("¼Ò¿ä½Ã°£:" + (System.currentTimeMillis() - ThreadEx19.startTime)); + } // main +} + +class ThreadEx19_1 extends Thread { + public void run() { + for(int i=0; i < 300; i++) { + System.out.print(new String("-")); + } + } // run() +} + +class ThreadEx19_2 extends Thread { + public void run() { + for(int i=0; i < 300; i++) { + System.out.print(new String("|")); + } + } // run() +} diff --git a/workspace/ch13/src/ThreadEx20.java b/workspace/ch13/src/ThreadEx20.java new file mode 100644 index 0000000..2c75ea5 --- /dev/null +++ b/workspace/ch13/src/ThreadEx20.java @@ -0,0 +1,53 @@ +class ThreadEx20 { + public static void main(String args[]) { + ThreadEx20_1 gc = new ThreadEx20_1(); + gc.setDaemon(true); + gc.start(); + + int requiredMemory = 0; + + for(int i=0; i < 20; i++) { + requiredMemory = (int)(Math.random() * 10) * 20; + + // ÇÊ¿äÇÑ ¸Þ¸ð¸®°¡ »ç¿ëÇÒ ¼ö ÀÖ´Â ¾çº¸´Ù Å©°Å³ª Àüü ¸Þ¸ð¸®ÀÇ 60%ÀÌ»óÀ» + // »ç¿ëÇßÀ» °æ¿ì gc¸¦ ±ú¿î´Ù. + if(gc.freeMemory() < requiredMemory || gc.freeMemory() < gc.totalMemory() * 0.4) { + gc.interrupt(); // ÀáÀÚ°í ÀÖ´Â ¾²·¹µå t1À» ±ú¿î´Ù. + } + + gc.usedMemory += requiredMemory; + System.out.println("usedMemory:"+gc.usedMemory); + } + } +} + +class ThreadEx20_1 extends Thread { + final static int MAX_MEMORY = 1000; + int usedMemory = 0; + + public void run() { + while(true) { + try { + Thread.sleep(10 * 1000); // 10Ãʸ¦ ±â´Ù¸°´Ù. + } catch(InterruptedException e) { + System.out.println("Awaken by interrupt()."); + } + + gc(); // garbage collectionÀ» ¼öÇàÇÑ´Ù. + System.out.println("Garbage Collected. Free Memory :" + freeMemory()); + } + } + + public void gc() { + usedMemory -= 300; + if(usedMemory < 0) usedMemory = 0; + } + + public int totalMemory() { + return MAX_MEMORY; + } + + public int freeMemory() { + return MAX_MEMORY - usedMemory; + } +} diff --git a/workspace/ch13/src/ThreadEx21.java b/workspace/ch13/src/ThreadEx21.java new file mode 100644 index 0000000..98e58a1 --- /dev/null +++ b/workspace/ch13/src/ThreadEx21.java @@ -0,0 +1,35 @@ +class ThreadEx21 { + public static void main(String args[]) { + Runnable r = new RunnableEx21(); + new Thread(r).start(); // ThreadGroup¿¡ ÀÇÇØ ÂüÁ¶µÇ¹Ç·Î gc´ë»óÀÌ ¾Æ´Ï´Ù. + new Thread(r).start(); // ThreadGroup¿¡ ÀÇÇØ ÂüÁ¶µÇ¹Ç·Î gc´ë»óÀÌ ¾Æ´Ï´Ù. + } +} + +class Account { + private int balance = 1000; + + public int getBalance() { + return balance; + } + + public void withdraw(int money){ + if(balance >= money) { + try { Thread.sleep(1000);} catch(InterruptedException e) {} + balance -= money; + } + } // withdraw +} + +class RunnableEx21 implements Runnable { + Account acc = new Account(); + + public void run() { + while(acc.getBalance() > 0) { + // 100, 200, 300ÁßÀÇ ÇÑ °ªÀ» ÀÓÀ¸·Î ¼±ÅÃÇؼ­ Ãâ±Ý(withdraw) + int money = (int)(Math.random() * 3 + 1) * 100; + acc.withdraw(money); + System.out.println("balance:"+acc.getBalance()); + } + } // run() +} diff --git a/workspace/ch13/src/ThreadEx22.java b/workspace/ch13/src/ThreadEx22.java new file mode 100644 index 0000000..f57ba67 --- /dev/null +++ b/workspace/ch13/src/ThreadEx22.java @@ -0,0 +1,35 @@ +class ThreadEx22 { + public static void main(String args[]) { + Runnable r = new RunnableEx22(); + new Thread(r).start(); + new Thread(r).start(); + } +} + +class Account2 { + private int balance = 1000; // privateÀ¸·Î ÇØ¾ß µ¿±âÈ­°¡ Àǹ̰¡ ÀÖ´Ù. + + public int getBalance() { + return balance; + } + + public synchronized void withdraw(int money){ // synchronized·Î ¸Þ¼­µå¸¦ µ¿±âÈ­ + if(balance >= money) { + try { Thread.sleep(1000);} catch(InterruptedException e) {} + balance -= money; + } + } // withdraw +} + +class RunnableEx22 implements Runnable { + Account2 acc = new Account2(); + + public void run() { + while(acc.getBalance() > 0) { + // 100, 200, 300ÁßÀÇ ÇÑ °ªÀ» ÀÓÀ¸·Î ¼±ÅÃÇؼ­ Ãâ±Ý(withdraw) + int money = (int)(Math.random() * 3 + 1) * 100; + acc.withdraw(money); + System.out.println("balance:"+acc.getBalance()); + } + } // run() +} diff --git a/workspace/ch13/src/ThreadWaitEx1.java b/workspace/ch13/src/ThreadWaitEx1.java new file mode 100644 index 0000000..8f8d777 --- /dev/null +++ b/workspace/ch13/src/ThreadWaitEx1.java @@ -0,0 +1,83 @@ +import java.util.ArrayList; + +class ThreadWaitEx1 { + public static void main(String[] args) throws Exception { + Table table = new Table(); // ¿©·¯ ¾²·¹µå°¡ °øÀ¯ÇÏ´Â °´Ã¼ + + new Thread(new Cook(table), "COOK1").start(); + new Thread(new Customer(table, "donut"), "CUST1").start(); + new Thread(new Customer(table, "burger"), "CUST2").start(); + + // 0.1ÃÊ(100 ¹Ð¸® ¼¼ÄÁµå) ÈÄ¿¡ °­Á¦ Á¾·á½ÃŲ´Ù. + Thread.sleep(100); + System.exit(0); + } +} + +class Customer implements Runnable { + private Table table; + private String food; + + Customer(Table table, String food) { + this.table = table; + this.food = food; + } + + public void run() { + while(true) { + try { Thread.sleep(10);} catch(InterruptedException e) {} + String name = Thread.currentThread().getName(); + + if(eatFood()) + System.out.println(name + " ate a " + food); + else + System.out.println(name + " failed to eat. :("); + } // while + } + + boolean eatFood() { return table.remove(food); } +} + +class Cook implements Runnable { + private Table table; + + Cook(Table table) { this.table = table; } + + public void run() { + while(true) { + // ÀÓÀÇÀÇ ¿ä¸®¸¦ Çϳª ¼±ÅÃÇؼ­ table¿¡ Ãß°¡ÇÑ´Ù. + int idx = (int)(Math.random()*table.dishNum()); + table.add(table.dishNames[idx]); + + try { Thread.sleep(1);} catch(InterruptedException e) {} + } // while + } +} + +class Table { + String[] dishNames = { "donut","donut","burger" }; // donutÀÌ ´õ ÀÚÁÖ ³ª¿Â´Ù. + final int MAX_FOOD = 6; // Å×ÀÌºí¿¡ ³õÀ» ¼ö ÀÖ´Â ÃÖ´ë À½½ÄÀÇ °³¼ö + +private ArrayList dishes = new ArrayList<>(); + + public void add(String dish) { + // Å×ÀÌºí¿¡ À½½ÄÀÌ °¡µæáÀ¸¸é, Å×ÀÌºí¿¡ À½½ÄÀ» Ãß°¡ÇÏÁö ¾Ê´Â´Ù. + if(dishes.size() >= MAX_FOOD) + return; + dishes.add(dish); + System.out.println("Dishes:" + dishes.toString()); + } + + public boolean remove(String dishName) { + // ÁöÁ¤µÈ ¿ä¸®¿Í ÀÏÄ¡ÇÏ´Â ¿ä¸®¸¦ Å×ÀÌºí¿¡¼­ Á¦°ÅÇÑ´Ù. + for(int i=0; i dishes = new ArrayList<>(); + + public synchronized void add(String dish) { // synchronized¸¦ Ãß°¡ + if(dishes.size() >= MAX_FOOD) + return; + dishes.add(dish); + System.out.println("Dishes:" + dishes.toString()); + } + + public boolean remove(String dishName) { + synchronized(this) { + while(dishes.size()==0) { + String name = Thread.currentThread().getName(); + System.out.println(name+" is waiting."); + try { Thread.sleep(500);} catch(InterruptedException e) {} + } + + for(int i=0; i dishes = new ArrayList<>(); + + public synchronized void add(String dish) { + while(dishes.size() >= MAX_FOOD) { + String name = Thread.currentThread().getName(); + System.out.println(name+" is waiting."); + try { + wait(); // COOK¾²·¹µå¸¦ ±â´Ù¸®°Ô ÇÑ´Ù. + Thread.sleep(500); + } catch(InterruptedException e) {} + } + dishes.add(dish); + notify(); // ±â´Ù¸®°í ÀÖ´Â CUST¸¦ ±ú¿ì±â À§ÇÔ. + System.out.println("Dishes:" + dishes.toString()); + } + + public void remove(String dishName) { + + synchronized(this) { + String name = Thread.currentThread().getName(); + + while(dishes.size()==0) { + System.out.println(name+" is waiting."); + try { + wait(); // CUST¾²·¹µå¸¦ ±â´Ù¸®°Ô ÇÑ´Ù. + Thread.sleep(500); + } catch(InterruptedException e) {} + } + + while(true) { + for(int i=0; i dishes = new ArrayList<>(); + + private ReentrantLock lock = new ReentrantLock(); + private Condition forCook = lock.newCondition(); + private Condition forCust = lock.newCondition(); + + public void add(String dish) { + lock.lock(); + + try { + while(dishes.size() >= MAX_FOOD) { + String name = Thread.currentThread().getName(); + System.out.println(name+" is waiting."); + try { + forCook.await(); // wait(); COOK¾²·¹µå¸¦ ±â´Ù¸®°Ô ÇÑ´Ù. + Thread.sleep(500); + } catch(InterruptedException e) {} + } + + dishes.add(dish); + forCust.signal(); // notify(); ±â´Ù¸®°í ÀÖ´Â CUST¸¦ ±ú¿ì±â À§ÇÔ. + System.out.println("Dishes:" + dishes.toString()); + } finally { + lock.unlock(); + } + } + + public void remove(String dishName) { + lock.lock(); // synchronized(this) { + String name = Thread.currentThread().getName(); + + try { + while(dishes.size()==0) { + System.out.println(name+" is waiting."); + try { + forCust.await(); // wait(); CUST¾²·¹µå¸¦ ±â´Ù¸®°Ô ÇÑ´Ù. + Thread.sleep(500); + } catch(InterruptedException e) {} + } + + while(true) { + for(int i=0; i + + + + + diff --git a/workspace/ch14/.project b/workspace/ch14/.project new file mode 100644 index 0000000..bb698c9 --- /dev/null +++ b/workspace/ch14/.project @@ -0,0 +1,17 @@ + + + ch14 + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/workspace/ch14/.settings/org.eclipse.jdt.core.prefs b/workspace/ch14/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..3a21537 --- /dev/null +++ b/workspace/ch14/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,11 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/workspace/ch14/src/CollectorEx1.java b/workspace/ch14/src/CollectorEx1.java new file mode 100644 index 0000000..7352577 --- /dev/null +++ b/workspace/ch14/src/CollectorEx1.java @@ -0,0 +1,48 @@ +import java.util.*; +import java.util.function.*; +import java.util.stream.*; + +class CollectorEx1 { + public static void main(String[] args) { + String[] strArr = { "aaa","bbb","ccc" }; + Stream strStream = Stream.of(strArr); + + String result = strStream.collect(new ConcatCollector()); + + System.out.println(Arrays.toString(strArr)); + System.out.println("result="+result); + } +} + +class ConcatCollector implements Collector { + @Override + public Supplier supplier() { + return () -> new StringBuilder(); +// return StringBuilder::new; + } + + @Override + public BiConsumer accumulator() { + return (sb, s) -> sb.append(s); +// return StringBuilder::append; + } + + @Override + public Function finisher() { + return sb -> sb.toString(); +// return StringBuilder::toString; + } + + @Override + public BinaryOperator combiner() { + return (sb, sb2)-> { + sb.append(sb2); + return sb; + }; + } + + @Override + public Set characteristics() { + return Collections.emptySet(); + } +} diff --git a/workspace/ch14/src/FileMerge.java b/workspace/ch14/src/FileMerge.java new file mode 100644 index 0000000..4ee4d76 --- /dev/null +++ b/workspace/ch14/src/FileMerge.java @@ -0,0 +1,49 @@ +import java.io.*; + +class FileMerge { + public static void main(String[] args) { + if (args.length != 1) { + System.out.println("USAGE : java FileMerge filename"); + System.exit(0); // ÇÁ·Î±×·¥À» Á¾·áÇÑ´Ù. + } + + String mergeFilename = args[0]; + + try { + + File tempFile = File.createTempFile("~mergetemp",".tmp"); + tempFile.deleteOnExit(); + + FileOutputStream fos = new FileOutputStream(tempFile); + BufferedOutputStream bos = new BufferedOutputStream(fos); + + BufferedInputStream bis = null; + + int number = 1; + + File f = new File(mergeFilename + "_." + number); + + while(f.exists()) { + f.setReadOnly(); // ÀÛ¾÷Áß¿¡ ÆÄÀÏÀÇ ³»¿ëÀÌ º¯°æµÇÁö ¾Êµµ·Ï ÇÑ´Ù. + bis = new BufferedInputStream(new FileInputStream(f)); + + int data = 0; + while((data = bis.read()) != -1) { + bos.write(data); + } + + bis.close(); + + f = new File(mergeFilename + "_." + ++number); + } // while + + bos.close(); + + File oldFile = new File(mergeFilename); + + if(oldFile.exists()) oldFile.delete(); + + tempFile.renameTo(oldFile); + } catch (IOException e) {} + } // main +} // class diff --git a/workspace/ch14/src/LambdaEx1.java b/workspace/ch14/src/LambdaEx1.java new file mode 100644 index 0000000..26621f0 --- /dev/null +++ b/workspace/ch14/src/LambdaEx1.java @@ -0,0 +1,35 @@ +@FunctionalInterface +interface MyFunction { + void run(); // public abstract void run(); +} + +class LambdaEx1 { + static void execute(MyFunction f) { // ¸Å°³º¯¼öÀÇ Å¸ÀÔÀÌ MyFunctionÀÎ ¸Þ¼­µå + f.run(); + } + + static MyFunction getMyFunction() { // ¹Ýȯ ŸÀÔÀÌ MyFunctionÀÎ ¸Þ¼­µå + MyFunction f = () -> System.out.println("f3.run()"); + return f; + } + + public static void main(String[] args) { + // ¶÷´Ù½ÄÀ¸·Î MyFunctionÀÇ run()À» ±¸Çö + MyFunction f1 = ()-> System.out.println("f1.run()"); + + MyFunction f2 = new MyFunction() { // À͸íŬ·¡½º·Î run()À» ±¸Çö + public void run() { // publicÀ» ¹Ýµå½Ã ºÙ¿©¾ß ÇÔ + System.out.println("f2.run()"); + } + }; + + MyFunction f3 = getMyFunction(); + + f1.run(); + f2.run(); + f3.run(); + + execute(f1); + execute( ()-> System.out.println("run()") ); + } +} diff --git a/workspace/ch14/src/LambdaEx2.java b/workspace/ch14/src/LambdaEx2.java new file mode 100644 index 0000000..4690faa --- /dev/null +++ b/workspace/ch14/src/LambdaEx2.java @@ -0,0 +1,21 @@ +@FunctionalInterface +interface MyFunction2 { + void myMethod(); // public abstract void myMethod(); +} + +class LambdaEx2 { + public static void main(String[] args) { + MyFunction2 f = ()->{}; // MyFunction f = (MyFunction)(()->{}); + Object obj = (MyFunction2)(()-> {}); // ObjectŸÀÔÀ¸·Î Çüº¯È¯ÀÌ »ý·«µÊ + String str = ((Object)(MyFunction2)(()-> {})).toString(); + + System.out.println(f); + System.out.println(obj); + System.out.println(str); + +// System.out.println(()->{}); // ¿¡·¯. ¶÷´Ù½ÄÀº ObjectŸÀÔÀ¸·Î Çüº¯È¯ ¾ÈµÊ + System.out.println((MyFunction2)(()-> {})); +// System.out.println((MyFunction)(()-> {}).toString()); // ¿¡·¯ + System.out.println(((Object)(MyFunction2)(()-> {})).toString()); + } +} diff --git a/workspace/ch14/src/LambdaEx3.java b/workspace/ch14/src/LambdaEx3.java new file mode 100644 index 0000000..a56711f --- /dev/null +++ b/workspace/ch14/src/LambdaEx3.java @@ -0,0 +1,34 @@ +@FunctionalInterface +interface MyFunction3 { + void myMethod(); +} + +class Outer { + int val=10; // Outer.this.val + + class Inner { + int val=20; // this.val + + void method(int i) { // void method(final int i) { + int val=30; // final int val=30; +// i = 10; // ¿¡·¯. »ó¼öÀÇ °ªÀ» º¯°æÇÒ ¼ö ¾øÀ½. + + MyFunction3 f = () -> { + System.out.println(" i :" + i); + System.out.println(" val :" + val); + System.out.println(" this.val :" + ++this.val); + System.out.println("Outer.this.val :" + ++Outer.this.val); + }; + + f.myMethod(); + } + } // InnerŬ·¡½ºÀÇ ³¡ +} // OuterŬ·¡½ºÀÇ ³¡ + +class LambdaEx3 { + public static void main(String args[]) { + Outer outer = new Outer(); + Outer.Inner inner = outer.new Inner(); + inner.method(100); + } +} diff --git a/workspace/ch14/src/LambdaEx4.java b/workspace/ch14/src/LambdaEx4.java new file mode 100644 index 0000000..a12d6d2 --- /dev/null +++ b/workspace/ch14/src/LambdaEx4.java @@ -0,0 +1,30 @@ +import java.util.*; + +class LambdaEx4 { + public static void main(String[] args) { + ArrayList list = new ArrayList<>(); + for(int i=0;i<10;i++) + list.add(i); + + // listÀÇ ¸ðµç ¿ä¼Ò¸¦ Ãâ·Â + list.forEach(i->System.out.print(i+",")); + System.out.println(); + + // list¿¡¼­ 2 ¶Ç´Â 3ÀÇ ¹è¼ö¸¦ Á¦°ÅÇÑ´Ù. + list.removeIf(x-> x%2==0 || x%3==0); + System.out.println(list); + + list.replaceAll(i->i*10); // listÀÇ °¢ ¿ä¼Ò¿¡ 10À» °öÇÑ´Ù. + System.out.println(list); + + Map map = new HashMap<>(); + map.put("1", "1"); + map.put("2", "2"); + map.put("3", "3"); + map.put("4", "4"); + + // mapÀÇ ¸ðµç ¿ä¼Ò¸¦ {k,v}ÀÇ Çü½ÄÀ¸·Î Ãâ·ÂÇÑ´Ù. + map.forEach((k,v)-> System.out.print("{"+k+","+v+"},")); + System.out.println(); + } +} diff --git a/workspace/ch14/src/LambdaEx5.java b/workspace/ch14/src/LambdaEx5.java new file mode 100644 index 0000000..e2a272d --- /dev/null +++ b/workspace/ch14/src/LambdaEx5.java @@ -0,0 +1,43 @@ +import java.util.function.*; +import java.util.*; + +class LambdaEx5 { + public static void main(String[] args) { + Supplier s = ()-> (int)(Math.random()*100)+1; + Consumer c = i -> System.out.print(i+", "); + Predicate p = i -> i%2==0; + Function f = i -> i/10*10; // iÀÇ ÀÏÀÇ ÀÚ¸®¸¦ ¾ø¾Ø´Ù. + + List list = new ArrayList<>(); + makeRandomList(s, list); + System.out.println(list); + printEvenNum(p, c, list); + List newList = doSomething(f, list); + System.out.println(newList); + } + + static List doSomething(Function f, List list) { + List newList = new ArrayList(list.size()); + + for(T i : list) { + newList.add(f.apply(i)); + } + + return newList; + } + + static void printEvenNum(Predicate p, Consumer c, List list) { + System.out.print("["); + for(T i : list) { + if(p.test(i)) + c.accept(i); + } + System.out.println("]"); + } + + static void makeRandomList(Supplier s, List list) { + for(int i=0;i<10;i++) { + list.add(s.get()); + } + } +} diff --git a/workspace/ch14/src/LambdaEx6.java b/workspace/ch14/src/LambdaEx6.java new file mode 100644 index 0000000..9d4c31d --- /dev/null +++ b/workspace/ch14/src/LambdaEx6.java @@ -0,0 +1,44 @@ +import java.util.function.*; +import java.util.*; + +class LambdaEx6 { + public static void main(String[] args) { + IntSupplier s = ()-> (int)(Math.random()*100)+1; + IntConsumer c = i -> System.out.print(i+", "); + IntPredicate p = i -> i%2==0; + IntUnaryOperator op = i -> i/10*10; // iÀÇ ÀÏÀÇ ÀÚ¸®¸¦ ¾ø¾Ø´Ù. + + int[] arr = new int[10]; + + makeRandomList(s, arr); + System.out.println(Arrays.toString(arr)); + printEvenNum(p, c, arr); + int[] newArr = doSomething(op, arr); + System.out.println(Arrays.toString(newArr)); + } + + static void makeRandomList(IntSupplier s, int[] arr) { + for(int i=0;i f = (s) -> Integer.parseInt(s, 16); + Function g = (i) -> Integer.toBinaryString(i); + + Function h = f.andThen(g); + Function h2 = f.compose(g); + + System.out.println(h.apply("FF")); // "FF" ¡æ 255 ¡æ "11111111" + System.out.println(h2.apply(2)); // 2 ¡æ "10" ¡æ 16 + + + Function f2 = x -> x; // Ç×µî ÇÔ¼ö(identity function) + System.out.println(f2.apply("AAA")); // AAA°¡ ±×´ë·Î Ãâ·ÂµÊ + + Predicate p = i -> i < 100; + Predicate q = i -> i < 200; + Predicate r = i -> i%2 == 0; + Predicate notP = p.negate(); // i >= 100 + + Predicate all = notP.and(q).or(r); + System.out.println(all.test(150)); // true + + String str1 = "abc"; + String str2 = "abc"; + + // str1°ú str2°¡ °°ÀºÁö ºñ±³ÇÑ °á°ú¸¦ ¹Ýȯ + Predicate p2 = Predicate.isEqual(str1); + boolean result = p2.test(str2); + System.out.println(result); + } +} diff --git a/workspace/ch14/src/OptionalEx1.java b/workspace/ch14/src/OptionalEx1.java new file mode 100644 index 0000000..df372dd --- /dev/null +++ b/workspace/ch14/src/OptionalEx1.java @@ -0,0 +1,56 @@ +import java.util.*; + +class OptionalEx1 { + public static void main(String[] args) { + Optional optStr = Optional.of("abcde"); + Optional optInt = optStr.map(String::length); + System.out.println("optStr="+optStr.get()); + System.out.println("optInt="+optInt.get()); + + int result1 = Optional.of("123") + .filter(x->x.length() >0) + .map(Integer::parseInt).get(); + + int result2 = Optional.of("") + .filter(x->x.length() >0) + .map(Integer::parseInt).orElse(-1); + + System.out.println("result1="+result1); + System.out.println("result2="+result2); + + Optional.of("456").map(Integer::parseInt) + .ifPresent(x->System.out.printf("result3=%d%n",x)); + + OptionalInt optInt1 = OptionalInt.of(0); // 0À» ÀúÀå + OptionalInt optInt2 = OptionalInt.empty(); // ºó °´Ã¼¸¦ »ý¼º + + System.out.println(optInt1.isPresent()); // true + System.out.println(optInt2.isPresent()); // false + + System.out.println(optInt1.getAsInt()); // 0 +// System.out.println(optInt2.getAsInt()); // NoSuchElementException + System.out.println("optInt1 ="+optInt1); + System.out.println("optInt2="+optInt2); + System.out.println("optInt1.equals(optInt2)?"+optInt1.equals(optInt2)); + + Optional opt = Optional.ofNullable(null); // nullÀ» ÀúÀå + Optional opt2 = Optional.empty(); // ºó °´Ã¼¸¦ »ý¼º + System.out.println("opt ="+opt); + System.out.println("opt2="+opt2); + System.out.println("opt.equals(opt2)?"+opt.equals(opt2)); // true + + int result3 = optStrToInt(Optional.of("123"), 0); + int result4 = optStrToInt(Optional.of(""), 0); + + System.out.println("result3="+result3); + System.out.println("result3="+result4); + } + + static int optStrToInt(Optional optStr, int defaultValue) { + try { + return optStr.map(Integer::parseInt).get(); + } catch (Exception e){ + return defaultValue; + } + } +} \ No newline at end of file diff --git a/workspace/ch14/src/StreamEx1.java b/workspace/ch14/src/StreamEx1.java new file mode 100644 index 0000000..f07bd91 --- /dev/null +++ b/workspace/ch14/src/StreamEx1.java @@ -0,0 +1,45 @@ +import java.util.*; +import java.util.stream.*; + +class StreamEx1 { + public static void main(String[] args) { + Stream studentStream = Stream.of( + new Student("ÀÌÀÚ¹Ù", 3, 300), + new Student("±èÀÚ¹Ù", 1, 200), + new Student("¾ÈÀÚ¹Ù", 2, 100), + new Student("¹ÚÀÚ¹Ù", 2, 150), + new Student("¼ÒÀÚ¹Ù", 1, 200), + new Student("³ªÀÚ¹Ù", 3, 290), + new Student("°¨ÀÚ¹Ù", 3, 180) + ); + + studentStream.sorted(Comparator.comparing(Student::getBan) // ¹Ýº° Á¤·Ä + .thenComparing(Comparator.naturalOrder())) // ±âº» Á¤·Ä + .forEach(System.out::println); + } +} + +class Student implements Comparable { + String name; + int ban; + int totalScore; + + Student(String name, int ban, int totalScore) { + this.name =name; + this.ban =ban; + this.totalScore =totalScore; + } + + public String toString() { + return String.format("[%s, %d, %d]", name, ban, totalScore).toString(); + } + + String getName() { return name;} + int getBan() { return ban;} + int getTotalScore() { return totalScore;} + + // ÃÑÁ¡ ³»¸²Â÷¼øÀ» ±âº» Á¤·Ä·Î ÇÑ´Ù. + public int compareTo(Student s) { + return s.totalScore - this.totalScore; + } +} diff --git a/workspace/ch14/src/StreamEx2.java b/workspace/ch14/src/StreamEx2.java new file mode 100644 index 0000000..55aa449 --- /dev/null +++ b/workspace/ch14/src/StreamEx2.java @@ -0,0 +1,27 @@ +import java.io.*; +import java.util.stream.*; + +class StreamEx2 { + public static void main(String[] args) { + File[] fileArr = { new File("Ex1.java"), new File("Ex1.bak"), + new File("Ex2.java"), new File("Ex1"), new File("Ex1.txt") + }; + + Stream fileStream = Stream.of(fileArr); + + // map()À¸·Î StreamÀ» StreamÀ¸·Î º¯È¯ + Stream filenameStream = fileStream.map(File::getName); + filenameStream.forEach(System.out::println); // ¸ðµç ÆÄÀÏÀÇ À̸§À» Ãâ·Â + + fileStream = Stream.of(fileArr); // ½ºÆ®¸²À» ´Ù½Ã »ý¼º + + fileStream.map(File::getName) // Stream ¡æ Stream + .filter(s -> s.indexOf('.')!=-1) // È®ÀåÀÚ°¡ ¾ø´Â °ÍÀº Á¦¿Ü + .map(s -> s.substring(s.indexOf('.')+1)) // È®ÀåÀÚ¸¸ ÃßÃâ + .map(String::toUpperCase) // ¸ðµÎ ´ë¹®ÀÚ·Î º¯È¯ + .distinct() // Áߺ¹ Á¦°Å + .forEach(System.out::print); // JAVABAKTXT + + System.out.println(); + } +} diff --git a/workspace/ch14/src/StreamEx3.java b/workspace/ch14/src/StreamEx3.java new file mode 100644 index 0000000..19a3d7c --- /dev/null +++ b/workspace/ch14/src/StreamEx3.java @@ -0,0 +1,55 @@ +import java.util.*; +import java.util.stream.*; + +class StreamEx3 { + public static void main(String[] args) { + Student2[] stuArr = { + new Student2("ÀÌÀÚ¹Ù", 3, 300), + new Student2("±èÀÚ¹Ù", 1, 200), + new Student2("¾ÈÀÚ¹Ù", 2, 100), + new Student2("¹ÚÀÚ¹Ù", 2, 150), + new Student2("¼ÒÀÚ¹Ù", 1, 200), + new Student2("³ªÀÚ¹Ù", 3, 290), + new Student2("°¨ÀÚ¹Ù", 3, 180) + }; + + Stream stuStream = Stream.of(stuArr); + + stuStream.sorted(Comparator.comparing(Student2::getBan) + .thenComparing(Comparator.naturalOrder())) + .forEach(System.out::println); + + stuStream = Stream.of(stuArr); // ½ºÆ®¸²À» ´Ù½Ã »ý¼ºÇÑ´Ù. + IntStream stuScoreStream= stuStream.mapToInt(Student2::getTotalScore); + + IntSummaryStatistics stat = stuScoreStream.summaryStatistics(); + System.out.println("count="+stat.getCount()); + System.out.println("sum="+stat.getSum()); + System.out.printf("average=%.2f%n", stat.getAverage()); + System.out.println("min="+stat.getMin()); + System.out.println("max="+stat.getMax()); + } +} + +class Student2 implements Comparable { + String name; + int ban; + int totalScore; + Student2(String name, int ban, int totalScore) { + this.name = name; + this.ban = ban; + this.totalScore = totalScore; + } + + public String toString() { + return String.format("[%s, %d, %d]", name, ban, totalScore).toString(); + } + + String getName() { return name;} + int getBan() { return ban;} + int getTotalScore() { return totalScore;} + + public int compareTo(Student2 s) { + return s.totalScore - this.totalScore; + } +} diff --git a/workspace/ch14/src/StreamEx4.java b/workspace/ch14/src/StreamEx4.java new file mode 100644 index 0000000..f4b2c2d --- /dev/null +++ b/workspace/ch14/src/StreamEx4.java @@ -0,0 +1,46 @@ +import java.util.*; +import java.util.stream.*; + +class StreamEx4 { + public static void main(String[] args) { + + Stream strArrStrm = Stream.of( + new String[]{"abc", "def", "jkl"}, + new String[]{"ABC", "GHI", "JKL"} + ); + +// Stream> strStrmStrm = strArrStrm.map(Arrays::stream); + Stream strStrm = strArrStrm.flatMap(Arrays::stream); + + strStrm.map(String::toLowerCase) + .distinct() + .sorted() + .forEach(System.out::println); + System.out.println(); + + String[] lineArr = { + "Believe or not It is true", + "Do or do not There is no try", + }; + + Stream lineStream = Arrays.stream(lineArr); + lineStream.flatMap(line -> Stream.of(line.split(" +"))) + .map(String::toLowerCase) + .distinct() + .sorted() + .forEach(System.out::println); + System.out.println(); + + Stream strStrm1 = Stream.of("AAA", "ABC", "bBb", "Dd"); + Stream strStrm2 = Stream.of("bbb", "aaa", "ccc", "dd"); + + Stream> strStrmStrm = Stream.of(strStrm1, strStrm2); + + Stream strStream = strStrmStrm + .map(s -> s.toArray(String[]::new)) + .flatMap(Arrays::stream); + strStream.map(String::toLowerCase) + .distinct() + .forEach(System.out::println); + } +} diff --git a/workspace/ch14/src/StreamEx5.java b/workspace/ch14/src/StreamEx5.java new file mode 100644 index 0000000..14fcb4f --- /dev/null +++ b/workspace/ch14/src/StreamEx5.java @@ -0,0 +1,37 @@ +import java.util.*; +import java.util.stream.*; + +class StreamEx5 { + public static void main(String[] args) { + String[] strArr = { + "Inheritance", "Java", "Lambda", "stream", + "OptionalDouble", "IntStream", "count", "sum" + }; + + Stream.of(strArr).forEach(System.out::println); + + boolean noEmptyStr = Stream.of(strArr).noneMatch(s->s.length()==0); + Optional sWord = Stream.of(strArr) + .filter(s->s.charAt(0)=='s').findFirst(); + + System.out.println("noEmptyStr="+noEmptyStr); + System.out.println("sWord="+ sWord.get()); + + // StreamÀ» IntStreamÀ¸·Î º¯È¯ + IntStream intStream1 = Stream.of(strArr).mapToInt(String::length); + IntStream intStream2 = Stream.of(strArr).mapToInt(String::length); + IntStream intStream3 = Stream.of(strArr).mapToInt(String::length); + IntStream intStream4 = Stream.of(strArr).mapToInt(String::length); + + int count = intStream1.reduce(0, (a,b) -> a + 1); + int sum = intStream2.reduce(0, (a,b) -> a + b); + + OptionalInt max = intStream3.reduce(Integer::max); + OptionalInt min = intStream4.reduce(Integer::min); + + System.out.println("count="+count); + System.out.println("sum="+sum); + System.out.println("max="+ max.getAsInt()); + System.out.println("min="+ min.getAsInt()); + } +} diff --git a/workspace/ch14/src/StreamEx6.java b/workspace/ch14/src/StreamEx6.java new file mode 100644 index 0000000..21dbe70 --- /dev/null +++ b/workspace/ch14/src/StreamEx6.java @@ -0,0 +1,81 @@ +import java.util.*; +import java.util.stream.*; +import static java.util.stream.Collectors.*; + +class StreamEx6 { + public static void main(String[] args) { + Student3[] stuArr = { + new Student3("ÀÌÀÚ¹Ù", 3, 300), + new Student3("±èÀÚ¹Ù", 1, 200), + new Student3("¾ÈÀÚ¹Ù", 2, 100), + new Student3("¹ÚÀÚ¹Ù", 2, 150), + new Student3("¼ÒÀÚ¹Ù", 1, 200), + new Student3("³ªÀÚ¹Ù", 3, 290), + new Student3("°¨ÀÚ¹Ù", 3, 180) + }; + + // Çлý À̸§¸¸ »Ì¾Æ¼­ List¿¡ ÀúÀå + List names = Stream.of(stuArr).map(Student3::getName) + .collect(Collectors.toList()); + System.out.println(names); + + // ½ºÆ®¸²À» ¹è¿­·Î º¯È¯ + Student3[] stuArr2 = Stream.of(stuArr).toArray(Student3[]::new); + + for(Student3 s : stuArr2) + System.out.println(s); + + // ½ºÆ®¸²À» Map·Î º¯È¯. Çлý À̸§ÀÌ key + Map stuMap = Stream.of(stuArr) + .collect(Collectors.toMap(s->s.getName(), p->p)); + for(String name : stuMap.keySet()) + System.out.println(name +"-"+stuMap.get(name)); + + long count = Stream.of(stuArr).collect(counting()); + int totalScore = Stream.of(stuArr) + .collect(summingInt(Student3::getTotalScore)); + System.out.println("count="+count); + System.out.println("totalScore="+totalScore); + + totalScore = Stream.of(stuArr) + .collect(reducing(0, Student3::getTotalScore, Integer::sum)); + System.out.println("totalScore="+totalScore); + + Optional topStudent = Stream.of(stuArr) + .collect(maxBy(Comparator.comparingInt(Student3::getTotalScore))); + System.out.println("topStudent="+topStudent.get()); + + IntSummaryStatistics stat = Stream.of(stuArr) + .collect(summarizingInt(Student3::getTotalScore)); + System.out.println(stat); + + String stuNames = Stream.of(stuArr) + .map(Student3::getName) + .collect(joining(",", "{", "}")); + System.out.println(stuNames); + } +} + +class Student3 implements Comparable { + String name; + int ban; + int totalScore; + + Student3(String name, int ban, int totalScore) { + this.name =name; + this.ban =ban; + this.totalScore =totalScore; + } + + public String toString() { + return String.format("[%s, %d, %d]", name, ban, totalScore).toString(); + } + + String getName() { return name;} + int getBan() { return ban;} + int getTotalScore() { return totalScore;} + + public int compareTo(Student s) { + return s.totalScore - this.totalScore; + } +} diff --git a/workspace/ch14/src/StreamEx7.java b/workspace/ch14/src/StreamEx7.java new file mode 100644 index 0000000..d748cfa --- /dev/null +++ b/workspace/ch14/src/StreamEx7.java @@ -0,0 +1,106 @@ +import java.util.*; +import java.util.function.*; +import java.util.stream.*; +import static java.util.stream.Collectors.*; +import static java.util.Comparator.*; + +class Student4 { + String name; + boolean isMale; // ¼ºº° + int hak; // Çгâ + int ban; // ¹Ý + int score; + + Student4(String name, boolean isMale, int hak, int ban, int score) { + this.name = name; + this.isMale = isMale; + this.hak = hak; + this.ban = ban; + this.score = score; + } + String getName() { return name;} + boolean isMale() { return isMale;} + int getHak() { return hak;} + int getBan() { return ban;} + int getScore() { return score;} + + public String toString() { + return String.format("[%s, %s, %dÇгâ %d¹Ý, %3dÁ¡]", + name, isMale ? "³²":"¿©", hak, ban, score); + } + // groupingBy()¿¡¼­ »ç¿ë + enum Level { HIGH, MID, LOW } // ¼ºÀûÀ» »ó, Áß, ÇÏ ¼¼ ´Ü°è·Î ºÐ·ù +} + +class StreamEx7 { + public static void main(String[] args) { + Student4[] stuArr = { + new Student4("³ªÀÚ¹Ù", true, 1, 1, 300), + new Student4("±èÁö¹Ì", false, 1, 1, 250), + new Student4("±èÀÚ¹Ù", true, 1, 1, 200), + new Student4("ÀÌÁö¹Ì", false, 1, 2, 150), + new Student4("³²ÀÚ¹Ù", true, 1, 2, 100), + new Student4("¾ÈÁö¹Ì", false, 1, 2, 50), + new Student4("ȲÁö¹Ì", false, 1, 3, 100), + new Student4("°­Áö¹Ì", false, 1, 3, 150), + new Student4("ÀÌÀÚ¹Ù", true, 1, 3, 200), + + new Student4("³ªÀÚ¹Ù", true, 2, 1, 300), + new Student4("±èÁö¹Ì", false, 2, 1, 250), + new Student4("±èÀÚ¹Ù", true, 2, 1, 200), + new Student4("ÀÌÁö¹Ì", false, 2, 2, 150), + new Student4("³²ÀÚ¹Ù", true, 2, 2, 100), + new Student4("¾ÈÁö¹Ì", false, 2, 2, 50), + new Student4("ȲÁö¹Ì", false, 2, 3, 100), + new Student4("°­Áö¹Ì", false, 2, 3, 150), + new Student4("ÀÌÀÚ¹Ù", true, 2, 3, 200) + }; + + System.out.printf("1. ´Ü¼øºÐÇÒ(¼ºº°·Î ºÐÇÒ)%n"); + Map> stuBySex = Stream.of(stuArr) + .collect(partitioningBy(Student4::isMale)); + + List maleStudent = stuBySex.get(true); + List femaleStudent = stuBySex.get(false); + + for(Student4 s : maleStudent) System.out.println(s); + for(Student4 s : femaleStudent) System.out.println(s); + + System.out.printf("%n2. ´Ü¼øºÐÇÒ + Åë°è(¼ºº° Çлý¼ö)%n"); + Map stuNumBySex = Stream.of(stuArr) + .collect(partitioningBy(Student4::isMale, counting())); + + System.out.println("³²Çлý ¼ö :"+ stuNumBySex.get(true)); + System.out.println("¿©Çлý ¼ö :"+ stuNumBySex.get(false)); + + + System.out.printf("%n3. ´Ü¼øºÐÇÒ + Åë°è(¼ºº° 1µî)%n"); + Map> topScoreBySex = Stream.of(stuArr) + .collect(partitioningBy(Student4::isMale, + maxBy(comparingInt(Student4::getScore)) + )); + System.out.println("³²Çлý 1µî :"+ topScoreBySex.get(true)); + System.out.println("¿©Çлý 1µî :"+ topScoreBySex.get(false)); + + Map topScoreBySex2 = Stream.of(stuArr) + .collect(partitioningBy(Student4::isMale, + collectingAndThen( + maxBy(comparingInt(Student4::getScore)), Optional::get + ) + )); + System.out.println("³²Çлý 1µî :"+ topScoreBySex2.get(true)); + System.out.println("¿©Çлý 1µî :"+ topScoreBySex2.get(false)); + + System.out.printf("%n4. ´ÙÁߺÐÇÒ(¼ºº° ºÒÇÕ°ÝÀÚ, 100Á¡ ÀÌÇÏ)%n"); + + Map>> failedStuBySex = + Stream.of(stuArr).collect(partitioningBy(Student4::isMale, + partitioningBy(s -> s.getScore() <= 100)) + ); + List failedMaleStu = failedStuBySex.get(true).get(true); + List failedFemaleStu = failedStuBySex.get(false).get(true); + + for(Student4 s : failedMaleStu) System.out.println(s); + for(Student4 s : failedFemaleStu) System.out.println(s); + } +} diff --git a/workspace/ch14/src/StreamEx8.java b/workspace/ch14/src/StreamEx8.java new file mode 100644 index 0000000..e09b367 --- /dev/null +++ b/workspace/ch14/src/StreamEx8.java @@ -0,0 +1,154 @@ +import java.util.*; +import java.util.function.*; +import java.util.stream.*; +import static java.util.stream.Collectors.*; +import static java.util.Comparator.*; + +class Student5 { + String name; + boolean isMale; // ¼ºº° + int hak; // Çгâ + int ban; // ¹Ý + int score; + + Student5(String name, boolean isMale, int hak, int ban, int score) { + this.name = name; + this.isMale = isMale; + this.hak = hak; + this.ban = ban; + this.score = score; + } + + String getName() { return name;} + boolean isMale() { return isMale;} + int getHak() { return hak;} + int getBan() { return ban;} + int getScore() { return score;} + + public String toString() { + return String.format("[%s, %s, %dÇгâ %d¹Ý, %3dÁ¡]", name, isMale ? "³²":"¿©", hak, ban, score); + } + + enum Level { + HIGH, MID, LOW + } +} + +class StreamEx8 { + public static void main(String[] args) { + Student5[] stuArr = { + new Student5("³ªÀÚ¹Ù", true, 1, 1, 300), + new Student5("±èÁö¹Ì", false, 1, 1, 250), + new Student5("±èÀÚ¹Ù", true, 1, 1, 200), + new Student5("ÀÌÁö¹Ì", false, 1, 2, 150), + new Student5("³²ÀÚ¹Ù", true, 1, 2, 100), + new Student5("¾ÈÁö¹Ì", false, 1, 2, 50), + new Student5("ȲÁö¹Ì", false, 1, 3, 100), + new Student5("°­Áö¹Ì", false, 1, 3, 150), + new Student5("ÀÌÀÚ¹Ù", true, 1, 3, 200), + + new Student5("³ªÀÚ¹Ù", true, 2, 1, 300), + new Student5("±èÁö¹Ì", false, 2, 1, 250), + new Student5("±èÀÚ¹Ù", true, 2, 1, 200), + new Student5("ÀÌÁö¹Ì", false, 2, 2, 150), + new Student5("³²ÀÚ¹Ù", true, 2, 2, 100), + new Student5("¾ÈÁö¹Ì", false, 2, 2, 50), + new Student5("ȲÁö¹Ì", false, 2, 3, 100), + new Student5("°­Áö¹Ì", false, 2, 3, 150), + new Student5("ÀÌÀÚ¹Ù", true, 2, 3, 200) + }; + + System.out.printf("1. ´Ü¼ø±×·ìÈ­(¹Ýº°·Î ±×·ìÈ­)%n"); + Map> stuByBan = Stream.of(stuArr) + .collect(groupingBy(Student5::getBan)); + + for(List ban : stuByBan.values()) { + for(Student5 s : ban) { + System.out.println(s); + } + } + + System.out.printf("%n2. ´Ü¼ø±×·ìÈ­(¼ºÀûº°·Î ±×·ìÈ­)%n"); + Map> stuByLevel = Stream.of(stuArr) + .collect(groupingBy(s-> { + if(s.getScore() >= 200) return Student5.Level.HIGH; + else if(s.getScore() >= 100) return Student5.Level.MID; + else return Student5.Level.LOW; + })); + + TreeSet keySet = new TreeSet<>(stuByLevel.keySet()); + + for(Student5.Level key : keySet) { + System.out.println("["+key+"]"); + + for(Student5 s : stuByLevel.get(key)) + System.out.println(s); + System.out.println(); + } + + System.out.printf("%n3. ´Ü¼ø±×·ìÈ­ + Åë°è(¼ºÀûº° Çлý¼ö)%n"); + Map stuCntByLevel = Stream.of(stuArr) + .collect(groupingBy(s-> { + if(s.getScore() >= 200) return Student5.Level.HIGH; + else if(s.getScore() >= 100) return Student5.Level.MID; + else return Student5.Level.LOW; + }, counting())); + + for(Student5.Level key : stuCntByLevel.keySet()) + System.out.printf("[%s] - %d¸í, ", key, stuCntByLevel.get(key)); + System.out.println(); +/* + for(List level : stuByLevel.values()) { + System.out.println(); + for(Student5 s : level) { + System.out.println(s); + } + } +*/ + System.out.printf("%n4. ´ÙÁß±×·ìÈ­(Çг⺰, ¹Ýº°)%n"); + Map>> stuByHakAndBan = + Stream.of(stuArr) + .collect(groupingBy(Student5::getHak, + groupingBy(Student5::getBan) + )); + + for(Map> hak : stuByHakAndBan.values()) { + for(List ban : hak.values()) { + System.out.println(); + for(Student5 s : ban) + System.out.println(s); + } + } + + System.out.printf("%n5. ´ÙÁß±×·ìÈ­ + Åë°è(Çг⺰, ¹Ýº° 1µî)%n"); + Map> topStuByHakAndBan = Stream.of(stuArr) + .collect(groupingBy(Student5::getHak, + groupingBy(Student5::getBan, + collectingAndThen( + maxBy(comparingInt(Student5::getScore)), + Optional::get + ) + ) + )); + + for(Map ban : topStuByHakAndBan.values()) + for(Student5 s : ban.values()) + System.out.println(s); + + System.out.printf("%n6. ´ÙÁß±×·ìÈ­ + Åë°è(Çг⺰, ¹Ýº° ¼ºÀû±×·ì)%n"); + Map> stuByScoreGroup = Stream.of(stuArr) + .collect(groupingBy(s-> s.getHak() + "-" + s.getBan(), + mapping(s-> { + if(s.getScore() >= 200) return Student5.Level.HIGH; + else if(s.getScore() >= 100) return Student5.Level.MID; + else return Student5.Level.LOW; + } , toSet()) + )); + + Set keySet2 = stuByScoreGroup.keySet(); + + for(String key : keySet2) { + System.out.println("["+key+"]" + stuByScoreGroup.get(key)); + } + } // mainÀÇ ³¡ +} diff --git a/workspace/ch15/.classpath b/workspace/ch15/.classpath new file mode 100644 index 0000000..fceb480 --- /dev/null +++ b/workspace/ch15/.classpath @@ -0,0 +1,6 @@ + + + + + + diff --git a/workspace/ch15/.project b/workspace/ch15/.project new file mode 100644 index 0000000..ec318ad --- /dev/null +++ b/workspace/ch15/.project @@ -0,0 +1,17 @@ + + + ch15 + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/workspace/ch15/.settings/org.eclipse.jdt.core.prefs b/workspace/ch15/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..3a21537 --- /dev/null +++ b/workspace/ch15/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,11 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/workspace/ch15/src/BufferedOutputStreamEx1.java b/workspace/ch15/src/BufferedOutputStreamEx1.java new file mode 100644 index 0000000..471f784 --- /dev/null +++ b/workspace/ch15/src/BufferedOutputStreamEx1.java @@ -0,0 +1,19 @@ +import java.io.*; + +class BufferedOutputStreamEx1 { + public static void main(String args[]) { + try { + FileOutputStream fos = new FileOutputStream("123.txt"); + // BufferedOutputStreamÀÇ ¹öÆÛ Å©±â¸¦ 5·Î ÇÑ´Ù. + BufferedOutputStream bos = new BufferedOutputStream(fos, 5); + // ÆÄÀÏ 123.txt¿¡ 1 ºÎÅÍ 9±îÁö Ãâ·ÂÇÑ´Ù. + for(int i='1'; i <= '9'; i++) { + bos.write(i); + } + + fos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/workspace/ch15/src/BufferedReaderEx1.java b/workspace/ch15/src/BufferedReaderEx1.java new file mode 100644 index 0000000..db26384 --- /dev/null +++ b/workspace/ch15/src/BufferedReaderEx1.java @@ -0,0 +1,19 @@ +import java.io.*; + +class BufferedReaderEx1 { + public static void main(String[] args) { + try { + FileReader fr = new FileReader("BufferedReaderEx1.java"); + BufferedReader br = new BufferedReader(fr); + + String line = ""; + for(int i=1;(line = br.readLine())!=null;i++) { + // ";"¸¦ Æ÷ÇÔÇÑ ¶óÀÎÀ» Ãâ·ÂÇÑ´Ù. + if(line.indexOf(";")!=-1) + System.out.println(i+":"+line); + } + + br.close(); + } catch(IOException e) {} + } // main +} diff --git a/workspace/ch15/src/DataInputStreamEx1.java b/workspace/ch15/src/DataInputStreamEx1.java new file mode 100644 index 0000000..81605c0 --- /dev/null +++ b/workspace/ch15/src/DataInputStreamEx1.java @@ -0,0 +1,17 @@ +import java.io.*; + +class DataInputStreamEx1 { + public static void main(String args[]) { + try { + FileInputStream fis = new FileInputStream("sample.dat"); + DataInputStream dis = new DataInputStream(fis); + + System.out.println(dis.readInt()); + System.out.println(dis.readFloat()); + System.out.println(dis.readBoolean()); + dis.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } // main +} diff --git a/workspace/ch15/src/DataInputStreamEx2.java b/workspace/ch15/src/DataInputStreamEx2.java new file mode 100644 index 0000000..17352bb --- /dev/null +++ b/workspace/ch15/src/DataInputStreamEx2.java @@ -0,0 +1,33 @@ +import java.io.*; + +class DataInputStreamEx2 { + public static void main(String args[]) { + int sum = 0; + int score = 0; + + FileInputStream fis = null; + DataInputStream dis = null; + + try { + fis = new FileInputStream("score.dat"); + dis = new DataInputStream(fis); + + while(true) { + score = dis.readInt(); + System.out.println(score); + sum += score; + } + } catch (EOFException e) { + System.out.println("Á¡¼öÀÇ ÃÑÇÕÀº " + sum +"ÀÔ´Ï´Ù."); + } catch (IOException ie) { + ie.printStackTrace(); + } finally { + try { + if(dis!=null) + dis.close(); + } catch(IOException ie){ + ie.printStackTrace(); + } + } // try + } // main +} diff --git a/workspace/ch15/src/DataInputStreamEx3.java b/workspace/ch15/src/DataInputStreamEx3.java new file mode 100644 index 0000000..3fd7261 --- /dev/null +++ b/workspace/ch15/src/DataInputStreamEx3.java @@ -0,0 +1,23 @@ +import java.io.*; + +class DataInputStreamEx3 { + public static void main(String args[]) { + int sum = 0; + int score = 0; + + try (FileInputStream fis = new FileInputStream("score.dat"); + DataInputStream dis = new DataInputStream(fis)) + { + + while(true) { + score = dis.readInt(); + System.out.println(score); + sum += score; + } + } catch (EOFException e) { + System.out.println("Á¡¼öÀÇ ÃÑÇÕÀº " + sum +"ÀÔ´Ï´Ù."); + } catch (IOException ie) { + ie.printStackTrace(); + } // try + } // main +} diff --git a/workspace/ch15/src/DataOutputStreamEx1.java b/workspace/ch15/src/DataOutputStreamEx1.java new file mode 100644 index 0000000..691adf6 --- /dev/null +++ b/workspace/ch15/src/DataOutputStreamEx1.java @@ -0,0 +1,20 @@ +import java.io.*; + +class DataOutputStreamEx1 { + public static void main(String args[]) { + FileOutputStream fos = null; + DataOutputStream dos = null; + + try { + fos = new FileOutputStream("sample.dat"); + dos = new DataOutputStream(fos); + dos.writeInt(10); + dos.writeFloat(20.0f); + dos.writeBoolean(true); + + dos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } // main +} diff --git a/workspace/ch15/src/DataOutputStreamEx2.java b/workspace/ch15/src/DataOutputStreamEx2.java new file mode 100644 index 0000000..afe86c8 --- /dev/null +++ b/workspace/ch15/src/DataOutputStreamEx2.java @@ -0,0 +1,38 @@ +import java.io.*; +import java.util.Arrays; + +class DataOutputStreamEx2 { + public static void main(String args[]) { + ByteArrayOutputStream bos = null; + DataOutputStream dos = null; + + byte[] result = null; + + try { + bos = new ByteArrayOutputStream(); + dos = new DataOutputStream(bos); + dos.writeInt(10); + dos.writeFloat(20.0f); + dos.writeBoolean(true); + + result = bos.toByteArray(); + + String[] hex = new String[result.length]; + + for(int i=0;i 0) result = 1; + else if(time1 - time2 == 0) result = 0; + else if(time1 - time2 < 0) result = -1; + break; + case 'T' : + if(time1 - time2 > 0) result = -1; + else if(time1 - time2 == 0) result = 0; + else if(time1 - time2 < 0) result = 1; + break; + case 'l' : + if(length1 - length2 > 0) result = 1; + else if(length1 - length2 == 0) result = 0; + else if(length1 - length2 < 0) result = -1; + break; + case 'L' : + if(length1 - length2 > 0) result = -1; + else if(length1 - length2 == 0) result = 0; + else if(length1 - length2 < 0) result = 1; + break; + case 'n' : + result = name1.compareTo(name2); + break; + case 'N' : + result = name2.compareTo(name1); + break; + } + return result; + } // compare + + public boolean equals(Object o) { return false; } // not used. + }; // end of Comparator + + Arrays.sort(files, comp); + + for(int i=0; i < files.length; i++) { + File f = files[i]; + String name = f.getName(); + SimpleDateFormat df =new SimpleDateFormat("yyyy-MM-dd HH:mm"); + String attribute = ""; + String size = ""; + + if(files[i].isDirectory()) { + attribute = "DIR"; + } else { + size = f.length() + ""; + attribute = f.canRead() ? "R" : " "; + attribute += f.canWrite() ? "W" : " "; + attribute += f.isHidden() ? "H" : " "; + } + + System.out.printf("%s %3s %6s %s%n", df.format(new Date(f.lastModified())),attribute,size,name ); + } // for + } // main +} // end of class diff --git a/workspace/ch15/src/FileEx6.java b/workspace/ch15/src/FileEx6.java new file mode 100644 index 0000000..8bf1f3a --- /dev/null +++ b/workspace/ch15/src/FileEx6.java @@ -0,0 +1,64 @@ +import java.io.*; + +class FileEx6 { + static int found = 0; + + public static void main(String args[]) { + if(args.length != 2) { + System.out.println("USAGE : java FileEx6 DIRECTORY KEYWORD"); + System.exit(0); + } + + File dir = new File(args[0]); + String keyword = args[1]; + + if(!dir.exists() || !dir.isDirectory()) { + System.out.println("À¯È¿ÇÏÁö ¾ÊÀº µð·ºÅ丮ÀÔ´Ï´Ù."); + System.exit(0); + } + + try { + findInFiles(dir, keyword); + } catch(IOException e) { + e.printStackTrace(); + } + + System.out.println(); + System.out.println("ÃÑ " + found + "°³ÀÇ ¶óÀο¡¼­ '" + keyword + "'À»/¸¦ ¹ß°ßÇÏ¿´½À´Ï´Ù. "); + } // main + + public static void findInFiles(File dir, String keyword) throws IOException + { + File[] files = dir.listFiles(); + + for(int i=0; i < files.length; i++) { + if(files[i].isDirectory()) { + findInFiles(files[i], keyword); + } else { + String filename = files[i].getName(); + String extension = filename.substring(filename.lastIndexOf(".")+1); + extension = "," + extension + "," ; + + if(",java,txt,bak,".indexOf(extension) == -1) continue; + + filename = dir.getAbsolutePath() + File.separator + filename; + + FileReader fr = new FileReader(files[i]); + BufferedReader br = new BufferedReader(fr); + + String data = ""; + int lineNum = 0; + + while((data=br.readLine())!=null) { + lineNum++; + if(data.indexOf(keyword)!=-1) { + found++; + System.out.println("["+filename+ "("+lineNum+")" + "]" + data); + } + } // while + + br.close(); + } + } // for + } // findInFiles +} // class diff --git a/workspace/ch15/src/FileEx7.java b/workspace/ch15/src/FileEx7.java new file mode 100644 index 0000000..571de7f --- /dev/null +++ b/workspace/ch15/src/FileEx7.java @@ -0,0 +1,26 @@ +import java.io.*; + +class FileEx7 { + public static void main(String[] args) throws Exception { + if(args.length != 1) { + System.out.println("USAGE : java FileEx7 pattern"); + System.exit(0); + } + + String currDir = System.getProperty("user.dir"); + + File dir = new File(currDir); + final String pattern = args[0]; + + // String[] list (FilenameFilter filter) + String[] files = dir.list(new FilenameFilter() { + public boolean accept(File dir, String name) { + return name.indexOf(pattern) != -1; + } + }); + + for(int i=0; i < files.length; i++) { + System.out.println(files[i]); + } + } // end of main +} // end of class diff --git a/workspace/ch15/src/FileEx8.java b/workspace/ch15/src/FileEx8.java new file mode 100644 index 0000000..e034e57 --- /dev/null +++ b/workspace/ch15/src/FileEx8.java @@ -0,0 +1,42 @@ +import java.io.*; + +class FileEx8 { + static int deletedFiles = 0; + + public static void main(String[] args) { + if(args.length != 1) { + System.out.println("USAGE : java FileEx8 Extension"); + System.exit(0); + } + + String currDir = System.getProperty("user.dir"); + + File dir = new File(currDir); + String ext = "." + args[0]; + + delete(dir, ext); + System.out.println(deletedFiles + "°³ÀÇ ÆÄÀÏÀÌ »èÁ¦µÇ¾ú½À´Ï´Ù."); + } // end of main + + public static void delete(File dir, String ext) { + File[] files = dir.listFiles(); + + for(int i=0; i < files.length; i++) { + if(files[i].isDirectory()) { + delete(files[i], ext); + } else { + String filename = files[i].getAbsolutePath(); + + if(filename.endsWith(ext)) { + System.out.print(filename); + if(files[i].delete()) { + System.out.println(" - »èÁ¦ ¼º°ø"); + deletedFiles++; + } else { + System.out.println(" - »èÁ¦ ½ÇÆÐ"); + } + } // if(filename.endsWith(ext)) { + } // if(files[i].isDirectory()) { + } // for(int i=0; i < files.length; i++) { + } // end of delete +} // end of class diff --git a/workspace/ch15/src/FileEx9.java b/workspace/ch15/src/FileEx9.java new file mode 100644 index 0000000..93c3725 --- /dev/null +++ b/workspace/ch15/src/FileEx9.java @@ -0,0 +1,27 @@ +import java.io.*; + +class FileEx9 { + public static void main(String[] args) { + if (args.length != 1) { + System.out.println("Usage: java FileEx9 DIRECTORY"); + System.exit(0); + } + + File dir = new File(args[0]); + + if(!dir.exists() || !dir.isDirectory()) { + System.out.println("À¯È¿ÇÏÁö ¾ÊÀº µð·ºÅ丮ÀÔ´Ï´Ù."); + System.exit(0); + } + + File[] list = dir.listFiles(); + + for (int i = 0; i < list.length; i++) { + String fileName = list[i].getName(); + // ÆÄÀϸí + String newFileName = "0000" + fileName; + newFileName = newFileName.substring(newFileName.length() - 7); + list[i].renameTo(new File(dir, newFileName)); + } + } // end of main +} // end of FileEx9 class diff --git a/workspace/ch15/src/FileMerge.java b/workspace/ch15/src/FileMerge.java new file mode 100644 index 0000000..4ee4d76 --- /dev/null +++ b/workspace/ch15/src/FileMerge.java @@ -0,0 +1,49 @@ +import java.io.*; + +class FileMerge { + public static void main(String[] args) { + if (args.length != 1) { + System.out.println("USAGE : java FileMerge filename"); + System.exit(0); // ÇÁ·Î±×·¥À» Á¾·áÇÑ´Ù. + } + + String mergeFilename = args[0]; + + try { + + File tempFile = File.createTempFile("~mergetemp",".tmp"); + tempFile.deleteOnExit(); + + FileOutputStream fos = new FileOutputStream(tempFile); + BufferedOutputStream bos = new BufferedOutputStream(fos); + + BufferedInputStream bis = null; + + int number = 1; + + File f = new File(mergeFilename + "_." + number); + + while(f.exists()) { + f.setReadOnly(); // ÀÛ¾÷Áß¿¡ ÆÄÀÏÀÇ ³»¿ëÀÌ º¯°æµÇÁö ¾Êµµ·Ï ÇÑ´Ù. + bis = new BufferedInputStream(new FileInputStream(f)); + + int data = 0; + while((data = bis.read()) != -1) { + bos.write(data); + } + + bis.close(); + + f = new File(mergeFilename + "_." + ++number); + } // while + + bos.close(); + + File oldFile = new File(mergeFilename); + + if(oldFile.exists()) oldFile.delete(); + + tempFile.renameTo(oldFile); + } catch (IOException e) {} + } // main +} // class diff --git a/workspace/ch15/src/FileReaderEx1.java b/workspace/ch15/src/FileReaderEx1.java new file mode 100644 index 0000000..cdfcbdb --- /dev/null +++ b/workspace/ch15/src/FileReaderEx1.java @@ -0,0 +1,30 @@ +import java.io.*; + +class FileReaderEx1 { + public static void main(String args[]) { + try { + String fileName = "test.txt"; + FileInputStream fis = new FileInputStream(fileName); + FileReader fr = new FileReader(fileName); + + int data =0; + + // FileInputStreamÀ» ÀÌ¿ëÇؼ­ ÆÄÀϳ»¿ëÀ» Àоî È­¸é¿¡ Ãâ·ÂÇÑ´Ù. + while((data=fis.read())!=-1) { + System.out.print((char)data); + } + System.out.println(); + fis.close(); + + // FileReader¸¦ ÀÌ¿ëÇؼ­ ÆÄÀϳ»¿ëÀ» Àоî È­¸é¿¡ Ãâ·ÂÇÑ´Ù. + while((data=fr.read())!=-1) { + System.out.print((char)data); + } + System.out.println(); + fr.close(); + + } catch (IOException e) { + e.printStackTrace(); + } + } // main +} diff --git a/workspace/ch15/src/FileSplit.java b/workspace/ch15/src/FileSplit.java new file mode 100644 index 0000000..a16e767 --- /dev/null +++ b/workspace/ch15/src/FileSplit.java @@ -0,0 +1,44 @@ +import java.io.*; + +class FileSplit { + public static void main(String[] args) { + if (args.length < 2) { + System.out.println("USAGE : java FileSplit filename SIZE_KB"); + System.exit(0); // ÇÁ·Î±×·¥À» Á¾·áÇÑ´Ù. + } + + final int VOLUME = Integer.parseInt(args[1]) * 1000; + + try { + String filename = args[0]; + + FileInputStream fis = new FileInputStream(filename); + BufferedInputStream bis = new BufferedInputStream(fis); + + FileOutputStream fos = null; + BufferedOutputStream bos = null; + + int data = 0; + int i = 0; + int number = 0; + + while((data = bis.read()) != -1) { + if (i%VOLUME==0) { + if (i!=0) { + bos.close(); + } + + fos = new FileOutputStream(filename + "_."+ ++number); + bos = new BufferedOutputStream(fos); + } + bos.write(data); + i++; + } + + bis.close(); + bos.close(); + } catch (IOException e) { + e.printStackTrace(); + } // end of try-catch + } // end of main +} // end of class FileSplit diff --git a/workspace/ch15/src/FileViewer.java b/workspace/ch15/src/FileViewer.java new file mode 100644 index 0000000..2ababa0 --- /dev/null +++ b/workspace/ch15/src/FileViewer.java @@ -0,0 +1,13 @@ +import java.io.*; + +class FileViewer { + public static void main(String args[]) throws IOException{ + FileInputStream fis = new FileInputStream(args[0]); + int data = 0; + + while((data=fis.read())!=-1) { + char c = (char)data; + System.out.print(c); + } + } +} diff --git a/workspace/ch15/src/IOEx1.java b/workspace/ch15/src/IOEx1.java new file mode 100644 index 0000000..a474765 --- /dev/null +++ b/workspace/ch15/src/IOEx1.java @@ -0,0 +1,26 @@ +import java.io.*; +import java.util.Arrays; + +class IOEx1 { + public static void main(String[] args) { + byte[] inSrc = {0,1,2,3,4,5,6,7,8,9}; + byte[] outSrc = null; + + ByteArrayInputStream input = null; + ByteArrayOutputStream output = null; + + input = new ByteArrayInputStream(inSrc); + output = new ByteArrayOutputStream(); + + int data = 0; + + while((data = input.read())!=-1) { + output.write(data); // void write(int b) + } + + outSrc = output.toByteArray(); // ½ºÆ®¸²ÀÇ ³»¿ëÀ» byte¹è¿­·Î ¹ÝȯÇÑ´Ù. + + System.out.println("Input Source :" + Arrays.toString(inSrc)); + System.out.println("Output Source :" + Arrays.toString(outSrc)); + } +} diff --git a/workspace/ch15/src/IOEx2.java b/workspace/ch15/src/IOEx2.java new file mode 100644 index 0000000..ebf0a4d --- /dev/null +++ b/workspace/ch15/src/IOEx2.java @@ -0,0 +1,27 @@ +import java.io.*; +import java.util.Arrays; + +class IOEx2 { + public static void main(String[] args) { + byte[] inSrc = {0,1,2,3,4,5,6,7,8,9}; + byte[] outSrc = null; + + byte[] temp = new byte[10]; + + ByteArrayInputStream input = null; + ByteArrayOutputStream output = null; + + input = new ByteArrayInputStream(inSrc); + output = new ByteArrayOutputStream(); + + input.read(temp,0,temp.length); // ÀÐ¾î ¿Â µ¥ÀÌÅ͸¦ ¹è¿­ temp¿¡ ´ã´Â´Ù. + output.write(temp,5, 5); // temp[5]ºÎÅÍ 5°³ÀÇ µ¥ÀÌÅ͸¦ writeÇÑ´Ù. + + outSrc = output.toByteArray(); + + System.out.println("Input Source :" + Arrays.toString(inSrc)); + System.out.println("temp :" + Arrays.toString(temp)); + System.out.println("Output Source :" + Arrays.toString(outSrc)); + + } +} diff --git a/workspace/ch15/src/IOEx3.java b/workspace/ch15/src/IOEx3.java new file mode 100644 index 0000000..b54c411 --- /dev/null +++ b/workspace/ch15/src/IOEx3.java @@ -0,0 +1,35 @@ +import java.io.*; +import java.util.Arrays; + +class IOEx3 { + public static void main(String[] args) { + byte[] inSrc = {0,1,2,3,4,5,6,7,8,9}; + byte[] outSrc = null; + + byte[] temp = new byte[4]; // ÀÌÀü ¿¹Á¦¿Í ¹è¿­ÀÇ Å©±â°¡ ´Ù¸£´Ù. + + ByteArrayInputStream input = null; + ByteArrayOutputStream output = null; + + input = new ByteArrayInputStream(inSrc); + output = new ByteArrayOutputStream(); + + System.out.println("Input Source :" + Arrays.toString(inSrc)); + + try { + while(input.available() > 0) { + input.read(temp); + output.write(temp); +// System.out.println("temp :" + Arrays.toString(temp)); + + outSrc = output.toByteArray(); + printArrays(temp, outSrc); + } + } catch(IOException e) {} + } // mainÀÇ ³¡ + + static void printArrays(byte[] temp, byte[] outSrc) { + System.out.println("temp :" +Arrays.toString(temp)); + System.out.println("Output Source :" +Arrays.toString(outSrc)); + } +} diff --git a/workspace/ch15/src/IOEx4.java b/workspace/ch15/src/IOEx4.java new file mode 100644 index 0000000..94da2da --- /dev/null +++ b/workspace/ch15/src/IOEx4.java @@ -0,0 +1,30 @@ +import java.io.*; +import java.util.Arrays; + +class IOEx4 { + public static void main(String[] args) { + byte[] inSrc = {0,1,2,3,4,5,6,7,8,9}; + byte[] outSrc = null; + + byte[] temp = new byte[4]; + + ByteArrayInputStream input = null; + ByteArrayOutputStream output = null; + + input = new ByteArrayInputStream(inSrc); + output = new ByteArrayOutputStream(); + + try { + while(input.available() > 0) { + int len = input.read(temp); // ÀÐ¾î ¿Â µ¥ÀÌÅÍÀÇ °³¼ö¸¦ ¹ÝȯÇÑ´Ù. + output.write(temp, 0, len); // ÀÐ¾î ¿Â ¸¸Å­¸¸ writeÇÑ´Ù. + } + } catch(IOException e) {} + + outSrc = output.toByteArray(); + + System.out.println("Input Source :" + Arrays.toString(inSrc)); + System.out.println("temp :" + Arrays.toString(temp)); + System.out.println("Output Source :" + Arrays.toString(outSrc)); + } +} diff --git a/workspace/ch15/src/InputStreamReaderEx.java b/workspace/ch15/src/InputStreamReaderEx.java new file mode 100644 index 0000000..182f617 --- /dev/null +++ b/workspace/ch15/src/InputStreamReaderEx.java @@ -0,0 +1,23 @@ +import java.io.*; + +class InputStreamReaderEx { + public static void main(String[] args) { + String line = ""; + + try { + InputStreamReader isr = new InputStreamReader(System.in); + BufferedReader br = new BufferedReader(isr); + + System.out.println("»ç¿ëÁßÀÎ OSÀÇ ÀÎÄÚµù :" + isr.getEncoding()); + + do { + System.out.print("¹®ÀåÀ» ÀÔ·ÂÇϼ¼¿ä. ¸¶Ä¡½Ã·Á¸é q¸¦ ÀÔ·ÂÇϼ¼¿ä.>"); + line = br.readLine(); + System.out.println("ÀÔ·ÂÇϽŠ¹®Àå : "+line); + } while(!line.equalsIgnoreCase("q")); + +// br.close(); // System.in°ú °°Àº Ç¥ÁØÀÔÃâ·ÂÀº ´ÝÁö ¾Ê¾Æµµ µÈ´Ù. + System.out.println("ÇÁ·Î±×·¥À» Á¾·áÇÕ´Ï´Ù."); + } catch(IOException e) {} + } // main +} diff --git a/workspace/ch15/src/PipedReaderWriter.java b/workspace/ch15/src/PipedReaderWriter.java new file mode 100644 index 0000000..12e33d0 --- /dev/null +++ b/workspace/ch15/src/PipedReaderWriter.java @@ -0,0 +1,71 @@ +import java.io.*; + +public class PipedReaderWriter { + public static void main(String args[]) { + InputThread inThread = new InputThread("InputThread"); + OutputThread outThread = new OutputThread("OutputThread"); + + //PipedReader¿Í PipedWriter¸¦ ¿¬°áÇÑ´Ù. + inThread.connect(outThread.getOutput()); + + inThread.start(); + outThread.start(); + } // main +} + +class InputThread extends Thread { + PipedReader input = new PipedReader(); + StringWriter sw = new StringWriter(); + + InputThread(String name) { + super(name); // Thread(String name); + } + + public void run() { + try { + int data = 0; + + while((data=input.read()) != -1) { + sw.write(data); + } + System.out.println(getName() + " received : " + sw.toString()); + } catch(IOException e) {} + } // run + + public PipedReader getInput() { + return input; + } + + public void connect(PipedWriter output) { + try { + input.connect(output); + } catch(IOException e) {} + } // connect +} + +class OutputThread extends Thread { + PipedWriter output = new PipedWriter(); + + OutputThread(String name) { + super(name); // Thread(String name); + } + + public void run() { + try { + String msg = "Hello"; + System.out.println(getName() + " sent : " + msg); + output.write(msg); + output.close(); + } catch(IOException e) {} + } // run + + public PipedWriter getOutput() { + return output; + } + + public void connect(PipedReader input) { + try { + output.connect(input); + } catch(IOException e) {} + } // connect +} diff --git a/workspace/ch15/src/PrintStreamEx1.java b/workspace/ch15/src/PrintStreamEx1.java new file mode 100644 index 0000000..0df1abb --- /dev/null +++ b/workspace/ch15/src/PrintStreamEx1.java @@ -0,0 +1,23 @@ +import java.util.Date; + +class PrintStreamEx1 { + public static void main(String[] args) { + int i = 65; + float f = 1234.56789f; + + Date d = new Date(); + + System.out.printf("¹®ÀÚ %cÀÇ ÄÚµå´Â %d%n", i, i); + System.out.printf("%d´Â 8Áø¼ö·Î %o, 16Áø¼ö·Î %x%n", i ,i, i); + System.out.printf("%3d%3d%3d%n", 100, 90, 80); + System.out.println(); + System.out.printf("123456789012345678901234567890%n"); + System.out.printf("%s%-5s%5s%n", "123", "123", "123"); + System.out.println(); + System.out.printf("%-8.1f%8.1f %e%n",f,f,f); + System.out.println(); + System.out.printf("¿À´ÃÀº %tY³â %tm¿ù %tdÀÏ ÀÔ´Ï´Ù.%n", d,d,d ); + System.out.printf("Áö±ÝÀº %tH½Ã %tMºÐ %tSÃÊ ÀÔ´Ï´Ù.%n", d,d,d ); + System.out.printf("Áö±ÝÀº %1$tH½Ã %1$tMºÐ %1$tSÃÊ ÀÔ´Ï´Ù.%n", d ); + } +} diff --git a/workspace/ch15/src/RandomAccessFileEx1.java b/workspace/ch15/src/RandomAccessFileEx1.java new file mode 100644 index 0000000..3ace121 --- /dev/null +++ b/workspace/ch15/src/RandomAccessFileEx1.java @@ -0,0 +1,16 @@ +import java.io.*; + +class RandomAccessFileEx1 { + public static void main(String[] args) { + try { + RandomAccessFile raf = new RandomAccessFile("test.dat", "rw"); + System.out.println("ÆÄÀÏ Æ÷ÀÎÅÍÀÇ À§Ä¡: " + raf.getFilePointer()); + raf.writeInt(100); + System.out.println("ÆÄÀÏ Æ÷ÀÎÅÍÀÇ À§Ä¡: " + raf.getFilePointer()); + raf.writeLong(100L); + System.out.println("ÆÄÀÏ Æ÷ÀÎÅÍÀÇ À§Ä¡: " + raf.getFilePointer()); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/workspace/ch15/src/RandomAccessFileEx2.java b/workspace/ch15/src/RandomAccessFileEx2.java new file mode 100644 index 0000000..c0025f8 --- /dev/null +++ b/workspace/ch15/src/RandomAccessFileEx2.java @@ -0,0 +1,29 @@ +import java.io.*; + +class RandomAccessFileEx2 { + public static void main(String args[]) { +// ¹øÈ£, ±¹¾î, ¿µ¾î, ¼öÇÐ + int[] score = { 1, 100, 90, 90, + 2, 70, 90, 100, + 3, 100, 100, 100, + 4, 70, 60, 80, + 5, 70, 90, 100 + }; + + try { + RandomAccessFile raf = new RandomAccessFile("score2.dat", "rw"); + + for(int i=0; i list = new ArrayList<>(); + list.add(u1); + list.add(u2); + + // °´Ã¼¸¦ Á÷·ÄÈ­ÇÑ´Ù. + out.writeObject(u1); + out.writeObject(u2); + out.writeObject(list); + out.close(); + System.out.println("Á÷·ÄÈ­°¡ Àß ³¡³µ½À´Ï´Ù."); + } catch(IOException e) { + e.printStackTrace(); + } + } // main +} // class diff --git a/workspace/ch15/src/SerialEx2.java b/workspace/ch15/src/SerialEx2.java new file mode 100644 index 0000000..0141747 --- /dev/null +++ b/workspace/ch15/src/SerialEx2.java @@ -0,0 +1,26 @@ +import java.io.*; +import java.util.ArrayList; + +public class SerialEx2 { + public static void main(String[] args) { + try { + String fileName = "UserInfo.ser"; + FileInputStream fis = new FileInputStream(fileName); + BufferedInputStream bis = new BufferedInputStream(fis); + + ObjectInputStream in = new ObjectInputStream(bis); + + // °´Ã¼¸¦ ÀÐÀ» ¶§´Â Ãâ·ÂÇÑ ¼ø¼­¿Í ÀÏÄ¡ÇؾßÇÑ´Ù. + UserInfo u1 = (UserInfo)in.readObject(); + UserInfo u2 = (UserInfo)in.readObject(); + ArrayList list = (ArrayList)in.readObject(); + + System.out.println(u1); + System.out.println(u2); + System.out.println(list); + in.close(); + } catch(Exception e) { + e.printStackTrace(); + } + } // main +} // class diff --git a/workspace/ch15/src/StandardIOEx1.java b/workspace/ch15/src/StandardIOEx1.java new file mode 100644 index 0000000..f9d38f1 --- /dev/null +++ b/workspace/ch15/src/StandardIOEx1.java @@ -0,0 +1,15 @@ +import java.io.*; + +class StandardIOEx1 { + public static void main(String[] args) { + try { + int input = 0; + + while((input=System.in.read())!=-1) { + System.out.println("input :" + input + ", (char)input :" + (char)input); + } + } catch(IOException e) { + e.printStackTrace(); + } + } // main +} diff --git a/workspace/ch15/src/StandardIOEx2.java b/workspace/ch15/src/StandardIOEx2.java new file mode 100644 index 0000000..64dad15 --- /dev/null +++ b/workspace/ch15/src/StandardIOEx2.java @@ -0,0 +1,6 @@ +class StandardIOEx2 { + public static void main(String[] args) { + System.out.println("out : Hello World!"); + System.err.println("err : Hello World!"); + } +} diff --git a/workspace/ch15/src/StandardIOEx3.java b/workspace/ch15/src/StandardIOEx3.java new file mode 100644 index 0000000..7e25eb6 --- /dev/null +++ b/workspace/ch15/src/StandardIOEx3.java @@ -0,0 +1,19 @@ + import java.io.*; + +class StandardIOEx3 { + public static void main(String[] args) { + PrintStream ps = null; + FileOutputStream fos = null; + + try { + fos = new FileOutputStream("test.txt"); + ps = new PrintStream(fos); + System.setOut(ps); // System.outÀÇ Ãâ·Â´ë»óÀ» test.txtÆÄÀÏ·Î º¯°æ + } catch(FileNotFoundException e) { + System.err.println("File not found."); + } + + System.out.println("Hello by System.out"); + System.err.println("Hello by System.err"); + } +} diff --git a/workspace/ch15/src/StringReaderWriterEx.java b/workspace/ch15/src/StringReaderWriterEx.java new file mode 100644 index 0000000..d86e376 --- /dev/null +++ b/workspace/ch15/src/StringReaderWriterEx.java @@ -0,0 +1,21 @@ + import java.io.*; + +class StringReaderWriterEx { + public static void main(String[] args) { + String inputData = "ABCD"; + StringReader input = new StringReader(inputData); + StringWriter output = new StringWriter(); + + int data = 0; + + try { + while((data = input.read())!=-1) { + output.write(data); // void write(int b) + } + } catch(IOException e) {} + + System.out.println("Input Data :" + inputData); + System.out.println("Output Data :" + output.toString()); +// System.out.println("Output Data :" + output.getBuffer().toString()); + } +} diff --git a/workspace/ch15/src/UserInfo.java b/workspace/ch15/src/UserInfo.java new file mode 100644 index 0000000..76024d0 --- /dev/null +++ b/workspace/ch15/src/UserInfo.java @@ -0,0 +1,19 @@ +public class UserInfo implements java.io.Serializable { + String name; + String password; + int age; + + public UserInfo() { + this("Unknown", "1111", 0); + } + + public UserInfo(String name, String password, int age) { + this.name = name; + this.password = password; + this.age = age; + } + + public String toString() { + return "("+ name + "," + password + "," + age + ")"; + } +} diff --git a/workspace/ch15/src/UserInfo2.java b/workspace/ch15/src/UserInfo2.java new file mode 100644 index 0000000..3d92be4 --- /dev/null +++ b/workspace/ch15/src/UserInfo2.java @@ -0,0 +1,46 @@ +import java.io.*; + +class SuperUserInfo { + String name; + String password; + + SuperUserInfo() { + this("Unknown","1111"); + } + + SuperUserInfo(String name, String password) { + this.name = name; + this.password = password; + } +} // class SuperUserInfo + +public class UserInfo2 extends SuperUserInfo implements java.io.Serializable { + int age; + + public UserInfo2() { + this("Unknown", "1111", 0); + } + + public UserInfo2(String name, String password, int age) { + super(name, password); + this.age = age; + } + + public String toString() { + return "("+ name + "," + password + "," + age + ")"; + } + + private void writeObject(ObjectOutputStream out) + throws IOException { + out.writeUTF(name); + out.writeUTF(password); + out.defaultWriteObject(); + } + + private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + name = in.readUTF(); + password = in.readUTF(); + in.defaultReadObject(); + + } +} // class UserInfo2 diff --git a/workspace/ch16/.classpath b/workspace/ch16/.classpath new file mode 100644 index 0000000..fceb480 --- /dev/null +++ b/workspace/ch16/.classpath @@ -0,0 +1,6 @@ + + + + + + diff --git a/workspace/ch16/.project b/workspace/ch16/.project new file mode 100644 index 0000000..e6ba382 --- /dev/null +++ b/workspace/ch16/.project @@ -0,0 +1,17 @@ + + + ch16 + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/workspace/ch16/.settings/org.eclipse.jdt.core.prefs b/workspace/ch16/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..3a21537 --- /dev/null +++ b/workspace/ch16/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,11 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/workspace/ch16/src/NetworkEx1.java b/workspace/ch16/src/NetworkEx1.java new file mode 100644 index 0000000..ad3119d --- /dev/null +++ b/workspace/ch16/src/NetworkEx1.java @@ -0,0 +1,51 @@ +import java.net.*; +import java.util.*; + +class NetworkEx1 { + public static void main(String[] args) + { + InetAddress ip = null; + InetAddress[] ipArr = null; + + try { + ip = InetAddress.getByName("www.naver.com"); + System.out.println("getHostName() :" +ip.getHostName()); + System.out.println("getHostAddress() :"+ip.getHostAddress()); + System.out.println("toString() :" +ip.toString()); + + byte[] ipAddr = ip.getAddress(); + System.out.println("getAddress() :"+Arrays.toString(ipAddr)); + + String result = ""; + for(int i=0; i < ipAddr.length;i++) { + result += (ipAddr[i] < 0) ? ipAddr[i] + 256 : ipAddr[i]; + result += "."; + } + System.out.println("getAddress()+256 :"+result); + System.out.println(); + } catch (UnknownHostException e) { + e.printStackTrace(); + } + + try { + ip = InetAddress.getLocalHost(); + System.out.println("getHostName() :" +ip.getHostName()); + System.out.println("getHostAddress() :"+ip.getHostAddress()); + System.out.println(); + } catch (UnknownHostException e) { + e.printStackTrace(); + } + + + try { + ipArr = InetAddress.getAllByName("www.naver.com"); + + for(int i=0; i < ipArr.length; i++) { + System.out.println("ipArr["+i+"] :" + ipArr[i]); + } + } catch (UnknownHostException e) { + e.printStackTrace(); + } + + } // main +} diff --git a/workspace/ch16/src/NetworkEx2.java b/workspace/ch16/src/NetworkEx2.java new file mode 100644 index 0000000..8383c1b --- /dev/null +++ b/workspace/ch16/src/NetworkEx2.java @@ -0,0 +1,21 @@ +import java.net.*; + +class NetworkEx2 { + public static void main(String args[]) throws Exception { + URL url = new URL("http://www.codechobo.com:80/sample/"+"hello.html?referer=javachobo#index1"); + + System.out.println("url.getAuthority():"+ url.getAuthority()); + System.out.println("url.getContent():"+ url.getContent()); + System.out.println("url.getDefaultPort():"+ url.getDefaultPort()); + System.out.println("url.getPort():"+ url.getPort()); + System.out.println("url.getFile():"+ url.getFile()); + System.out.println("url.getHost():"+ url.getHost()); + System.out.println("url.getPath():"+ url.getPath()); + System.out.println("url.getProtocol():"+ url.getProtocol()); + System.out.println("url.getQuery():"+ url.getQuery()); + System.out.println("url.getRef():"+ url.getRef()); + System.out.println("url.getUserInfo():"+ url.getUserInfo()); + System.out.println("url.toExternalForm():"+ url.toExternalForm()); + System.out.println("url.toURI():"+ url.toURI()); + } +} diff --git a/workspace/ch16/src/NetworkEx3.java b/workspace/ch16/src/NetworkEx3.java new file mode 100644 index 0000000..d82a93d --- /dev/null +++ b/workspace/ch16/src/NetworkEx3.java @@ -0,0 +1,35 @@ +import java.net.*; + +public class NetworkEx3 { + public static void main(String args[]) { + URL url = null; + String address = "http://www.codechobo.com/sample/hello.html"; + + try { + url = new URL(address); + URLConnection conn = url.openConnection(); + + System.out.println("conn.toString():"+conn); + System.out.println("getAllowUserInteraction():"+conn.getAllowUserInteraction()); + System.out.println("getConnectTimeout():"+conn.getConnectTimeout()); + System.out.println("getContent():"+conn.getContent()); + System.out.println("getContentEncoding():"+conn.getContentEncoding()); + System.out.println("getContentLength():"+conn.getContentLength()); + System.out.println("getContentType():"+conn.getContentType()); + System.out.println("getDate():"+conn.getDate()); + System.out.println("getDefaultAllowUserInteraction():"+conn.getDefaultAllowUserInteraction()); + System.out.println("getDefaultUseCaches():"+conn.getDefaultUseCaches()); + System.out.println("getDoInput():"+conn.getDoInput()); + System.out.println("getDoOutput():"+conn.getDoOutput()); + System.out.println("getExpiration():"+conn.getExpiration()); + System.out.println("getHeaderFields():"+conn.getHeaderFields()); + System.out.println("getIfModifiedSince():"+conn.getIfModifiedSince()); + System.out.println("getLastModified():"+conn.getLastModified()); + System.out.println("getReadTimeout():"+conn.getReadTimeout()); + System.out.println("getURL():"+conn.getURL()); + System.out.println("getUseCaches():"+conn.getUseCaches()); + } catch(Exception e) { + e.printStackTrace(); + } + } // main +} diff --git a/workspace/ch16/src/NetworkEx4.java b/workspace/ch16/src/NetworkEx4.java new file mode 100644 index 0000000..c7ad4b7 --- /dev/null +++ b/workspace/ch16/src/NetworkEx4.java @@ -0,0 +1,24 @@ +import java.net.*; +import java.io.*; + +public class NetworkEx4 { + public static void main(String args[]) { + URL url = null; + BufferedReader input = null; + String address = "http://www.codechobo.com/sample/hello.html"; + String line = ""; + + try { + url = new URL(address); + + input = new BufferedReader(new InputStreamReader(url.openStream())); + + while((line=input.readLine()) !=null) { + System.out.println(line); + } + input.close(); + } catch(Exception e) { + e.printStackTrace(); + } + } +} diff --git a/workspace/ch16/src/NetworkEx5.java b/workspace/ch16/src/NetworkEx5.java new file mode 100644 index 0000000..f0aef0f --- /dev/null +++ b/workspace/ch16/src/NetworkEx5.java @@ -0,0 +1,27 @@ +import java.net.*; +import java.io.*; + +public class NetworkEx5 { + public static void main(String args[]) { + URL url = null; + InputStream in = null; + FileOutputStream out = null; + String address = "http://www.codechobo.com/book/src/javajungsuk_src.zip"; + + int ch = 0; + + try { + url = new URL(address); + in = url.openStream(); + out = new FileOutputStream("javajungsuk_src.zip"); + + while((ch=in.read()) !=-1) { + out.write(ch); + } + in.close(); + out.close(); + } catch(Exception e) { + e.printStackTrace(); + } + } // main +} diff --git a/workspace/ch16/src/TcpIpClient.java b/workspace/ch16/src/TcpIpClient.java new file mode 100644 index 0000000..f317061 --- /dev/null +++ b/workspace/ch16/src/TcpIpClient.java @@ -0,0 +1,33 @@ +import java.net.*; +import java.io.*; + +public class TcpIpClient { + public static void main(String args[]) { + try { + String serverIp = "127.0.0.1"; + + System.out.println("¼­¹ö¿¡ ¿¬°áÁßÀÔ´Ï´Ù. ¼­¹öIP :" + serverIp); + // ¼ÒÄÏÀ» »ý¼ºÇÏ¿© ¿¬°áÀ» ¿äûÇÑ´Ù. + Socket socket = new Socket(serverIp, 7777); + + // ¼ÒÄÏÀÇ ÀԷ½ºÆ®¸²À» ¾ò´Â´Ù. + InputStream in = socket.getInputStream(); + DataInputStream dis = new DataInputStream(in); + + // ¼ÒÄÏÀ¸·Î ºÎÅÍ ¹ÞÀº µ¥ÀÌÅ͸¦ Ãâ·ÂÇÑ´Ù. + System.out.println("¼­¹ö·ÎºÎÅÍ ¹ÞÀº ¸Þ½ÃÁö :"+dis.readUTF()); + System.out.println("¿¬°áÀ» Á¾·áÇÕ´Ï´Ù."); + + // ½ºÆ®¸²°ú ¼ÒÄÏÀ» ´Ý´Â´Ù. + dis.close(); + socket.close(); + System.out.println("¿¬°áÀÌ Á¾·áµÇ¾ú½À´Ï´Ù."); + } catch(ConnectException ce) { + ce.printStackTrace(); + } catch(IOException ie) { + ie.printStackTrace(); + } catch(Exception e) { + e.printStackTrace(); + } + } // main +} // class diff --git a/workspace/ch16/src/TcpIpClient5.java b/workspace/ch16/src/TcpIpClient5.java new file mode 100644 index 0000000..5b4cac8 --- /dev/null +++ b/workspace/ch16/src/TcpIpClient5.java @@ -0,0 +1,26 @@ +import java.net.*; +import java.io.*; + +public class TcpIpClient5 { + public static void main(String args[]) { + try { + String serverIp = "127.0.0.1"; + + // ¼ÒÄÏÀ» »ý¼ºÇÏ¿© ¿¬°áÀ» ¿äûÇÑ´Ù. + Socket socket = new Socket(serverIp, 7777); + + System.out.println("¼­¹ö¿¡ ¿¬°áµÇ¾ú½À´Ï´Ù."); + Sender sender = new Sender(socket); + Receiver receiver = new Receiver(socket); + + sender.start(); + receiver.start(); + } catch(ConnectException ce) { + ce.printStackTrace(); + } catch(IOException ie) { + ie.printStackTrace(); + } catch(Exception e) { + e.printStackTrace(); + } + } // main +} // class diff --git a/workspace/ch16/src/TcpIpMultichatClient.java b/workspace/ch16/src/TcpIpMultichatClient.java new file mode 100644 index 0000000..a0bc0e9 --- /dev/null +++ b/workspace/ch16/src/TcpIpMultichatClient.java @@ -0,0 +1,72 @@ +import java.net.*; +import java.io.*; +import java.util.Scanner; + +public class TcpIpMultichatClient { + public static void main(String args[]) { + if(args.length!=1) { + System.out.println("USAGE: java TcpIpMultichatClient ´ëÈ­¸í"); + System.exit(0); + } + + try { + String serverIp = "127.0.0.1"; + // ¼ÒÄÏÀ» »ý¼ºÇÏ¿© ¿¬°áÀ» ¿äûÇÑ´Ù. + Socket socket = new Socket(serverIp, 7777); + System.out.println("¼­¹ö¿¡ ¿¬°áµÇ¾ú½À´Ï´Ù."); + Thread sender = new Thread(new ClientSender(socket, args[0])); + Thread receiver = new Thread(new ClientReceiver(socket)); + + sender.start(); + receiver.start(); + } catch(ConnectException ce) { + ce.printStackTrace(); + } catch(Exception e) {} + } // main + + static class ClientSender extends Thread { + Socket socket; + DataOutputStream out; + String name; + + ClientSender(Socket socket, String name) { + this.socket = socket; + try { + out = new DataOutputStream(socket.getOutputStream()); + this.name = name; + } catch(Exception e) {} + } + + public void run() { + Scanner scanner = new Scanner(System.in); + try { + if(out!=null) { + out.writeUTF(name); + } + + while(out!=null) { + out.writeUTF("["+name+"]"+scanner.nextLine()); } + } catch(IOException e) {} + } // run() + } // ClientSender + + static class ClientReceiver extends Thread { + Socket socket; + DataInputStream in; + + ClientReceiver(Socket socket) { + this.socket = socket; + try { + in = new DataInputStream(socket.getInputStream()); + } catch(IOException e) {} + } + + public void run() { + while(in!=null) { + try { + System.out.println(in.readUTF()); + } catch(IOException e) {} + } + } // run + } // ClientReceiver +} // class diff --git a/workspace/ch16/src/TcpIpMultichatServer.java b/workspace/ch16/src/TcpIpMultichatServer.java new file mode 100644 index 0000000..8b34fa0 --- /dev/null +++ b/workspace/ch16/src/TcpIpMultichatServer.java @@ -0,0 +1,81 @@ +import java.net.*; +import java.io.*; +import java.util.*; + +public class TcpIpMultichatServer { + HashMap clients; + + TcpIpMultichatServer() { + clients = new HashMap(); + Collections.synchronizedMap(clients); + } + + public void start() { + ServerSocket serverSocket = null; + Socket socket = null; + + try { + serverSocket = new ServerSocket(7777); + System.out.println("¼­¹ö°¡ ½ÃÀ۵Ǿú½À´Ï´Ù."); + + while(true) { + socket = serverSocket.accept(); + System.out.println("["+socket.getInetAddress()+":"+socket.getPort()+"]"+"¿¡¼­ Á¢¼ÓÇÏ¿´½À´Ï´Ù."); + ServerReceiver thread = new ServerReceiver(socket); + thread.start(); + } + } catch(Exception e) { + e.printStackTrace(); + } + } // start() + + void sendToAll(String msg) { + Iterator it = clients.keySet().iterator(); + + while(it.hasNext()) { + try { + DataOutputStream out = (DataOutputStream)clients.get(it.next()); + out.writeUTF(msg); + } catch(IOException e){} + } // while + } // sendToAll + + public static void main(String args[]) { + new TcpIpMultichatServer().start(); + } + class ServerReceiver extends Thread { + Socket socket; + DataInputStream in; + DataOutputStream out; + + ServerReceiver(Socket socket) { + this.socket = socket; + try { + in = new DataInputStream(socket.getInputStream()); + out = new DataOutputStream(socket.getOutputStream()); + } catch(IOException e) {} + } + + public void run() { + String name = ""; + try { + name = in.readUTF(); + sendToAll("#"+name+"´ÔÀÌ µé¾î¿À¼Ì½À´Ï´Ù."); + + clients.put(name, out); + System.out.println("ÇöÀç ¼­¹öÁ¢¼ÓÀÚ ¼ö´Â "+ clients.size()+"ÀÔ´Ï´Ù."); + + while(in!=null) { + sendToAll(in.readUTF()); + } + } catch(IOException e) { + // ignore + } finally { + sendToAll("#"+name+"´ÔÀÌ ³ª°¡¼Ì½À´Ï´Ù."); + clients.remove(name); + System.out.println("["+socket.getInetAddress() +":"+socket.getPort()+"]"+"¿¡¼­ Á¢¼ÓÀ» Á¾·áÇÏ¿´½À´Ï´Ù."); + System.out.println("ÇöÀç ¼­¹öÁ¢¼ÓÀÚ ¼ö´Â "+ clients.size()+"ÀÔ´Ï´Ù."); + } // try + } // run + } // ReceiverThread +} // class diff --git a/workspace/ch16/src/TcpIpServer.java b/workspace/ch16/src/TcpIpServer.java new file mode 100644 index 0000000..2b5407e --- /dev/null +++ b/workspace/ch16/src/TcpIpServer.java @@ -0,0 +1,49 @@ +import java.net.*; +import java.io.*; +import java.util.Date; +import java.text.SimpleDateFormat; + +public class TcpIpServer { + public static void main(String args[]) { + ServerSocket serverSocket = null; + + try { + // ¼­¹ö¼ÒÄÏÀ» »ý¼ºÇÏ¿© 7777¹ø Æ÷Æ®¿Í °áÇÕ(bind)½ÃŲ´Ù. + serverSocket = new ServerSocket(7777); + System.out.println(getTime()+"¼­¹ö°¡ ÁغñµÇ¾ú½À´Ï´Ù."); + + } catch(IOException e) { + e.printStackTrace(); + } + + while(true) { + try { + System.out.println(getTime()+"¿¬°á¿äûÀ» ±â´Ù¸³´Ï´Ù."); + // ¼­¹ö¼ÒÄÏÀº Ŭ¶óÀ̾ðÆ®ÀÇ ¿¬°á¿äûÀÌ ¿Ã ¶§±îÁö ½ÇÇàÀ» ¸ØÃß°í °è¼Ó ±â´Ù¸°´Ù. + // Ŭ¶óÀ̾ðÆ®ÀÇ ¿¬°á¿äûÀÌ ¿À¸é Ŭ¶óÀ̾ðÆ® ¼ÒÄÏ°ú Åë½ÅÇÒ »õ·Î¿î ¼ÒÄÏÀ» »ý¼ºÇÑ´Ù. + Socket socket = serverSocket.accept(); + System.out.println(getTime()+ socket.getInetAddress() + "·ÎºÎÅÍ ¿¬°á¿äûÀÌ µé¾î¿Ô½À´Ï´Ù."); + + // ¼ÒÄÏÀÇ Ãâ·Â½ºÆ®¸²À» ¾ò´Â´Ù. + OutputStream out = socket.getOutputStream(); + DataOutputStream dos = new DataOutputStream(out); + + // ¿ø°Ý ¼ÒÄÏ(remote socket)¿¡ µ¥ÀÌÅ͸¦ º¸³½´Ù. + dos.writeUTF("[Notice] Test Message1 from Server."); + System.out.println(getTime()+"µ¥ÀÌÅ͸¦ Àü¼ÛÇß½À´Ï´Ù."); + + // ½ºÆ®¸²°ú ¼ÒÄÏÀ» ´Ý¾ÆÁØ´Ù. + dos.close(); + socket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } // while + } // main + + // ÇöÀç½Ã°£À» ¹®ÀÚ¿­·Î ¹ÝȯÇÏ´Â ÇÔ¼ö + static String getTime() { + SimpleDateFormat f = new SimpleDateFormat("[hh:mm:ss]"); + return f.format(new Date()); + } +} // class diff --git a/workspace/ch16/src/TcpIpServer2.java b/workspace/ch16/src/TcpIpServer2.java new file mode 100644 index 0000000..ef8f4c4 --- /dev/null +++ b/workspace/ch16/src/TcpIpServer2.java @@ -0,0 +1,51 @@ +import java.net.*; +import java.io.*; +import java.util.Date; +import java.text.SimpleDateFormat; + +public class TcpIpServer2 { + public static void main(String args[]) { + ServerSocket serverSocket = null; + + try { + // ¼­¹ö¼ÒÄÏÀ» »ý¼ºÇÏ¿© 7777¹ø Æ÷Æ®¿Í °áÇÕ(bind)½ÃŲ´Ù. + serverSocket = new ServerSocket(7777); + System.out.println(getTime()+"¼­¹ö°¡ ÁغñµÇ¾ú½À´Ï´Ù."); + + } catch(IOException e) { + e.printStackTrace(); + } + + while(true) { + try { + // ¼­¹ö¼ÒÄÏ + System.out.println(getTime()+"¿¬°á¿äûÀ» ±â´Ù¸³´Ï´Ù."); + Socket socket = serverSocket.accept(); + System.out.println(getTime()+ socket.getInetAddress() + "·ÎºÎÅÍ ¿¬°á¿äûÀÌ µé¾î¿Ô½À´Ï´Ù."); + + System.out.println("getPort():"+socket.getPort()); + System.out.println("getLocalPort():" +socket.getLocalPort()); + + // ¼ÒÄÏÀÇ Ãâ·Â½ºÆ®¸²À» ¾ò´Â´Ù. + OutputStream out = socket.getOutputStream(); + DataOutputStream dos = new DataOutputStream(out); + + // ¿ø°Ý ¼ÒÄÏ(remote socket)¿¡ µ¥ÀÌÅ͸¦ º¸³½´Ù. + dos.writeUTF("[Notice] Test Message1 from Server."); + System.out.println(getTime()+"µ¥ÀÌÅ͸¦ Àü¼ÛÇß½À´Ï´Ù."); + + // ½ºÆ®¸²°ú ¼ÒÄÏÀ» ´Ý¾ÆÁØ´Ù. + dos.close(); + socket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } // while + } // main + + // ÇöÀç½Ã°£À» ¹®ÀÚ¿­·Î ¹ÝȯÇÏ´Â ÇÔ¼ö + static String getTime() { + SimpleDateFormat f = new SimpleDateFormat("[hh:mm:ss]"); + return f.format(new Date()); + } +} // class diff --git a/workspace/ch16/src/TcpIpServer3.java b/workspace/ch16/src/TcpIpServer3.java new file mode 100644 index 0000000..b5639df --- /dev/null +++ b/workspace/ch16/src/TcpIpServer3.java @@ -0,0 +1,55 @@ +import java.net.*; +import java.io.*; +import java.util.Date; +import java.text.SimpleDateFormat; + +public class TcpIpServer3 { + public static void main(String args[]) { + ServerSocket serverSocket = null; + + try { + // ¼­¹ö¼ÒÄÏÀ» »ý¼ºÇÏ¿© 7777¹ø Æ÷Æ®¿Í °áÇÕ(bind)½ÃŲ´Ù. + serverSocket = new ServerSocket(7777); + System.out.println(getTime()+"¼­¹ö°¡ ÁغñµÇ¾ú½À´Ï´Ù."); + + } catch(IOException e) { + e.printStackTrace(); + } + + while(true) { + try { + // ¼­¹ö¼ÒÄÏ + System.out.println(getTime()+"¿¬°á¿äûÀ» ±â´Ù¸³´Ï´Ù."); + + // ¿äû´ë±â½Ã°£À» 5ÃÊ·Î ¼³Á¤ÇÑ´Ù. + // 5Ãʵ¿¾È Á¢¼Ó¿äûÀÌ ¾øÀ¸¸é SocketTimeoutExceptionÀÌ ¹ß»ýÇÑ´Ù. + serverSocket.setSoTimeout(5*1000); + Socket socket = serverSocket.accept(); + System.out.println(getTime()+ socket.getInetAddress() + "·ÎºÎÅÍ ¿¬°á¿äûÀÌ µé¾î¿Ô½À´Ï´Ù."); + + // ¼ÒÄÏÀÇ Ãâ·Â½ºÆ®¸²À» ¾ò´Â´Ù. + OutputStream out = socket.getOutputStream(); + DataOutputStream dos = new DataOutputStream(out); + + // ¿ø°Ý ¼ÒÄÏ(remote socket)¿¡ µ¥ÀÌÅ͸¦ º¸³½´Ù. + dos.writeUTF("[Notice] Test Message1 from Server."); + System.out.println(getTime()+"µ¥ÀÌÅ͸¦ Àü¼ÛÇß½À´Ï´Ù."); + + // ½ºÆ®¸²°ú ¼ÒÄÏÀ» ´Ý¾ÆÁØ´Ù. + dos.close(); + socket.close(); + } catch (SocketTimeoutException e) { + System.out.println("ÁöÁ¤µÈ ½Ã°£µ¿¾È Á¢¼Ó¿äûÀÌ ¾ø¾î¼­ ¼­¹ö¸¦ Á¾·áÇÕ´Ï´Ù."); + System.exit(0); + } catch (IOException e) { + e.printStackTrace(); + } + } // while + } // main + + // ÇöÀç½Ã°£À» ¹®ÀÚ¿­·Î ¹ÝȯÇÏ´Â ÇÔ¼ö + static String getTime() { + SimpleDateFormat f = new SimpleDateFormat("[hh:mm:ss]"); + return f.format(new Date()); + } +} // class diff --git a/workspace/ch16/src/TcpIpServer4.java b/workspace/ch16/src/TcpIpServer4.java new file mode 100644 index 0000000..f58c167 --- /dev/null +++ b/workspace/ch16/src/TcpIpServer4.java @@ -0,0 +1,67 @@ +import java.net.*; +import java.io.*; +import java.util.Date; +import java.text.SimpleDateFormat; + +public class TcpIpServer4 implements Runnable { + ServerSocket serverSocket; + Thread[] threadArr; + + public static void main(String args[]) { + // 5°³ÀÇ ¾²·¹µå¸¦ »ý¼ºÇÏ´Â ¼­¹ö¸¦ »ý¼ºÇÑ´Ù. + TcpIpServer4 server = new TcpIpServer4(5); + server.start(); + } // main + + public TcpIpServer4(int num) { + try { + // ¼­¹ö¼ÒÄÏÀ» »ý¼ºÇÏ¿© 7777¹ø Æ÷Æ®¿Í °áÇÕ(bind)½ÃŲ´Ù. + serverSocket = new ServerSocket(7777); + System.out.println(getTime()+"¼­¹ö°¡ ÁغñµÇ¾ú½À´Ï´Ù."); + + threadArr = new Thread[num]; + } catch(IOException e) { + e.printStackTrace(); + } + } + + public void start() { + for(int i=0; i < threadArr.length; i++) { + threadArr[i] = new Thread(this); + threadArr[i].start(); + } + } + + public void run() { + while(true) { + try { + System.out.println(getTime()+ "°¡ ¿¬°á¿äûÀ» ±â´Ù¸³´Ï´Ù."); + + Socket socket = serverSocket.accept(); + System.out.println(getTime()+ socket.getInetAddress() + "·ÎºÎÅÍ ¿¬°á¿äûÀÌ µé¾î¿Ô½À´Ï´Ù."); + + // ¼ÒÄÏÀÇ Ãâ·Â½ºÆ®¸²À» ¾ò´Â´Ù. + OutputStream out = socket.getOutputStream(); + DataOutputStream dos = new DataOutputStream(out); + + // ¿ø°Ý ¼ÒÄÏ(remote socket)¿¡ µ¥ÀÌÅ͸¦ º¸³½´Ù. + dos.writeUTF("[Notice] Test Message1 from Server."); + System.out.println(getTime()+"µ¥ÀÌÅ͸¦ Àü¼ÛÇß½À´Ï´Ù."); + + // ½ºÆ®¸²°ú ¼ÒÄÏÀ» ´Ý¾ÆÁØ´Ù. + dos.close(); + socket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } // while + } // run + + // ÇöÀç½Ã°£À» ¹®ÀÚ¿­·Î ¹ÝȯÇÏ´Â ÇÔ¼ö + static String getTime() { + String name = Thread.currentThread().getName(); + SimpleDateFormat f = new SimpleDateFormat("[hh:mm:ss]"); + + return f.format(new Date()) + name ; + } +} // class diff --git a/workspace/ch16/src/TcpIpServer5.java b/workspace/ch16/src/TcpIpServer5.java new file mode 100644 index 0000000..6ce20eb --- /dev/null +++ b/workspace/ch16/src/TcpIpServer5.java @@ -0,0 +1,70 @@ +import java.net.*; +import java.io.*; +import java.util.Scanner; + +public class TcpIpServer5 { + public static void main(String args[]) { + ServerSocket serverSocket = null; + Socket socket = null; + + try { + // ¼­¹ö¼ÒÄÏÀ» »ý¼ºÇÏ¿© 7777¹ø Æ÷Æ®¿Í °áÇÕ(bind)½ÃŲ´Ù. + serverSocket = new ServerSocket(7777); + System.out.println("¼­¹ö°¡ ÁغñµÇ¾ú½À´Ï´Ù."); + + socket = serverSocket.accept(); + + Sender sender = new Sender(socket); + Receiver receiver = new Receiver(socket); + + sender.start(); + receiver.start(); + } catch (Exception e) { + e.printStackTrace(); + } + } // main +} // class + +class Sender extends Thread { + Socket socket; + DataOutputStream out; + String name; + + Sender(Socket socket) { + this.socket = socket; + try { + out = new DataOutputStream(socket.getOutputStream()); + name = "["+socket.getInetAddress()+":"+socket.getPort()+"]"; + } catch(Exception e) {} + } + + public void run() { + Scanner scanner = new Scanner(System.in); + while(out!=null) { + try { + out.writeUTF(name+scanner.nextLine()); + } catch(IOException e) {} + } + } // run() +} + +class Receiver extends Thread { + Socket socket; + DataInputStream in; + + Receiver(Socket socket) { + this.socket = socket; + try { + in = new DataInputStream(socket.getInputStream()); + } catch(IOException e) {} + + } + + public void run() { + while(in!=null) { + try { + System.out.println(in.readUTF()); + } catch(IOException e) {} + } + } // run +} diff --git a/workspace/ch16/src/UdpClient.java b/workspace/ch16/src/UdpClient.java new file mode 100644 index 0000000..8feb867 --- /dev/null +++ b/workspace/ch16/src/UdpClient.java @@ -0,0 +1,30 @@ +import java.net.*; +import java.io.*; + +public class UdpClient { + public void start() throws IOException, UnknownHostException { + DatagramSocket datagramSocket = new DatagramSocket(); + InetAddress serverAddress = InetAddress.getByName("127.0.0.1"); + + // µ¥ÀÌÅÍ°¡ ÀúÀåµÉ °ø°£À¸·Î byte¹è¿­À» »ý¼ºÇÑ´Ù. + byte[] msg = new byte[100]; + + DatagramPacket outPacket = new DatagramPacket(msg, 1, serverAddress, 7777); + DatagramPacket inPacket = new DatagramPacket(msg, msg.length); + + datagramSocket.send(outPacket); // DatagramPacketÀ» Àü¼ÛÇÑ´Ù. + datagramSocket.receive(inPacket); // DatagramPacketÀ» ¼ö½ÅÇÑ´Ù. + + System.out.println("current server time :" + new String(inPacket.getData())); + + datagramSocket.close(); + } // start() + + public static void main(String args[]) { + try { + new UdpClient().start(); + } catch(Exception e) { + e.printStackTrace(); + } + } // main +} diff --git a/workspace/ch16/src/UdpServer.java b/workspace/ch16/src/UdpServer.java new file mode 100644 index 0000000..b0a3438 --- /dev/null +++ b/workspace/ch16/src/UdpServer.java @@ -0,0 +1,44 @@ +import java.net.*; +import java.io.*; +import java.util.Date; +import java.text.SimpleDateFormat; + +public class UdpServer { + public void start() throws IOException { + // Æ÷Æ® 7777¹øÀ» »ç¿ëÇÏ´Â ¼ÒÄÏÀ» »ý¼ºÇÑ´Ù. + DatagramSocket socket = new DatagramSocket(7777); + DatagramPacket inPacket, outPacket; + + byte[] inMsg = new byte[10]; + byte[] outMsg; + + while(true) { + // µ¥ÀÌÅ͸¦ ¼ö½ÅÇϱâ À§ÇÑ ÆÐŶÀ» »ý¼ºÇÑ´Ù. + inPacket = new DatagramPacket(inMsg, inMsg.length); + + // ÆÐŶÀ» ÅëÇØ µ¥ÀÌÅ͸¦ ¼ö½Å(receive)ÇÑ´Ù. + socket.receive(inPacket); + + // ¼ö½ÅÇÑ ÆÐŶÀ¸·Î ºÎÅÍ clientÀÇ IPÁÖ¼Ò¿Í Port¸¦ ¾ò´Â´Ù. + InetAddress address = inPacket.getAddress(); + int port = inPacket.getPort(); + + // ¼­¹öÀÇ ÇöÀç ½Ã°£À» ½ÃºÐÃÊ ÇüÅÂ([hh:mm:ss])·Î ¹ÝȯÇÑ´Ù. + SimpleDateFormat sdf = new SimpleDateFormat("[hh:mm:ss]"); + String time = sdf.format(new Date()); + outMsg = time.getBytes(); // timeÀ» byte¹è¿­·Î º¯È¯ÇÑ´Ù. + + // ÆÐŶÀ» »ý¼ºÇؼ­ client¿¡°Ô Àü¼Û(send)ÇÑ´Ù. + outPacket = new DatagramPacket(outMsg, outMsg.length, address, port); + socket.send(outPacket); + } + } // start() + + public static void main(String args[]) { + try { + new UdpServer().start(); // UDP¼­¹ö¸¦ ½ÇÇà½ÃŲ´Ù. + } catch (IOException e) { + e.printStackTrace(); + } + } // main +}