Appendix - $SSHQGL[ $ $QVZHUV WR 6HOI &KHFN...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: $SSHQGL[ $ $QVZHUV WR 6HOI &KHFN 3UREOHPV &RS\ULJKW E\ 6WXDUW 5HJHV DQG 0DUW\ 6WHSS &KDSWHU &RPSXWHUV XVH ELQDU\ QXPEHUV EHFDXVH LW V HDVLHU WR EXLOG HOHFWURQLF GHYLFHV UHOLDEO\ LI WKH\ RQO\ KDYH WR GLVWLQJXLVK EHWZHHQ WZR HOHFWULF VWDWHV 0DNH WKH FRRNLH EDWWHU 0L[ WKH GU\ LQJUHGLHQWV &UHDP WKH EXWWHU DQG VXJDU %HDW LQ WKH HJJV 6WLU LQ WKH GU\ LQJUHGLHQWV %DNH WKH FRRNLHV 6HW WKH RYHQ IRU WKH DSSURSULDWH WHPSHUDWXUH 6HW WKH WLPHU 3ODFH WKH FRRNLHV LQWR WKH RYHQ $OORZ WKH FRRNLHV WR EDNH $GG IURVWLQJ DQG VSULQNOHV 0L[ WKH LQJUHGLHQWV IRU WKH IURVWLQJ 6SUHDG IURVWLQJ DQG VSULQNOHV RQWR WKH FRRNLHV 0\3URJUDP MDYD LV D VRXUFH FRGH ILOH W\SHG E\ WKH SURJUDPPHU DQG 0\3URJUDP FODVV LV D FRPSLOHG H[HFXWDEOH FODVV ILOH WKDW LV UXQ E\ WKH FRPSXWHU 7KH OHJDO LGHQWLILHUV VKRZQ DUH SULQWOQ $QQXDO6DODU\ $%& VXPBRIBGDWD BDYHUDJH DQG % "Quotes" Slashes \// How '"confounding' "\" it is! Shaq is 7'1" The string "" is an empty message. \'"" 747 Dear "DoubleSlash" magazine, Your publication confuses me. Is it a \\ slash or a //// slash that I should use? Sincerely, Susan "Suzy" Smith System.out.println("\"Several slashes are sometimes seen,\""); System.out.println("said Sally. \"I've said so myself.\" See?"); System.out.println("\\ / \\\\ // \\\\\\ ///"); System.out.println("This is a test of your"); System.out.println("knowledge of \"quotes\" used"); System.out.println("in 'string literals.'"); System.out.println("You're bound to \"get it right\""); System.out.println("if you read the section on"); System.out.println("''quotes.''"); 7KH NH\ZRUG FODVV LV PLVVLQJ RQ OLQH $ VHPLFRORQ LV PLVVLQJ RQ OLQH 7KH ZRUG 3ULQWOQ VKRXOG QRW EH FDSLWDOL]HG RQ OLQH 7KH NH\ZRUG YRLG LV PLVVLQJ RQ OLQH 7KH ZRUG VWULQJ VKRXOG EH FDSLWDOL]HG RQ OLQH $ FORVLQJ PDUN LV PLVVLQJ RQ OLQH $ FORVLQJ ` EUDFH LV PLVVLQJ RQ OLQH $ ^ EUDFH LV PLVVLQJ RQ OLQH $ FORVLQJ LV PLVVLQJ RQ OLQH 7KH FRPPHQW RQ OLQHV DFFLGHQWDOO\ FRPPHQWV RXW OLQHV FRPPHQWV ZRXOG IL[ WKH SUREOHP Inside Inside Inside Inside Inside Inside Inside Inside Inside Inside Inside first method third method first method second method first method second method first method third method first method second method first method RI WKH SURJUDP 8VLQJ 748 Inside Inside Inside Inside Inside Inside Inside Inside Inside Inside Inside Inside Inside Inside Inside Inside Inside Inside Inside Inside I I I I I I I I I I I I I I I I I I I I I I I I I I I I I I I am am am am am am am am am am am am am am am am am am am am am am am am am am am am am am am first method first method second method first method third method second method first method first method second method first method third method second method first method first method second method first method third method first method second method first method 1. 1. 2. 3. 1. 1. 2. 1. 2. 3. 1. 1. 1. 1. 2. 3. 1. 2. 1. 1. 2. 3. 1. 2. 1. 1. 2. 3. 1. 1. 2. method method method method method method method method method method method method method method method method method method method method method method method method method method method method method method method 2Q OLQH 2Q OLQH WKH FODVV QDPH VKRXOG EH /RWV2I(UURUV QR VSDFH WKH ZRUG YRLG VKRXOG DSSHDU DIWHU VWDWLF 749 2Q OLQH 2Q OLQH 2Q OLQH 2Q OLQH 2Q OLQH 2Q OLQH 2Q OLQH 2Q OLQH 2Q OLQH 6WULQJ VKRXOG EH 6WULQJ>@ 6\VWHP SULQWOQ VKRXOG EH 6\VWHP RXW SULQWOQ +HOOR ZRUOG VKRXOG EH +HOOR ZRUOG WKHUH VKRXOG EH D VHPLFRORQ DIWHU PHVVDJH WKHUH VKRXOG EH DIWHU PHVVDJH 6\VWHP RXW SULQWOQ VKRXOG EH 6\VWHP RXW SULQWOQ FDQQRW VKRXOG EH FDQQRW WKH SKUDVH HUURUV FDQQRW DSSHDU LQVLGH D 6WULQJ HUURUV ZRXOG ZRUN WKHUH VKRXOG EH D FORVLQJ ` EUDFH 6\QWD[ HUURU 7KH SURJUDP ZRXOG QRW FRPSLOH EHFDXVH LWV FODVV QDPH 'HPRQVWUDWLRQ ZRXOG QRW PDWFK LWV ILOH QDPH ([DPSOH MDYD 'LIIHUHQW SURJUDP RXWSXW 7KH SURJUDP ZRXOG QRW UXQ EHFDXVH -DYD ZRXOG EH XQDEOH WR ILQG WKH PDLQ PHWKRG 'LIIHUHQW SURJUDP RXWSXW 7KHUH ZRXOG QRZ EH D EODQN OLQH EHWZHHQ WKH WZR SULQWHG PHVVDJHV 6\QWD[ HUURU 7KH SURJUDP ZRXOG QRW FRPSLOH EHFDXVH WKH PDLQ PHWKRG ZRXOG EH FDOOLQJ D PHWKRG GLVSOD\5XOH WKDW QR ORQJHU H[LVWHG 1R HIIHFW 7KH SURJUDP ZRXOG VWLOO FRPSLOH VXFFHVVIXOO\ DQG SURGXFH WKH VDPH RXWSXW 'LIIHUHQW SURJUDP RXWSXW 7KH RXWSXW ZRXOG QRZ KDYH QR OLQH EUHDN EHWZHHQ 7KH ILUVW UXOH DQG RI -DYD &OXE LV LQ LWV RXWSXW 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 11 12 13 public class GiveAdvice { public static void main(String args) { System.out.println("Programs can be easy or difficult"); System.out.println("to read, depending upon their format."); System.out.println(); System.out.println("Everyone, including yourself, will be"); System.out.println("happier if you choose to format your"); System.out.println("Programs."); } } public class Messy { public static void main(String args) { message(); System.out.println(); message(); } public static void message() { System.out.println("I really wish that"); System.out.println("I had formatted my source"); System.out.println("code correctly!"); } } &KDSWHU DQG DUH OHJDO LQW OLWHUDOV 750 KHOOR int age; String gender; double height; int weight; String year; int numberOfCourses; double gpa; /DVW GLJLW number % 10 6HFRQG WR ODVW GLJLW (number % 100) / 10 RU (number / 10) % 10 7KLUG WR ODVW GLJLW (number % 1000) / 100 RU (number / 100) % 10 first: 19 second: 8 7KH FRGH VZDSV WKH YDOXHV RI WKH YDULDEOHV ILUVW DQG VHFRQG 751 int first = 8, second = 19; first += second; second = first - second; first -= second; a: 7 b: 10 c: 16 FRXQW FRXQW FRXQW FRXQW for (int i = 1; i < 6; i++) { // your code here System.out.println(18 * i - 22); } System.out.println("Twas brillig and the "); System.out.println(" slithy toves did gyre and"); System.out.println("gimble"); System.out.println(); System.out.println("in the wabe."); 7KH ORRS SULQWV HYHU\ WKLUG QXPEHU QRW HYHU\ RGG QXPEHU 7KH VWDWHPHQW count = count + 2 RQ OLQH VKRXOG EH PRYHG LQWR WKH ORRS KHDGHU LQVWHDG RI count++ 2Q OLQH WKH YDULDEOH FRXQW LV QR ORQJHU GHILQHG LWV VFRSH LV RQO\ ZLWKLQ WKH IRU ORRS DERYH ,W VKRXOG EH GHFODUHG EHIRUH WKH ORRS EHJLQV UDWKHU WKDQ LQVLGH WKH ORRS V KHDGHU 2Q OLQH WRR ODUJH D YDOXH LV SULQWHG IRU WKH ILQDO RGG QXPEHU count VKRXOG EH SULQWHG QRW FRXQW 2Q OLQH LW LV LOOHJDO WR WU\ WR DVVLJQ D QHZ YDOXH WR D FRQVWDQW VXFK DV 0$;B2'' 2QH ZD\ WR IL[ WKLV ZRXOG EH WR ZULWH WZR PHWKRGV RQH WR SULQW WKH RGGV XS WR DQG D VHFRQG WR SULQW WKH RGGV XS WR %XW WKLV LV DGPLWWHGO\ UHGXQGDQW 7KH EHWWHU VROXWLRQ WR WKLV NLQG RI SUREOHP LV FDOOHG SDUDPHWHU SDVVLQJ ZKLFK ZLOO EH VHHQ LQ ODWHU FKDSWHUV 4 2 The result is: 55 24 22 19 15 10 1 2 3 4 5 752 +----+ \ / / \ \ / / \ \ / / \ +----+ How How How are many lines many lines many lines printed? T-minus 5, 4, 3, 2, 1, Blastoff! 1 2 3 4 5 2 3 4 5 6 7 8 9 10 4 6 8 10 12 14 16 18 20 6 9 12 15 18 21 24 27 30 8 12 16 20 24 28 32 36 40 10 15 20 25 30 35 40 45 50 * *** ***** ******* ********* *********** ************* *************** ***************** ******************* ****!****!****! ****!****!****! ************! ************! *!*!*!*! *!*!*!*! *!*!*!*! *!*!*!*! *!*!*!*! *!*!*!*! 753 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 public class SlashFigure { public static void main(String args) { for (int line = 1; line <= 6; line++) { for (int i = 1; i <= 2 * line - 2; i++) { System.out.print("\\"); } for (int i = 1; i <= -4 * line + 26; i++) { System.out.print("!"); } for (int i = 1; i <= 2 * line - 2; i++) { System.out.print("/"); } System.out.println(); } } } public class SlashFigure2 { public static final int SIZE = 4; public static void main(String args) { for (int line = 1; line <= SIZE; line++) { for (int i = 1; i <= 2 * line - 2; i++) { System.out.print("\\"); } for (int i = 1; i <= -4 * line + (4 * SIZE + 2); i++) { System.out.print("!"); } for (int i = 1; i <= 2 * line - 2; i++) { System.out.print("/"); } System.out.println(); } } } &KDSWHU 1 3 5 1 3 5 7 9 11 13 15 1 3 5 7 9 11 13 15 17 19 21 23 25 1 2 3 4 5 1 2 3 4 5 6 7 1 2 3 4 number = 8 three times two 1 times three = 1 times 1 = 42 three times 1 = 1 times eight = = 6 28 2 20 754 whom and who like it it and him like whom whom and him like him stu and boo like who her and him like who public static void printStrings(String s, int n) { for (int i = 1; i <= n; i++) { System.out.print(s); } System.out.println(); } 6\VWHP RXW SULQWOQ LV DQ RYHUORDGHG PHWKRG 7KH SURJUDP FKDQJHV WKH YDOXH RI LWV SDUDPHWHU WHPSF EXW WKLV GRHVQ W DIIHFW WKH YDULDEOH WHPSF LQ PDLQ 7KH LQFRUUHFW RXWSXW LV Body temp in C is: 0.0 3 1 4 5 8 5 0 2 4 3 2 4 1 9 4 public static int min(int n1, int n2, int n3) { return Math.min(n1, Math.min(n2, n3)); } public static int countQuarters(int cents) { return cents % 100 / 25; } 755 THG $5&785$1 0(*$'21.(< 7KH FRGH WKURZV DQ ,QGH[2XW2I%RXQGV([FHSWLRQ HJDG $UFWXUDQ 0HJDGRQNH\V E &\EHU PHJD &RUS quote.substring(5, 10).toUpperCase() quote.toLowerCase().substring(0, 4) + quote.substring(20, 26) p1: java.awt.Point[x=20,y=10] p2: java.awt.Point[x=46,y=4] p3: java.awt.Point[x=46,y=4] (5, 2) (6, -3) (5, 2) 7KHUH DUH WRNHQV +HOOR 6WULQJ WKHUH 6WULQJ 6WULQJ LV 6WULQJ LQW GRXEOH 6WULQJ DQG 6WULQJ GRXEOH 6WULQJ VTXDUHG 6WULQJ LV 6WULQJ 6WULQJ 7KH FRGH ZLOO UXQ VXFFHVVIXOO\ DQG WKH YDULDEOH PRQH\ ZLOO VWRUH WKH YDOXH 7KH FRGH ZLOO UXQ VXFFHVVIXOO\ DQG WKH YDULDEOH PRQH\ ZLOO VWRUH WKH YDOXH 7KH FRGH ZLOO FUDVK ZLWK DQ H[FHSWLRQ PLOOLRQ 7KH FRGH ZLOO FUDVK ZLWK DQ H[FHSWLRQ 7KH FRGH ZLOO FUDVK ZLWK DQ H[FHSWLRQ 7KH FRGH ZLOO FUDVK ZLWK DQ H[FHSWLRQ QRQH 7KH FRGH ZLOO FUDVK ZLWK DQ H[FHSWLRQ 7KH FRGH ZLOO UXQ VXFFHVVIXOO\ DQG WKH YDULDEOH PRQH\ ZLOO VWRUH WKH YDOXH Scanner console = new Scanner(System.in); System.out.print("Type an integer: "); int number = console.nextInt(); System.out.println(number + " times 2 = " + (number * 2)); 756 Scanner console = new Scanner(System.in); System.out.print("What is your phrase? "); String phrase = console.nextLine(); System.out.print("How many times should I repeat the phrase? "); int times = console.nextInt(); for (int i = 1; i <= times; i++) { System.out.println(phrase); } 6XSSOHPHQW * 2Q WKH VHFRQG OLQH WKH FDOO WR GUDZ/LQH VKRXOG EH PDGH RQ WKH *UDSKLFV REMHFW LQ WKH SDQHO QRW RQ WKH 'UDZLQJ3DQHO LWVHOI 2Q WKH VHFRQG OLQH WKH RUGHU RI WKH SDUDPHWHUV LV LQFRUUHFW 7KH\ VKRXOG EH DQG 7KH IROORZLQJ LV WKH FRUUHFWHG FRGH DrawingPanel panel = new DrawingPanel(200, 200); Graphics g = panel.getGraphics(); panel.drawLine(50, 86, 20, 35); 7KH EODFN UHFWDQJOH LV EHLQJ GUDZQ VHFRQG VR LW V FRYHULQJ XS WKH ZKLWH LQQHU FLUFOH 7KH IROORZLQJ FRGH IL[HV WKH SUREOHP DrawingPanel panel = new DrawingPanel(200, 100); Graphics g = panel.getGraphics(); g.setColor(Color.BLACK); g.fillRect(10, 10, 50, 50); g.setColor(Color.WHITE); g.fillOval(10, 10, 50, 50); 7KH SUREOHP LV WKDW WKH SDUDPHWHUV IRU WKH GUDZ5HFW DQG GUDZ/LQH PHWKRGV KDYH GLIIHUHQW PHDQLQJV ,Q GUDZ5HFW WKH SDUDPHWHUV DUH [ \ ZLGWK KHLJKW DQG LQ GUDZ/LQH WKH\ DUH [ \ [ \ 7R IL[ WKH SUREOHP WKH WKLUG DQG IRXUWK SDUDPHWHUV SDVVHG WR GUDZ5HFW VKRXOG EH FKDQJHG WR DQG VR WKDW WKH UHFWDQJOH V ERWWRP OHIW FRUQHU ZLOO EH DW 7KH IROORZLQJ FRGH IL[HV WKH SUREOHP DrawingPanel panel = new DrawingPanel(200, 100); Graphics g = panel.getGraphics(); g.drawRect(10, 20, 40, 20); g.drawLine(10, 20, 50, 40); 7KH 'UDZ SURJUDP GUDZV EODFN FLUFOHV WKDW JHW VPDOOHU DQG VPDOOHU HDFK FLUFOH ZLWK LWV ULJKW DQG ERWWRP HGJHV WRXFKLQJ WKH ULJKW DQG ERWWRP FRUQHUV RI WKH ZLQGRZ 757 &KDSWHU 7KH VXP YDULDEOH QHHGV WR EH GHFODUHG RXWVLGH WKH IRU ORRS 7KH IROORZLQJ FRGH IL[HV WKH SUREOHP public static int sumTo(int n) { int sum = 0; for (int i = 1; i <= n; i++) { sum += i; } return sum; } 7KH FRGH KDV D IHQFHSRVW SUREOHP D FRPPD ZLOO EH SULQWHG DIWHU WKH ODVW QXPEHU 7KH IROORZLQJ FRGH IL[HV WKH SUREOHP System.out.print(1); for (int i = 1; i <= n; i++) { System.out.print(", " + i); } System.out.println(); // end the line of output Scanner console = new Scanner(System.in); System.out.print("How many numbers? "); int count = console.nextInt(); int product = 1; for (int i = 1; i <= count; i++) { System.out.print("Next number --> "); int num = console.nextInt(); product *= num; } System.out.println("Product = " + product); z % 2 == 1 z <= Math.sqrt(y) y > 0 x % 2 != y % 2 y % z == 0 z != 0 758 Math.abs(y) > Math.abs(z) (x >= 0) == (z < 0) y % 10 == y z >= 0 x % 2 == 0 Math.abs(x - y) < Math.abs(z - y) true false true false true false false true true 7KH FRGH LQFRUUHFWO\ XVHV DQ LI HOVH LI HOVH LI SDWWHUQ ZKHQ LW VKRXOG UHDOO\ XVH DQ LI LI LI SDWWHUQ EHFDXVH WKH WKUHH FRQGLWLRQV DUH QRW PXWXDOO\ H[FOXVLYH RI HDFK RWKHU 7KH JLYHQ FRGH RQO\ DQVZHUV FRUUHFWO\ ZKHQ ]HUR RU RQH RI WKH QXPEHUV DUH RGG LI PRUH WKDQ RQH LV RGG WKH FRGH RQO\ HQWHUV RQH EUDQFK DQG GRHV QRW SURSHUO\ LQFUHPHQW WKH FRXQWHU PXOWLSOH WLPHV 7KH IROORZLQJ YHUVLRQ RI WKH FRGH IL[HV WKH SUREOHP if (n1 % 2 == 1) { count++; } if (n2 % 2 == 1) { count++; } if (n3 % 2 == 1) { count++; } 2U WKH IROORZLQJ YHUVLRQ DFKLHYHV WKH VDPH WKLQJ ZLWKRXW WKH QHHG IRU LI HOVH VWDWHPHQWV count = n1 % 2 + n2 % 2 + n3 % 2; Scanner console = new Scanner(System.in); System.out.print("Type a number: "); int number = console.nextInt(); if (number % 2 == 0) { System.out.println("even"); } else { System.out.println("odd"); } 7KH FRGH LQFRUUHFWO\ SULQWV WKDW HYHQ QXPEHUV QRW GLYLVLEOH E\ DUH RGG 7KLV LV EHFDXVH WKH HOVH VWDWHPHQW PDWFKHV WKH PRVW FORVHO\ QHVWHG LI VWDWHPHQW QXPEHU QRW WKH RXWHU LI VWDWHPHQW 759 7KH IROORZLQJ FKDQJH FRUUHFWV WKH SUREOHP 1RWH WKH EUDFHV DURXQG WKH RXWHU LI VWDWHPHQW if (number % 2 == 0) { if (number % 3 == 0) { System.out.println("Divisible by 6."); } } else { System.out.println("Odd."); } 7KH FRGH VKRXOGQ W UHWXUQ WKH IDFWRU L ZKHQ IRXQG LW VKRXOG LQVWHDG FRXQW KRZ PDQ\ IDFWRUV LW ILQGV 7KLV LV D FXPXODWLYH VXP VR WKH FRXQW YDULDEOH VKRXOG EH GHFODUHG RXWVLGH WKH IRU ORRS 7KH IROORZLQJ FRGH IL[HV WKH SUREOHP public static int countFactors(int n) { int count = 0; for (int i = 1; i <= n; i++) { if (n % i == 0) { // factor count++; } } return count; } public static void moneyMultiply(int sum, int total, int count1, int count2) { Scanner console = new Scanner(System.in); System.out.print("Is your money multiplied 1 or 2 times? "); int times = console.nextInt(); System.out.print("And how much are you contributing? "); int donation = console.nextInt(); sum += times * donation; total += donation; if (times == 1) { count1++; } else if (times == 2) { count2++; } } ,I WKH XVHU FRXOG W\SH DQ\ QXPEHU WKH FRGH PLJKW QHHG DGGLWLRQDO LI VWDWHPHQWV WR LQFUHPHQW WKH SURSHU FRXQW YDULDEOH ,I WKH XVHU FRXOG W\SH DQ\WKLQJ HYHQ D QRQ LQWHJHU WKH FRGH PLJKW QHHG WR XVH WKH hasNextInt PHWKRG RI WKH 6FDQQHU WR HQVXUH YDOLG LQSXW EHIRUH SURFHHGLQJ 760 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 public class Bills { public static void main(String args) { Scanner console = new Scanner(System.in); int numBills1 = getBills(console, "John"); int numBills2 = getBills(console, "Jane"); System.out.println("John needs " + numBills1 + " bills"); System.out.println("Jane needs " + numBills2 + " bills"); } public static int getBills(Scanner console, String name) { System.out.print("How much will " + name + " be spending? "); double amount = console.nextDouble(); System.out.println(); int numBills = (int) (amount/20.0); if (numBills * 20.0 < amount) { numBills++; } return numBills; } } 7KH FRGH ZRQ W HYHU SULQW 0LQH WRR EHFDXVH 6WULQJV FDQQRW EH FRPSDUHG ZLWK WKH RSHUDWRU 7KH IRXUWK OLQH RI WKH FRGH VKRXOG EH FKDQJHG WR WKH IROORZLQJ if (name.equals("blue")) { 7KH FRGH V RXWSXW LV WKH IROORZLQJ EHFDXVH WKH PHWKRG non-equal second third RSHUDWRU ZDV XVHG LQVWHDG RI WKH HTXDOV Scanner console = new Scanner(System.in); System.out.print("What color do you want? "); String choice = console.nextLine(); if (choice.equalsIgnoreCase("r")) { System.out.println("You have chosen Red."); } else if (choice.equalsIgnoreCase("g")) { System.out.println("You have chosen Green."); } else if (choice.equalsIgnoreCase("b")) { System.out.println("You have chosen Blue."); } else { System.out.println("Unknown color: " + choice); } 761 Scanner console = new Scanner(System.in); System.out.print("Enter a card: "); String rank = console.next(); String suit = console.next(); if (rank.equals("2")) { rank = "Two"; } else if (rank.equals("3")) { rank = "Three"; } else if (rank.equals("4")) { rank = "Four"; } else if (rank.equals("5")) { rank = "Five"; } else if (rank.equals("6")) { rank = "Six"; } else if (rank.equals("7")) { rank = "Seven"; } else if (rank.equals("8")) { rank = "Eight"; } else if (rank.equals("9")) { rank = "Nine"; } else if (rank.equals("10")) { rank = "Ten"; } else if (rank.equals("J")) { rank = "Jack"; } else if (rank.equals("Q")) { rank = "Queen"; } else if (rank.equals("K")) { rank = "King"; } else { // rank.equals("A") rank = "Ace"; } if (suit.equals("C")) { suit = "Clubs"; } else if (suit.equals("D")) { suit = "Diamonds"; } else if (suit.equals("H")) { suit = "Hearts"; } else { // suit.equals("S") suit = "Spades"; } System.out.println(rank + " of " + suit); 7KH H[SUHVVLRQ HTXDOV OHG WR D URXQGRII 7KH H[SUHVVLRQ JSD HTXDOV WR WHVW WKDW WKH YDOXH ZDV FORVH WR EHFDXVH RI WKH OLPLWHG SUHFLVLRQ RI WKH GRXEOH W\SH EHFDXVH RI GRXEOH URXQGRII $ IL[ ZRXOG EH UDWKHU WKDQ H[DFWO\ HTXDO WR LW double gpa = 3.2; if (Math.abs(gpa * 3 - 9.6) < 0.1) { System.out.println("You earned enough credits."); } 762 if (Character.isUpperCase(theString.charAt(0))) { ... } 7KH WR/RZHU&DVH PHWKRG FDQQRW EH FDOOHG RQ D FKDU YDOXH ZKLFK LV ZKDW WKH FKDU$W PHWKRG UHWXUQV $ EHWWHU VROXWLRQ ZRXOG EH WR FDOO WKH &KDUDFWHU WR/RZHU&DVH PHWKRG RQ WKH FKDUDFWHUV RI WKH VWULQJ int count = 0; for (int i = 0; i < s.length(); i++) { if (Character.toLowerCase(s.charAt(i)) == 'e') { count++; } } $QRWKHU VROXWLRQ ZRXOG EH WR ORZHUFDVH WKH HQWLUH VWULQJ RQFH EHIRUH WKH ORRS s = s.toLowerCase(); int count = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == 'e') { count++; } } String name = "Marla Singer"; int space = name.indexOf(" "); String lastName = name.substring(space + 1); String firstInitial = name.substring(0, 1); String lastNameFirstInitial = lastName + ", " + firstInitial + "."; System.out.println(lastNameFirstInitial); RU D VKRUWHU YHUVLRQ String name = "Marla Singer"; System.out.println(name.substring(name.indexOf(" ") + 1) + ", " + name.charAt(0) + "."); // assuming that the string is stored in variable 'str' int count = 0; for (int i = 0; i < str.length(); i++) { if (Character.toLowerCase(str.charAt(i)) >= 'n') { count++; } } System.out.println(count + " letters come after n."); 763 public static void printTriangleType(int s1, int s2, int s3) { if (s1 == s2) { if (s2 == s3) { System.out.println("equilateral"); } } else if (s2 == s3) { System.out.println("isosceles"); } else { System.out.println("scalene"); } } ,QYDOLG YDOXHV DUH ZKHQ D VLGH V OHQJWK LV QHJDWLYH RU ZKHQ DQ\ RQH VLGH OHQJWK LV JUHDWHU WKDQ WKH VXP RI WKH RWKHU WZR VLGH OHQJWKV EHFDXVH WKLV FDQQRW EH D YDOLG WULDQJOH 7KH SUHFRQGLWLRQ RI RI WKH SULQW7ULDQJOH7\SH PHWKRG LV WKDW WKH VLGH OHQJWKV FRQVWLWXWH D YDOLG WULDQJOH 7KH SUHFRQGLWLRQV RI WKLV PHWKRG DUH WKDW WKH JUDGH SDUDPHWHU V YDOXH LV EHWZHHQ DQG 7KH FRGH IDLOV ZKHQ Q LV WKH VPDOOHVW RI WKH WKUHH QXPEHUV IRU H[DPSOH ZKHQ WKH SDUDPHWHUV YDOXHV DUH WKH FRGH VKRXOG UHWXUQ EXW LQVWHDG UHWXUQV 7KH PHWKRG FRXOG EH FRUUHFWO\ ZULWWHQ DV public static int medianOf3(int n1, int n2, int n3) { if (n1 < n2 && n1 < n3) { if (n2 < n3) { return n2; } else { return n3; } } else if (n2 < n1 && n2 < n3) { if (n1 < n3) { return n1; } else { return n3; } } else { // (n3 < n1 && n3 < n2) if (n1 < n2) { return n1; } else { return n2; } } } RU WKH IROORZLQJ VKRUWHU YHUVLRQ public static int medianOf3_2(int n1, int n2, int n3) { return Math.max(Math.max(Math.min(n1, n2), Math.min(n2, n3)), Math.min(n1, n3)); } ,QYDOLG YDOXHV DUH ZKHQ D ZKHQ E DF EHFDXVH LW PDNHV WKH GHQRPLQDWRU RI WKH HTXDWLRQ HTXDO RU EHFDXVH WKHQ LW KDV QR UHDO VTXDUH URRW 764 // Throws an exception if a, b, c are invalid. public static void quadratic(int a, int b, int c) { double determinant = b * b - 4 * a * c; if (a == 0) { throw new IllegalArgumentException("Invalid a value of 0"); } if (determinant < 0) { throw new IllegalArgumentException("Invalid determinant"); } ... } &KDSWHU H[HFXWHV ERG\ WLPHV H[HFXWHV ERG\ WLPHV 2 4 16 1 11 21 31 41 51 61 71 81 91 H[HFXWHV ERG\ WLPHV QR RXWSXW ORRSV LQILQLWHO\ 250 250 250 H[HFXWHV ERG\ WLPHV bbbbbabbbbb H[HFXWHV ERG\ WLPHV 10 5 2 1 0 0 0 UHSHDWV IRUHYHU int n = 1; while (n <= max) { System.out.println(n); n++; } int total = 25; int number = 1; while (number <= (total / 2)) { total = total - number; System.out.println(total + " number++; } " + number); 765 int i = 1; while (i <= 2) { int j = 1; while (j <= 3) { int k = 1; while (k <= 4) { System.out.print("*"); k++; } System.out.print("!"); j++; } System.out.println(); i++; } int number = 4; int count = 1; while (count <= number) { System.out.println(number); number = number / 2; count++; } Method Call Output -------------------------------------mystery(1); 1 0 mystery(6); 4 2 mystery(19); 16 4 mystery(39); 32 5 mystery(74); 64 6 Method Call Output -------------------------------------mystery(19); 19 0 mystery(42); 21 1 mystery(48); 3 4 mystery(40); 5 3 mystery(64); 1 6 766 int SENTINEL = -1; System.out.print("Type a number (or " + SENTINEL + " to stop): "); Scanner console = new Scanner(System.in); int input = console.nextInt(); int min = input; int max = input; while (input != SENTINEL) { if (input < min) { min = input; } else if (input > max) { max = input; } System.out.print("Type a number (or " + SENTINEL + " to stop): "); input = console.nextInt(); } if (min != SENTINEL) { System.out.println("Maximum was " + max); System.out.println("Minimum was " + min); } public static int zeroDigits(int number) { int count = 0; do { if (number % 10 == 0) { count++; } number = number / 10; } while (number > 0); return count; } Scanner console = new Scanner(System.in); System.out.print("Type a number: "); int number = console.nextInt(); String textNumber = String.valueOf(number); // print odd digits for (int i = 0; i < textNumber.length(); i++) { int digit = Character.getNumericValue(textNumber.charAt(i)); if (digit % 2 == 1) { System.out.print(digit); } } // print even digits for (int i = 0; i < textNumber.length(); i++) { int digit = Character.getNumericValue(textNumber.charAt(i)); if (digit % 2 == 0) { System.out.print(digit); } } 767 a: b: c: d: e: 0 through 99 inclusive 50 through 69 inclusive 0 through 69 inclusive -20 through 79 inclusive 0, 4, 8, 16, 20, 24, 28, 32, or 36 Random rand = new Random(); int num = rand.nextInt(11); Random rand = new Random(); int num = rand.nextInt(25) * 2 + 51; true true false true true false false true true true true false public static boolean isVowel(char c) { c = Character.toLowerCase(c); // case-insensitive return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; } RU public static boolean isVowel2(char c) { String vowels = "aeiouAEIOU"; return vowels.indexOf(c) >= 0; } ,Q WKLV FRGH WKH ERROHDQ IODJ LVQ W EHLQJ XVHG SURSHUO\ EHFDXVH LI WKH FRGH ILQGV D IDFWRU RI WKH QXPEHU SULPH ZLOO EH VHW WR IDOVH EXW RQ WKH QH[W SDVV WKURXJK WKH ORRS LI WKH QH[W QXPEHU LVQ W D IDFWRU SULPH ZLOO EH UHVHW EDFN WR WUXH DJDLQ 7KH IROORZLQJ FRGH IL[HV WKH SUREOHP public static boolean isPrime(int n) { boolean prime = true; for (int i = 2; i < n; i++) { if (n % i == 0) { prime = false; } } return prime; } 768 ,Q WKLV FRGH WKH ERROHDQ IODJ LVQ W EHLQJ XVHG SURSHUO\ EHFDXVH LI WKH FRGH ILQGV WKH FKDUDFWHU IRXQG ZLOO EH VHW WR WUXH EXW RQ WKH QH[W SDVV WKURXJK WKH ORRS LI WKH QH[W FKDUDFWHU LVQ W FK IRXQG ZLOO EH UHVHW EDFN WR IDOVH DJDLQ 7KH IROORZLQJ FRGH IL[HV WKH SUREOHP public static boolean contains(String str, char ch) { boolean found = false; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == ch) { found = true; } } return found; } public static boolean startEndSame(String str) { return str.charAt(0) == str.charAt(str.length() - 1); } public static boolean hasPennies(int cents) { return cents % 5 != 0; } Method Call Value Returned ---------------------------------------------mystery(3, 3) 3 mystery(5, 3) 1 mystery(2, 6) 2 mystery(12, 18) 6 mystery(30, 75) 15 7KH FRGH VKRXOG UH SURPSW IRU D YDOLG LQWHJHU IRU WKH XVHU V DJH DQG D YDOLG UHDO QXPEHU IRU WKH XVHU V *3$ ,I WKH XVHU W\SHV D WRNHQ RI WKH ZURQJ W\SH WKHLU OLQH RI LQSXW VKRXOG EH FRQVXPHG DQG WKH\ VKRXOG EH UHSURPSWHG 7KH IROORZLQJ FRGH LPSOHPHQWV WKH FRUUHFWHG EHKDYLRU Scanner console = new Scanner(System.in); System.out.print("Type your age: "); while (!console.hasNextInt()) { console.nextLine(); // throw away the offending token System.out.print("Type your age: "); } int age = console.nextInt(); System.out.print("Type your GPA: "); while (!console.hasNextDouble()) { console.nextLine(); // throw away the offending token System.out.print("Type your GPA: "); } double gpa = console.nextDouble(); :KHQ WKH XVHU W\SHV Jane Type something for me! Jane Your name is Jane 769 :KHQ WKH XVHU W\SHV 56 Type something for me! 56 Your IQ is 56 :KHQ WKH XVHU W\SHV 56.2 Type something for me! 56.2 Your name is 56.2 Scanner console = new Scanner(System.in); System.out.print("Type a number: "); if (console.hasNextDouble()) { double value = console.nextDouble(); System.out.println("You typed the real number " + value); } else if (console.hasNextInt()) { int value = console.nextInt(); System.out.println("You typed the integer " + value); } String prompt = "Please enter a number: "; Scanner console = new Scanner(System.in); int num1 = getInt(console, prompt); int num2 = getInt(console, prompt); int num3 = getInt(console, prompt); double average = (num1 + num2 + num3) / 3.0; System.out.println("Average: " + average); H[HFXWHV ERG\ WLPHV H[HFXWHV ERG\ WLPHV 2 4 16 1 11 21 31 41 51 61 71 81 91 LQILQLWH count down: 10 count down: 9 H[HFXWHV ERG\ WLPHV bbbbbabbbbb UHSHDWV IRUHYHU ORRSV LQILQLWHO\ 250 250 250 H[HFXWHV ERG\ WLPHV 10 5 2 1 0 0 0 UHSHDWV IRUHYHU H[HFXWHV ERG\ WLPHV 100 50 H[HFXWHV ERG\ WLPHV /\/\/\/\/\/\/\/\ 770 Scanner console = new Scanner(System.in); String response; do { System.out.println("She sells seashells by the seashore."); System.out.print("Do you want to hear it again? "); response = console.nextLine(); } while (response.equals("y")); Scanner console = new Scanner(System.in); Random rand = new Random(); int num; do { num = rand.nextInt(1000); System.out.println("Random number: " + num); } while (num < 900); int SENTINEL = -1; Scanner console = new Scanner(System.in); int input = console.nextInt(); int min = input; int max = input; while (true) { System.out.print("Type a number (or " + SENTINEL + " to stop): "); input = console.nextInt(); if (input == SENTINEL) { break; } if (input < min) min = input; else if (input > max) max = input; } if (min != SENTINEL || max != SENTINEL) { System.out.println("Maximum was " + max); System.out.println("Minimum was " + min); } y < x SOMETIMES ALWAYS ALWAYS SOMETIMES NEVER n > b SOMETIMES ALWAYS SOMETIMES SOMETIMES NEVER y == 0 SOMETIMES SOMETIMES ALWAYS SOMETIMES SOMETIMES a > 1 SOMETIMES SOMETIMES ALWAYS ALWAYS SOMETIMES count > 0 NEVER SOMETIMES ALWAYS SOMETIMES SOMETIMES b > a SOMETIMES SOMETIMES ALWAYS NEVER SOMETIMES Point Point Point Point Point A: B: C: D: E: Point Point Point Point Point A: B: C: D: E: 771 Point Point Point Point Point A: B: C: D: E: next == 0 SOMETIMES NEVER NEVER SOMETIMES ALWAYS prev == 0 ALWAYS SOMETIMES NEVER NEVER SOMETIMES next == prev SOMETIMES SOMETIMES ALWAYS SOMETIMES SOMETIMES &KDSWHU Scanner input = new Scanner(new File("input.txt")); 7KH 6FDQQHU VKRXOG UHDG D QHZ )LOH ZLWK WKH QDPH WHVW GDW 7KH FRUUHFW OLQH RI FRGH LV Scanner input = new Scanner(new File("test.dat")); 7KH ILOH QDPH 6WULQJ VKRXOG XVH RU ?? LQVWHDG RI ? 7KH ? LV XVHG WR FUHDWH HVFDSH VHTXHQFHV DQG ?? UHSUHVHQWV D OLWHUDO EDFNVODVK 7KH FRUUHFW 6WULQJ LV Scanner input = new Scanner(new File("C:/temp/new files/test.dat")); Scanner input = new Scanner(new File("input.txt")); "numbers.dat" numbers.dat" RU "C:/Documents and Settings/amanda/My Documents/programs/ "data/homework6/input.dat" RU "C:/Documents programs/data/homework6/input.dat" and Settings/amanda/My Documents/ 7KHUH LV RQO\ RQH OHJDO ZD\ WR UHIHU WR WKLV ILOH E\ LWV DEVROXWH SDWK "C:/Documents and Settings/amanda/My Documents/homework/data.txt" RU "/home/amanda/Documents/hw6/names.txt" RU "/home/amanda/Documents/hw6/data/numbers.txt" 7KHUH LV RQO\ RQH OHJDO ZD\ WR UHIHU WR WKLV ILOH E\ LWV DEVROXWH SDWK "/home/amanda/ "names.txt" "data/numbers.txt" download/saved.html" input: 6.7 This file has input: several input lines. input: input: 10 20 30 40 input: input: test 6 total input: 6.7 input: This input: file input: has input: several input: input input: lines. input: 10 input: 20 input: 30 input: 40 input: test 12 total 772 XVLQJ KDV1H[W,QW DQG QH[W,QW 0 total XVLQJ KDV1H[W'RXEOH DQG QH[W'RXEOH input: 6.7 1 total 1 2 3 4 5 6 7 8 9 10 11 import java.io.*; import java.util.*; public class PrintMyself { public static void main(String args) throws FileNotFoundException { Scanner input = new Scanner(new File("PrintMyself.java")); while (input.hasNextLine()) { System.out.println(input.nextLine()); } } } public static void printEntireFile() throws FileNotFoundException { Scanner console = new Scanner(System.in); System.out.print("Type a file name: "); String filename = console.nextLine(); Scanner input = new Scanner(new File(filename)); while (input.hasNextLine()) { System.out.println(input.nextLine()); } } $ 3ULQW6WUHDP REMHFW LV XVHG WR ZULWH WR DQ H[WHUQDO ILOH ,W KDV PHWKRGV VXFK DV SULQWOQ DQG SULQW PrintStream out = new PrintStream(new File("message.txt")); out.println("Testing,"); out.println("1, 2, 3."); out.println(); out.println("This is my output file."); public static String getFileName() { Scanner console = new Scanner(System.in); String filename = null; do { System.out.print("Type a file name: "); filename = console.nextLine(); } while (!(new File(filename).exists())); return filename; } 773 // re-prompts until file name is valid public static void printEntireFile2() throws FileNotFoundException { String filename = getFileName(); Scanner input = new Scanner(new File(filename)); while (input.hasNextLine()) { System.out.println(input.nextLine()); } } &KDSWHU ILUVW HOHPHQW numbers[0] ODVW HOHPHQW numbers[9] RU numbers[numbers.length - 1] int data = new int[5]; data[0] = 27; data[1] = 51; data[2] = 33; data[3] = -1; data[4] = 101; int odds = new int[22]; for (int i = 0; i < 22; i++) { odds[i] = i * 2 - 5; } ^ ` public static int sumAll(int a) { int sum = 0; for (int i = 0; i < a.length; i++) { sum += a[i]; } return sum; } public static double average(int a) { double mean = 0.0; for (int i = 0; i < a.length; i++) { mean += a[i]; } return mean / a.length; } RU PRUH FRQFLVH YHUVLRQ XVLQJ VROXWLRQ IURP SUHYLRXV H[HUFLVH public static double average2(int a) { return (double) sumAll(a) / a.length; } 7KH FRGH WR SULQW WKH DUUD\V DQG WR FRPSDUH WKHP GRHVQ W ZRUN SURSHUO\ $UUD\V FDQ W EH SULQWHG GLUHFWO\ E\ SULQWOQ QRU FDQ WKH\ EH FRPSDUHG GLUHFWO\ XVLQJ WKH UHODWLRQDO RSHUDWRUV VXFK DV 7KHVH RSHUDWLRQV FDQ EH GRQH FRUUHFWO\ E\ ORRSLQJ RYHU WKH HOHPHQWV RI HDFK DUUD\ DQG SULQWLQJ FRPSDULQJ WKHP RQH DW D WLPH 774 public static boolean equal(int array1, int array2) { if (array1.length != array2.length) { return false; } for (int i = 0; i < array1.length; i++) { if (array1[i] != array2[i]) { return false; } } return true; } int data = {7, -1, 13, 24, 6}; ^ ^ ` ` for (int i = 0; i < data.length; i++) { System.out.println("Element [" + i + "] is " + data[i]); } D D D D ^ ^ ^ ^ ^ ` ` ` ` ` public static double averageLength(String strings) { int sum = 0; for (int i = 0; i < strings.length; i++) { sum += strings[i].length(); } return (double) sum / strings.length; } public static boolean isPalindrome(String array) { for (int i = 0; i < array.length / 2; i++) { if (!array[i].equals(array[array.length - 1 - i])) { return false; } } return true; } &KDSWHU 3URFHGXUDO SURJUDPPLQJ WUHDWV D SURJUDP DV D VHTXHQFH RI DFWLRQV RU FRPPDQGV WR SHUIRUP 2EMHFW RULHQWHG SURJUDPPLQJ ORRNV DW D SURJUDP DV D JURXS RI LQWHUDFWLQJ HQWLWLHV QDPHG REMHFWV WKDW HDFK NHHS WUDFN RI UHODWHG GDWD DQG EHKDYLRU 775 $Q REMHFW LV DQ HQWLW\ WKDW HQFDSVXODWHV GDWD DQG EHKDYLRU WKDW RSHUDWHV RQ WKH GDWD $ FODVV LV WKH EOXHSULQW IRU D W\SH RI REMHFWV VSHFLI\LQJ ZKDW GDWD DQG EHKDYLRU HDFK ZLOO KDYH DQG KRZ WR FRQVWUXFW WKRVH REMHFWV 6RPH REMHFWV ZH YH XVHG VR IDU 6WULQJ 3RLQW 6FDQQHU 'UDZLQJ3DQHO *UDSKLFV &RORU )RQW 5DQGRP )LOH $ GDWD ILHOG LV D YDULDEOH WKDW H[LVWV LQVLGH RI DQ REMHFW $ SDUDPHWHU LV D YDULDEOH LQVLGH D PHWKRG ZKRVH YDOXH LV SDVVHG LQ IURP RXWVLGH 'DWD ILHOGV KDYH GLIIHUHQW V\QWD[ EHFDXVH WKH\ DUH XVXDOO\ GHFODUHG ZLWK WKH SULYDWH NH\ZRUG DQG QRW LQ D PHWKRG V KHDGHU $ GDWD ILHOG V VFRSH LV WKURXJKRXW WKH FODVV ZKLOH D SDUDPHWHU V VFRSH LV MXVW ZLWKLQ WKDW PHWKRG $Q LQVWDQFH PHWKRG GRHVQ W KDYH WKH VWDWLF NH\ZRUG $OVR LW PD\ DFFHVV RU PRGLI\ WKH GDWD ILHOGV RI WKDW REMHFW XVLQJ WKH WKLV NH\ZRUG 7KH\ UH XVHG GLIIHUHQWO\ EHFDXVH REMHFWV PHWKRGV DUH SUHFHGHG E\ VRPH YDULDEOH V QDPH DQG D GRW $Q DFFHVVRU SURYLGHV WKH FOLHQW DFFHVV WR VRPH GDWD LQ WKH REMHFW ZKLOH D PXWDWRU OHWV WKH FOLHQW FKDQJH WKH REMHFW V VWDWH LQ VRPH ZD\ $FFHVVRUV QDPHV RIWHQ EHJLQ ZLWK JHW RU LV ZKLOH PXWDWRUV RIWHQ EHJLQ ZLWK VHW $ FRQVWUXFWRU LV D VSHFLDO PHWKRG WKDW FUHDWHV DQ REMHFW DQG LQLWLDOL]HV LWV VWDWH ,W V WKH PHWKRG WKDW LV FDOOHG ZKHQ \RX XVH WKH QHZ NH\ZRUG ,W LV GHFODUHG ZLWKRXW D UHWXUQ W\SH 2QH SUREOHP LV WKDW WKH FRQVWUXFWRU VKRXOGQ W KDYH WKH YRLG NH\ZRUG LQ LWV KHDGHU EHFDXVH FRQVWUXFWRUV KDYH QR UHWXUQ W\SH 7KH KHDGHU VKRXOG EH public Point(int x, int y) { $OVR WKH GDWD ILHOGV [ DQG \ VKRXOGQ W KDYH WKHLU W\SHV UHGHFODUHG LQ IURQW RI WKHP 7KLV LV D EXJ DQG FDXVHV VKDGRZLQJ RI WKH GDWD ILHOGV +HUH DUH WKH FRUUHFWHG OLQHV x = initialX; y = initialY; $EVWUDFWLRQ LV WKH DELOLW\ WR IRFXV RQ D SUREOHP DW D KLJK OHYHO ZLWKRXW ZRUU\LQJ DERXW WKH PLQRU GHWDLOV 2EMHFWV SURYLGH DEVWUDFWLRQ E\ JLYLQJ XV PRUH SRZHUIXO SLHFHV RI GDWD WKDW KDYH VRSKLVWLFDWHG EHKDYLRU ZLWKRXW KDYLQJ WR PDQDJH DQG PDQLSXODWH WKH GDWD GLUHFWO\ ,WHPV GHFODUHG SXEOLF PD\ EH VHHQ DQG XVHG IURP DQ\ FODVV ,WHPV GHFODUHG SULYDWH PD\ RQO\ EH VHHQ DQG XVHG IURP ZLWKLQ WKHLU RZQ FODVV 2EMHFWV GDWD ILHOGV VKRXOG EH GHFODUHG SULYDWH WR SURYLGH HQFDSVXODWLRQ VR WKDW H[WHUQDO FRGH FDQ W PDNH XQZDQWHG GLUHFW PRGLILFDWLRQV WR WKH ILHOGV YDOXHV 7R DFFHVV SULYDWH GDWD ILHOGV FUHDWH DFFHVVRU PHWKRGV WKDW UHWXUQ WKHLU YDOXHV )RU H[DPSOH DGG D JHW1DPH PHWKRG WR DFFHVV WKH QDPH ILHOG RI DQ REMHFW 7R PDNH WKH REMHFWV RI \RXU FODVV SULQWDEOH GHILQH D WR6WULQJ PHWKRG LQ LW 776 // Returns a String representation of this Point object. public String toString() { return "java.awt.Point[x=" + this.x + ", y=" + this.y + "]"; } 7KH WKLV NH\ZRUG UHIHUV WR WKH REMHFW RQ ZKLFK D PHWKRG KDV EHHQ FDOOHG ,W LV XVHG WR DFFHVV RU VHW WKDW REMHFW V GDWD ILHOG YDOXHV RU WR FDOO WKDW REMHFW V RWKHU PHWKRGV // Constructs a Point object with the same x and y // coordinates as the given Point. public Point(Point p) { this.x = p.x; this.y = p.y; } RU // Constructs a Point object with the same x and y // coordinates as the given Point. public Point(Point p) { this(p.x, p.y); } 7KH RSHUDWRU GRHVQ W ZRUN ZLWK REMHFWV EHFDXVH LW MXVW FRPSDUHV UHIHUHQFHV WR VHH ZKHWKHU WKH\ SRLQW WR H[DFWO\ WKH VDPH REMHFW ,W GRHVQ W FRPSDUH WZR REMHFWV WR VHH ZKHWKHU WKH\ KDYH WKH VDPH VWDWH ZKLFK LV XVXDOO\ ZKDW \RX ZDQW ,I \RX ZDQW \RXU REMHFWV WR EH FRPSDUHG FRUUHFWO\ GHILQH DQ HTXDOV PHWKRG LQ \RXU FODVV DQG XVH HTXDOV LQVWHDG RI LQ WKH FOLHQW FRGH // Returns this Stock's number of shares purchased. public int getShares() { return this.numShares; } // Returns this Stock's symbol value. public String getSymbol() { return this.symbol; } // Returns this Stock's total cost. public double getTotalCost() { return this.totalCost; } &KDSWHU &RGH UHXVH LV WKH DELOLW\ WR ZULWH D VLQJOH SLHFH RI FRGH WKDW FDQ EH XVHG PDQ\ WLPHV LQ GLIIHUHQW SURJUDPV DQG FRQWH[WV ,QKHULWDQFH LV XVHIXO IRU FRGH UHXVH EHFDXVH LW DOORZV \RX WR ZULWH D FODVV WKDW FDSWXUHV FRPPRQ XVHIXO FRGH DQG WKHQ H[WHQG WKDW FODVV WR DGG PRUH IHDWXUHV DQG EHKDYLRU WR LW 2YHUORDGLQJ D PHWKRG LV FUHDWLQJ WZR PHWKRGV LQ WKH VDPH FODVV WKDW KDYH WKH VDPH QDPH EXW GLIIHUHQW SDUDPHWHUV 2YHUULGLQJ D PHWKRG LV FUHDWLQJ D QHZ YHUVLRQ RI DQ LQKHULWHG PHWKRG LQ D VXEFODVV ZLWK LGHQWLFDO SDUDPHWHUV EXW QHZ EHKDYLRU WR UHSODFH WKH ROG 777 7KH IROORZLQJ VWDWHPHQWV DUH OHJDO Vehicle v = new Car(); Vehicle v = new SUV(); Car c = new SUV(); SUV s = nev SUV(); B 2 A A 1 D 2 C C 1 A 2 A A 1 A 2 C C 1 flute shoe 1 flute 2 flute blue 1 flute 2 moo moo 1 moo 2 moo blue 1 moo 2 moo 2 blue 1 moo moo 2 moo 1 moo flute 2 shoe 1 flute flute 2 blue 1 flute 778 squid creature 1 tentacles BIG! spout creature 2 ocean-dwelling creature 1 creature 2 ocean-dwelling warm-blooded creature 2 creature 2 ocean-dwelling creature 1 tentacles squid creature 1 creature 2 ocean-dwelling warm-blooded creature 2 BIG! spout 7KH WKLV NH\ZRUG UHIHUV WR WKH FXUUHQW REMHFW ZKLOH WKH VXSHU NH\ZRUG UHIHUV WR WKH FXUUHQW FODVV V VXSHUFODVV 8VH WKH VXSHU NH\ZRUG ZKHQ FDOOLQJ D PHWKRG RU FRQVWUXFWRU IURP WKH VXSHUFODVV WKDW \RX YH RYHUULGGHQ DQG XVH WKH WKLV NH\ZRUG ZKHQ DFFHVVLQJ \RXU REMHFW V RWKHU GDWD ILHOGV FRQVWUXFWRUV DQG PHWKRGV )UHVKPDQ FDQ FDOO WKH VHW$JH PHWKRG EXW FDQQRW GLUHFWO\ DFFHVV WKH QDPH RU DJH GDWD ILHOGV IURP 6WXGHQW 7ZR VROXWLRQV DUH VKRZQ // Constructs a 3D Point at the origin of (0, 0, 0). public Point3D() { super(0, 0); this.z = 0; } // Constructs a 3D Point at the origin of (0, 0, 0). public Point3D() { this(0, 0, 0); } ([WHQGLQJ D FODVV FDXVHV \RXU FODVV WR LQKHULW DOO PHWKRGV DQG GDWD IURP WKDW FODVV ,PSOHPHQWLQJ DQ LQWHUIDFH IRUFHV \RX WR ZULWH \RXU RZQ FRGH WR LPSOHPHQW DOO WKH PHWKRGV LQ WKDW LQWHUIDFH 779 7KH FRGH IRU FODVV & PXVW FRQWDLQ LPSOHPHQWDWLRQV RI WKH PHWKRGV P DQG P WR FRPSLOH FRUUHFWO\ EHFDXVH & FODLPV WR LPSOHPHQW WKH , LQWHUIDFH 7KH LQWHUIDFH LV LQFRUUHFW EHFDXVH LQWHUIDFHV FDQ W GHFODUH GDWD ILHOGV RU ZULWH ERGLHV IRU PHWKRGV 7KH IROORZLQJ LV D FRUUHFW LQWHUIDFH 1 2 3 4 5 6 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 import java.awt.*; // Represents items that have a color that can be retrieved. public interface Colored { public Color getColor(); } // Represents a point with a color. import java.awt.*; public class ColoredPoint extends Point implements Colored { private Color color; // Constructs a new colored point with the given // coordinates and color. public ColoredPoint(int x, int y, Color color) { super(x, y); this.color = color; } // Returns this point's color. public Color getColor() { return color; } } $Q DEVWUDFW FODVV LV D FODVV LQWHQGHG WR EH XVHG RQO\ DV D VXSHUFODVV IRU LQKHULWDQFH ,W V OLNH D QRUPDO FODVV LQ WKDW LW FDQ KDYH GDWD ILHOGV PHWKRGV FRQVWUXFWRUV DQG VR RQ ,W V GLIIHUHQW IURP D QRUPDO FODVV LQ WKDW LW FDQ KDYH DEVWUDFW PHWKRGV ZKLFK DUH OLNH PHWKRGV RI DQ LQWHUIDFH EHFDXVH RQO\ WKHLU KHDGHUV DUH JLYHQ EXW QRW WKHLU ERGLHV ,W V DOVR GLIIHUHQW IURP D QRUPDO FODVV EHFDXVH LW FDQ W EH LQVWDQWLDWHG XVHG WR FUHDWH REMHFWV 2QH JRRG GHVLJQ ZRXOG EH WR KDYH DQ DEVWUDFW VXSHUFODVV QDPHG 0RYLH ZLWK GDWD VXFK DV QDPH GLUHFWRU DQG GDWH 7KHUH ZRXOG EH VXEFODVVHV RI 0RYLH WR UHSUHVHQW WKH SDUWLFXODU PRYLH W\SHV VXFK DV 'UDPD &RPHG\ 'RFXPHQWDU\ (DFK VXEFODVV ZRXOG VWRUH LWV VSHFLILF GDWD DQG EHKDYLRU &KDSWHU $Q $UUD\/LVW LV D VWUXFWXUH WKDW VWRUHV D FROOHFWLRQ RI REMHFWV LQVLGH LWVHOI DV HOHPHQWV (DFK HOHPHQW LV DVVRFLDWHG ZLWK DQ LQWHJHU LQGH[ VWDUWLQJ IURP <RX VKRXOG XVH DQ $UUD\/LVW LQVWHDG RI DQ DUUD\ LI \RX GRQ W NQRZ KRZ PDQ\ HOHPHQWV \RX OO QHHG LQ DGYDQFH RU LI \RX SODQ WR DGG DQG UHPRYH LWHPV IURP WKH PLGGOH RI \RXU GDWDVHW 780 ArrayList<String> list = new ArrayList<String>(); list.add("It"); list.add("was"); list.add("a"); list.add("stormy"); list.add("night"); 7KH OLVW V W\SH LV ArrayList<String> DQG LWV VL]H LV list.add(3, "dark"); list.add(4, "and"); list.set(1, "IS"); for (int i = 0; i < list.size(); i++) { if (list.get(i).indexOf("a") >= 0) { list.remove(i); i--; // so the new element i will be checked } } ArrayList<Integer> numbers = new ArrayList<Integer>(); for (int i = 0; i < 10; i++) { numbers.add(2 * i); } public static int maxLength(ArrayList<String> list) { int max = 0; for (int i = 0; i < list.size(); i++) { String s = list.get(i); if (s.length() > max) { max = s.length(); } } return max; } System.out.println(list.contains("IS")); System.out.println(list.indexOf("stormy")); System.out.println(list.indexOf("dark")); for (String s : list) { System.out.println(s.toUpperCase()); } 7KH FRGH WKURZV D &RQFXUUHQW0RGLILFDWLRQ([FHSWLRQ EHFDXVH LW LV LOOHJDO WR PRGLI\ WKH HOHPHQWV RI DQ $UUD\/LVW ZKLOH IRU HDFKLQJ RYHU LW 7KH FRGH GRHVQ W FRPSLOH EHFDXVH SULPLWLYHV FDQQRW EH VSHFLILHG DV W\SH SDUDPHWHUV IRU JHQHULF W\SHV 7KH VROXWLRQ LV WR XVH WKH ZUDSSHU W\SH ,QWHJHU LQVWHDG RI LQW &KDQJH WKH OLQH GHFODULQJ WKH $UUD\/LVW WR WKH IROORZLQJ ArrayList<Integer> numbers = new ArrayList<Integer>(); 781 $ ZUDSSHU FODVV LV RQH ZKRVH PDLQ SXUSRVH LV WR DFW DV D EULGJH EHWZHHQ SULPLWLYH YDOXHV DQG REMHFWV $Q ,QWHJHU LV DQ REMHFW WKDW KROGV DQ LQW YDOXH :UDSSHUV DUH XVHIXO WR DOORZ SULPLWLYH YDOXHV WR EH VWRUHG LQWR FROOHFWLRQV 7R DUUDQJH DQ $UUD\/LVW LQWR VRUWHG RUGHU FDOO WKH Collections.sort PHWKRG RQ LW )RU H[DPSOH LI \RXU $UUD\/LVW LV VWRUHG LQ D YDULDEOH QDPHG OLVW Collections.sort(list); )RU WKLV WR ZRUN WKH W\SH RI REMHFWV VWRUHG LQ WKH OLVW PXVW EH &RPSDUDEOH $ QDWXUDO RUGHULQJ LV DQ RUGHU IRU REMHFWV RI D FODVV ZKHUH OHVVHU REMHFWV FRPH EHIRUH JUHDWHU RQHV DV GHWHUPLQHG E\ D SURFHGXUH FDOOHG WKH FODVV V FRPSDULVRQ IXQFWLRQ 7R JLYH \RXU RZQ FODVV D QDWXUDO RUGHULQJ GHFODUH LW WR LPSOHPHQW WKH &RPSDUDEOH LQWHUIDFH DQG GHILQH D FRPSDULVRQ IXQFWLRQ IRU LW E\ ZULWLQJ DQ DSSURSULDWH FRPSDUH7R PHWKRG n1.compareTo(n2) n3.compareTo(n1) n2.compareTo(n1) s1.compareTo(s2) s3.compareTo(s1) s2.compareTo(s2) > 0 == 0 < 0 < 0 > 0 == 0 Scanner console = new Scanner(System.in); System.out.print("Type a name: "); String name1 = console.nextLine(); System.out.print("Type a name: "); String name2 = console.nextLine(); if (name1.compareTo(name2) < 0) { System.out.println(name1 + " goes before " + name2); } else if (name1.compareTo(name2) > 0) { System.out.println(name1 + " goes after " + name2); } else { // equal System.out.println(name1 + " is the same as " + name2); } Scanner console = new Scanner(System.in); System.out.print("Type a message to sort: "); String message = console.nextLine(); ArrayList<String> words = new ArrayList<String>(); Scanner lineScan = new Scanner(message); while (lineScan.hasNext()) { words.add(lineScan.next()); } System.out.print("Your message sorted: "); Collections.sort(words); for (String word : words) { System.out.print(word + " "); } System.out.println(); // to end the line of output 782 &KDSWHU <RX VKRXOG XVH D /LQNHG/LVW ZKHQ \RX SODQ WR GR PDQ\ DGGV DQG UHPRYHV IURP WKH IURQW RU EDFN RI WKH OLVW RU ZKHQ \RX SODQ WR PDNH PDQ\ ILOWHULQJ SDVVHV RYHU WKH OLVW LQ ZKLFK \RX UHPRYH FHUWDLQ HOHPHQWV 7KH FRGH VKRZQ ZRXOG SHUIRUP EHWWHU ZLWK DQ $UUD\/LVW EHFDXVH LW FDOOV WKH JHW PHWKRG PDQ\ WLPHV XVLQJ LQGH[HV LQ WKH PLGGOH RI WKH OLVW 7KLV LV D VORZ RSHUDWLRQ IRU D /LQNHG/LVW $Q LWHUDWRU LV DQ REMHFW WKDW UHSUHVHQWV D SRVLWLRQ ZLWKLQ D OLVW DQG WKH DELOLW\ WR YLHZ RU PDNH FKDQJHV WR WKH HOHPHQWV DW WKDW SRVLWLRQ ,WHUDWRUV DUH RIWHQ XVHG ZLWK OLQNHG OLVWV EHFDXVH WKH\ UHWDLQ WKH SRVLWLRQ LQ WKH OLVW VR WKDW ZH GRQ W KDYH WR FDOO H[SHQVLYH OLVW PHWKRGV OLNH JHW DGG RU UHPRYH PDQ\ WLPHV public static int countDuplicates(LinkedList<Integer> list) { int count = 0; Iterator<Integer> i = list.iterator(); int prev = i.next(); while (i.hasNext()) { int next = i.next(); if (prev == next) { count++; } prev = next; } return count; } public static void insertInOrder(LinkedList<String> list, String value) { int index = 0; Iterator<String> i = list.iterator(); String next = i.next(); // advance until the proper index while (i.hasNext() && next.compareTo(value) < 0) { next = i.next(); index++; } list.add(index, value); } public static void removeAll(LinkedList<Integer> list, int value) { Iterator<Integer> i = list.iterator(); while (i.hasNext()) { if (i.next() == value) { i.remove(); } } } 783 public static void wrapHalf(LinkedList<Integer> list) { int halfSize = (list.size() + 1) / 2; for (int i = 0; i < halfSize; i++) { // wrap around one element int element = list.remove(list.size() - 1); list.add(0, element); } } $Q DEVWUDFW GDWD W\SH GHILQHV WKH W\SH RI GDWD D FROOHFWLRQ FDQ KROG DQG WKH RSHUDWLRQV LW FDQ SHUIRUP RQ WKDW GDWD /LQNHG OLVWV LPSOHPHQW WKH /LVW DEVWUDFW GDWD W\SH 7KH FRXQW'XSOLFDWHV FRGH LV LGHQWLFDO WR WKH SUHFHGLQJ DQVZHU EXW WKH PHWKRG V KHDGHU VKRXOG EH FKDQJHG WR WKH IROORZLQJ public static int countDuplicates(List<Integer> list) { <RX ZRXOG XVH D 6HW UDWKHU WKDQ D /LVW LI \RX ZDQWHG WR DYRLG GXSOLFDWHV RU WR KDYH IDVW VHDUFKLQJ DELOLW\ $ 7UHH6HW VKRXOG EH XVHG ZKHQ \RX ZDQW WR NHHS WKH GDWD LQ VRUWHG QDWXUDO RUGHU $ +DVK6HW VKRXOG EH XVHG ZLWK QRQ &RPSDUDEOH W\SHV RU ZKHQ RUGHU GRHVQ W PDWWHU WR JHW WKH IDVWHVW VHDUFKLQJ WLPH ([DPLQH HYHU\ HOHPHQW RI D 6HW XVLQJ DQ ,WHUDWRU 7KH VHW FRQWDLQV > 7KH VHW FRQWDLQV > 7KH VHW FRQWDLQV > @ @ @ 7R GR D XQLRQ XVH WKH DGG$OO PHWKRG WR DGG RQH VHW V FRQWHQWV WR WKH RWKHU 7R GR DQ LQWHUVHFWLRQ XVH WKH UHWDLQ$OO PHWKRG WR UHPRYH HOHPHQWV QRW LQ FRPPRQ EHWZHHQ WKH WZR VHWV Map<String, Integer> ageMap = new TreeMap<String, Integer>(); ageMap.put("Stuart", 85); ageMap.put("Marty", 12); ageMap.put("Amanda", 25); ([DPLQH HYHU\ NH\ RI D PDS E\ FDOOLQJ WKH NH\6HW PHWKRG DQG WKHQ LWHUDWLQJ RU IRU HDFKLQJ RYHU WKDW NH\6HW ([DPLQH HYHU\ YDOXH RI D PDS E\ FDOOLQJ WKH YDOXHV PHWKRG DQG WKHQ LWHUDWLQJ RU IRU HDFKLQJ RYHU WKDW FROOHFWLRQ RI YDOXHV RU E\ ORRNLQJ XS HDFK DVVRFLDWHG YDOXH XVLQJ HDFK NH\ IURP WKH NH\6HW 7KH PDS FRQWDLQV ^ 'RQDOG` 7KH PDS FRQWDLQV ^ (LJKW\ VL[` 6WHYH 6HYHQW\ QLQH /RXDQQ 2FKR 0RVKH 2UODQGR )LIW\ (G 0RVKH 2QH7KUHH7ZR 1LQHW\ HLJKW 784 7KH IROORZLQJ PHWKRG LPSOHPHQWV WKH QHZ EHKDYLRU LQWR WKH &RXQW SURJUDP public static void reverseMap( Map<String, Integer> wordCountMap) { Map<Integer, String> reverseMap = new TreeMap<Integer, String>(); // reverse the original map for (String word : wordCountMap.keySet()) { int count = wordCountMap.get(word); if (count > OCCURRENCES) { reverseMap.put(count, word); } } // print the words sorted by count for (int count : reverseMap.keySet()) { String word = reverseMap.get(count); } } &KDSWHU 5HFXUVLRQ LV D WHFKQLTXH ZKHUH DQ DOJRULWKP LV H[SUHVVHG LQ WHUPV RI LWVHOI $ UHFXUVLYH PHWKRG GLIIHUV IURP D UHJXODU PHWKRG LQ WKDW LW FRQWDLQV D FDOO WR LWVHOI ZLWKLQ LWV ERG\ $ EDVH FDVH LV D VLWXDWLRQ ZKHUH D UHFXUVLYH PHWKRG GRHV QRW QHHG WR PDNH D UHFXUVLYH FDOO WR VROYH WKH SUREOHP $ UHFXUVLYH FDVH LV ZKHUH WKH UHFXUVLYH PHWKRG GRHV FDOO LWVHOI 5HFXUVLYH PHWKRGV QHHG ERWK FDVHV EHFDXVH WKH UHFXUVLYH FDVH LV FDOOHG UHSHDWHGO\ XQWLO WKH EDVH FDVH LV UHDFKHG VWRSSLQJ WKH FKDLQ RI UHFXUVLYH FDOOV public static void writeChars(int n) { if (n == 1) { System.out.print("*"); } else if (n == 2) { System.out.print("**"); } else { System.out.print("<"); writeChars(n - 2); System.out.print(">"); } } 785 public static void stutterReverse(String s) { if (s.length() == 0) { return s; } else { char last = s.charAt(s.length() - 1); System.out.print(last); System.out.print(last); stutterReverse(s.substring(0, s.length() - 1)); } } $ FDOO VWDFN LV WKH VWUXFWXUH RI LQIRUPDWLRQ DERXW DOO PHWKRGV WKDW KDYH FXUUHQWO\ EHHQ FDOOHG E\ \RXU SURJUDP 5HFXUVLRQ SURGXFHV D WDOO FDOO VWDFN LQ ZKLFK HDFK UHFXUVLYH FDOO LV UHSUHVHQWHG 7KH QHZ FRGH ZRXOG SULQW WKH OLQHV LQ WKHLU RULJLQDO RUGHU DQG QRW UHYHUVHG 7KH QHZ FRGH ZRXOG FDXVH LQILQLWH UHFXUVLRQ EHFDXVH HDFK UHFXUVLYH FDOO MXVW PDNHV DQRWKHU UHFXUVLYH FDOO DQG GRHVQ W SURJUHVV WRZDUG WKH EDVH FDVH 7KH VHFRQG YHUVLRQ RI WKH SRZ PHWKRG LV PRUH HIILFLHQW WKDQ WKH ILUVW EHFDXVH LW UHTXLUHV IHZHU UHFXUVLYH FDOOV %RWK YHUVLRQV DUH UHFXUVLYH public static int factorial(int n) { if (n == 0) { return 1; } else { return n * factorial(n - 1); } } 7KH EDVH FDVH LI VWDWHPHQW KDV D EXJ ,W VKRXOG WHVW IRU QXPEHUV OHVV WKDQ IROORZLQJ LV WKH FRUUHFW OLQH if (n > 10) { QRW JUHDWHU 7KH $ IUDFWDO LV DQ LPDJH WKDW LV UHFXUVLYHO\ FRQVWUXFWHG WR FRQWDLQ VPDOOHU YHUVLRQV RI LWVHOI 5HFXUVLYH PHWKRGV DUH XVHIXO ZKHQ GUDZLQJ IUDFWDO LPDJHV EHFDXVH WKH\ FDQ HOHJDQWO\ H[SUHVV WKH UHFXUVLYH QDWXUH RI WKH LPDJH 786 public static void drawHexegon(Graphics g, Point position, int size) { Polygon poly = new Polygon(); poly.addPoint(position.x, position.y + size / 2); poly.addPoint(position.x + size / 3, position.y); poly.addPoint(twoThirdX, position.y); poly.addPoint(position.x + size, position.y + size / 2); poly.addPoint(twoThirdX, position.y + size); poly.addPoint(position.x + size / 3, bottomY); g.drawPolygon(poly); } &KDSWHU <RX FDQ SHUIRUP D VHTXHQWLDO VHDUFK RYHU WKH DUUD\ XVLQJ D IRU ORRS RU \RX FDQ VRUW WKH DUUD\ XVLQJ $UUD\V VRUW DQG WKHQ SHUIRUP D ELQDU\ VHDUFK RYHU LW XVLQJ $UUD\V ELQDU\6HDUFK $ VHTXHQWLDO VHDUFK VKRXOG EH XVHG RQ DQ DUUD\ RI 3RLQW REMHFWV EHFDXVH WKH\ GR QRW LPSOHPHQW &RPSDUDEOH $UUD\V ELQDU\6HDUFK DQG &ROOHFWLRQV ELQDU\6HDUFK FDQ EH XVHG VXFFHVVIXOO\ LI WKH DUUD\ RU FROOHFWLRQ FRQWDLQV HOHPHQWV LQ D VRUWHG RUGHU HLWKHU DFFRUGLQJ WR WKHLU QDWXUDO RUGHULQJ RU WKH RUGHULQJ RI D &RPSDUDWRU 2 ORJ Q 2Q 2Q 2 2 2 2 Q Q Q ORJ % 2Q 2Q 2 Q ZKHUH Q LV WKH QXPEHU RI OLQHV RU E\WHV LQ WKH ILOH 2 7KH UXQWLPH FRPSOH[LW\ RI ERWK VHTXHQWLDO VHDUFKHV LV 2 Q %LQDU\ VHDUFK UHTXLUHV D VRUWHG GDWDVHW EHFDXVH LW XVHV WKH RUGHULQJ WR MXPS WR WKH QH[W LQGH[ ,I WKH HOHPHQWV DUH RXW RI RUGHU WKH VHDUFK LVQ W JXDUDQWHHG WR ILQG WKH WDUJHW HOHPHQW $ ELQDU\ VHDUFK RI XS HTXDOV HOHPHQWV H[DPLQHV DW PRVW HOHPHQWV EHFDXVH ORJ ZKHQ URXQGHG 7KH DOJRULWKP ZLOO H[DPLQH LQGH[ DQG UHWXUQ 7KH DOJRULWKP ZLOO H[DPLQH LQGH[HV DQG ,W ZLOO UHWXUQ 7KH DOJRULWKP ZLOO H[DPLQH LQGH[HV DQG ,W ZLOO UHWXUQ 7KH DOJRULWKP ZLOO H[DPLQH LQGH[HV DQG ,W ZLOO UHWXUQ %HFDXVH WKH LQSXW LVQ W VRUWHG WKH DOJRULWKP ZLOO H[DPLQH LQGH[HV 787 DQG ,W ZLOO UHWXUQ 7KH SDUDPHWHU DUUD\ W\SH VKRXOG EH FKDQJHG WR GRXEOH $OVR D QHZ VZDS PHWKRG ZLOO EH QHHGHG WKDW DFFHSWV D GRXEOH>@ DV WKH ILUVW SDUDPHWHU +HUH V WKH QHZ FRGH public static void selectionSort(double a) { for (int i = 0; i < a.length - 1; i++) { // find index of smallest element int smallest = i; for (int j = i + 1; j < a.length; j++) { if (a[j] < a[smallest]) { smallest = j; } } swap(a, i, smallest); } } // swap smallest to front $ PHUJH VRUW RI PHUJH RSHUDWLRQ HOHPHQWV ZLOO JHQHUDWH WLPHV WRWDO FDOOV WR PHUJH6RUW DQG ZLOO SHUIRUP WKH -DYD V VRUWLQJ PHWKRGV XVH TXLFNVRUW IRU SULPLWLYH GDWD EHFDXVH LW LV YHU\ IDVW 7KH\ XVH PHUJH VRUW IRU REMHFWV EHFDXVH LW LV D VWDEOH VRUW ZLWK ZHOO ERXQGHG ZRUVW FDVH SHUIRUPDQFH $IWHU SDVVHV RI VHOHFWLRQ VRUW ^ 7KH OHYHOV RI PHUJH VRUW {7, 2, 8, 4, 1, 11, 9, 5, 3, 10} {7, 2, 8, 4, 1}, {11, 9, 5, 3, 10} {7, 2}, {8, 4, 1}, {11, 9}, {5, 3, 10} {7, 2}, {8, 4, 1}, {11, 9}, {5, 3, 10} {7}, {2}, {8}, {4, 1}, {11}, {9}, {5}, {3, 10} {4}, {1}, {3}, {10} {2, {2, {1, {1, 7}, 7}, 2, 4, 2, 3, {8}, {1, 4}, {9, 11}, {5}, {3, 10} {1, 4, 8}, {9, 11}, {3, 5, 10} 7, 8}, {3, 5, 9, 10, 11} 4, 5, 7, 8, 9, 10, 11} ` &KDSWHU 3DFNDJH javax.swing FRQWDLQV -DYD V 6ZLQJ *8, FODVVHV 7KH VWDWHPHQW WR LPSRUW WKLV SDFNDJH LV import javax.swing.*; String response = JOptionPane.showInputDialog(null, "What's your age, cowboy?"); int age = Integer.parseInt(response); if (age < 40) { JOptionPane.showMessageDialog(null, "Only " + age + " ... still a young'n."); } else { JOptionPane.showMessageDialog(null, "You're " + age + " ... howdy, old timer!"); } 788 $ FRPSRQHQW LV DQ RQVFUHHQ LWHP VXFK DV D EXWWRQ RU WH[W ILHOG $ IUDPH LV GLIIHUHQW IURP RWKHU FRPSRQHQWV EHFDXVH LW LV D ILUVW FODVV FLWL]HQ RI WKH XVHU V RSHUDWLQJ V\VWHP )UDPHV KROG RWKHU FRPSRQHQWV LQVLGH WKHP 6RPH SURSHUWLHV RI IUDPHV DUH VL]H ORFDWLRQ DQG WLWOH 7KH IROORZLQJ FRGH FUHDWHV D IUDPH DQG VHWV WKHVH SURSHUWLHV JFrame frame = new JFrame(); frame.setSize(new Dimension(400, 300)); frame.setLocation(new Point(20, 10)); frame.setTitle("My favorite frame"); frame.setVisible(true); JColorChooser JOptionPane JComboBox JButton JRadioButton JButton b1 = new JButton("Click me"); b1.setBackground(Color.GREEN); JButton b2 = new JButton("Do not touch!"); b2.setBackground(Color.YELLOW); $ *ULG/D\RXW LV XVHG 7KH IROORZLQJ FRGH SHUIRUPV WKH OD\RXW frame.setLayout(new GridLayout(3, 2)); frame.add(b1); frame.add(b2); frame.add(b3); frame.add(b4); frame.add(b5); $ )ORZ/D\RXW LV XVHG 7KH IROORZLQJ FRGH SHUIRUPV WKH OD\RXW frame.setLayout(new FlowLayout()); frame.add(b1); frame.add(b2); frame.add(b3); frame.add(b4); frame.add(b5); $ %RUGHU/D\RXW LV XVHG 7KH IROORZLQJ FRGH SHUIRUPV WKH OD\RXW frame.setLayout(new BorderLayout()); frame.add(b1, BorderLayout.NORTH); frame.add(b2, BorderLayout.WEST); frame.add(b3, BorderLayout.CENTER); frame.add(b4, BorderLayout.EAST); frame.add(b5, BorderLayout.SOUTH); $Q HYHQW LV DQ REMHFW UHSUHVHQWLQJ D XVHU V LQWHUDFWLRQ ZLWK D JUDSKLFDO FRPSRQHQW 7KH $FWLRQ/LVWHQHU LQWHUIDFH LV XVHG WR KDQGOH HYHQWV 789 7R KDQGOH DQ HYHQW \RX PXVW ZULWH D FODVV WKDW LPSOHPHQWV WKH $FWLRQ/LVWHQHU LQWHUIDFH ,W PXVW FRQWDLQ D PHWKRG QDPHG DFWLRQ3HUIRUPHG <RX PXVW FDOO WKH DGG$FWLRQ/LVWHQHU RQ WKH FRPSRQHQW LQ TXHVWLRQ WR DWWDFK \RXU QHZ OLVWHQHU WR LW 1 2 3 4 5 6 7 8 9 import java.awt.event.*; import javax.swing.*; public class GreetingListener implements ActionListener { public void actionPerformed(ActionEvent event) { JOptionPane.showMessageDialog(null, "Greetings, Earthling!"); } } :KHQ GRLQJ ' JUDSKLFV H[WHQG WKH -3DQHO FODVV DQG ZULWH D SDLQW&RPSRQHQW PHWKRG 1 2 3 4 5 6 7 8 9 import java.awt.*; import javax.swing.*; public class RedCirclePanel extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); g.drawOval(10, 30, 50, 50); } } $ 7LPHU LV DQ REMHFW WKDW FDQ ILUH DQ $FWLRQ/LVWHQHU HYHQW DW UHJXODU LQWHUYDOV 7LPHUV FDQ EH XVHG WR DQLPDWH SDQHOV E\ KDYLQJ WKHLU $FWLRQ/LVWHQHU FKDQJH WKH VWDWH RI WKH SDQHO LQ VRPH ZD\ DQG WKHQ UHSDLQW LW 790 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 // An animated panel that draws a red and blue circle. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class RedCirclePanel2 extends JPanel { private boolean red; public RedCirclePanel2() { red = true; Timer timer = new Timer(1000, new ColorListener()); timer.start(); } public void paintComponent(Graphics g) { super.paintComponent(g); if (red) { g.setColor(Color.RED); } else { g.setColor(Color.BLUE); } g.drawOval(10, 30, 50, 50); } private class ColorListener implements ActionListener { public void actionPerformed(ActionEvent e) { red = !red; repaint(); } } } 6WXDUW 5HJHV 0DUW\ 6WHSS 791 ...
View Full Document

Ask a homework question - tutors are online