├── .gitignore ├── 01-Introduction ├── P1_01.java ├── P1_02.java ├── P1_03.java ├── P1_04.java ├── P1_05.java ├── P1_06.java ├── P1_07.java ├── P1_08.java ├── P1_09.java ├── P1_10.java ├── P1_11.java ├── P1_12.java ├── P1_13.java ├── P1_14.java ├── P1_15.java ├── P1_16.java ├── P1_17.java ├── P1_18.java ├── P1_19.java └── P1_20.java ├── 02-FundamentalDataTypes ├── P2_01.java ├── P2_02.java ├── P2_03.java ├── P2_04.java ├── P2_05.java ├── P2_06.java ├── P2_07.java ├── P2_08.java ├── P2_09.java ├── P2_10.java ├── P2_11.java ├── P2_12.java ├── P2_13.java ├── P2_14.java ├── P2_15.java ├── P2_16.java ├── P2_17.java ├── P2_18.java ├── P2_19.java ├── P2_20.java ├── P2_21.java ├── P2_22.java ├── P2_23.java ├── P2_24.java └── P2_27.java ├── 03-Decisions ├── P3_01.java ├── P3_02.java ├── P3_03.java ├── P3_04.java ├── P3_05.java ├── P3_06.java ├── P3_07.java ├── P3_08.java ├── P3_09.java ├── P3_10.java ├── P3_11.java ├── P3_12.java ├── P3_13.java ├── P3_14.java ├── P3_15.java ├── P3_16.java ├── P3_17.java ├── P3_18.java ├── P3_19.java ├── P3_20.java ├── P3_21.java ├── P3_22.java ├── P3_24.java ├── P3_25.java ├── P3_26.java ├── P3_27.java ├── P3_28.java ├── P3_29.java ├── P3_30.java ├── P3_31.java ├── P3_32.java ├── P3_33.java └── P3_34.java ├── 04-Loops ├── P4_01.java ├── P4_02A.java ├── P4_02B.java ├── P4_02C.java ├── P4_02D.java ├── P4_03.java ├── P4_04.java ├── P4_05.java ├── P4_06.java ├── P4_07.java ├── P4_08.java ├── P4_09.java ├── P4_10.java ├── P4_11.java ├── P4_12.java ├── P4_13.java ├── P4_14.java ├── P4_15.java ├── P4_16.java ├── P4_17.java ├── P4_18.java ├── P4_19.java ├── P4_20.java ├── P4_21.java ├── P4_22.java ├── P4_23.java ├── P4_25.java ├── P4_27.java ├── P4_28.java ├── P4_29.java ├── P4_30.java ├── P4_31.java └── P4_32.java ├── 05-Methods ├── P5_01.java ├── P5_02.java ├── P5_03.java ├── P5_04.java ├── P5_05.java ├── P5_06.java ├── P5_07.java ├── P5_08.java ├── P5_09.java ├── P5_10.java ├── P5_11.java ├── P5_12.java ├── P5_14.java ├── P5_15.java ├── P5_16.java ├── P5_17.java ├── P5_18.java ├── P5_19.java ├── P5_20.java ├── P5_21.java ├── P5_22.java ├── P5_23.java ├── P5_24.java ├── P5_25.java ├── P5_26.java ├── P5_27.java ├── P5_28.java └── P5_30.java ├── 06-ArraysAndArrayLists ├── P6_01.java ├── P6_02.java ├── P6_03.java ├── P6_04.java ├── P6_05.java ├── P6_06.java ├── P6_07.java ├── P6_08.java ├── P6_09.java ├── P6_10.java ├── P6_11.java ├── P6_12.java ├── P6_13.java ├── P6_14.java ├── P6_15.java ├── P6_17.java ├── P6_18.java ├── P6_19.java ├── P6_20.java ├── P6_21.java ├── P6_22.java ├── P6_23.java ├── P6_24.java ├── P6_26.java ├── P6_27.java ├── P6_28.java ├── P6_29.java ├── P6_30.java └── P6_31.java ├── 07-InputOutputAndExceptionHandling ├── P7_01.java ├── P7_02.java ├── P7_03.java ├── P7_04.java ├── P7_05.java ├── P7_06.java ├── P7_07.java ├── P7_08.java ├── P7_09.java ├── P7_13.java ├── P7_14.java └── P7_15.java ├── 08-ObjectsAndClasses ├── P8_01.java ├── P8_02.java ├── P8_03.java ├── P8_04.java ├── P8_05.java ├── P8_06.java ├── P8_07.java ├── P8_08A.java ├── P8_08B.java ├── P8_10.java ├── P8_11.java ├── P8_12.java ├── P8_13.java ├── P8_14.java ├── P8_15A.java ├── P8_15B.java └── P8_15C.java ├── 09-InheritanceAndInterfaces ├── AnyCorrectChoiceQuestion.java ├── Appointment.java ├── BankAccount.java ├── BetterRectangle.java ├── ChoiceQuestion.java ├── Daily.java ├── Employee.java ├── Executive.java ├── FillInQuestion.java ├── Filter.java ├── Instructor.java ├── LabeledPoint.java ├── Manager.java ├── Measurable.java ├── ModifiedPoint.java ├── Monthly.java ├── MultiChoiceQuestion.java ├── NumericQuestion.java ├── OneTime.java ├── Person.java ├── PersonAverage.java ├── Question.java ├── ShortWordFilter.java ├── SodaCan.java └── Student.java ├── 10-GraphicalUserInterfaces ├── BankAccountFrame.java ├── BullsEyeViewer.java ├── ButtonViewer1.java ├── ButtonViewer2.java ├── ButtonViewer3.java ├── CashRegisterFrame.java ├── ColorHouseViewer.java ├── ColorNameViewer.java ├── CurrencyConverterFrame.java ├── EarthquakeFrame.java ├── FaceViewer.java ├── FlagViewer.java ├── HelloViewer.java ├── HouseViewer.java ├── HundredButtons.java ├── NameViewer.java ├── OlympicFrame.java ├── RestaurantBillFrame.java ├── SavingsAccount.java ├── StatisticsFrame.java └── TwoSquareViewer.java ├── 11-AdvancedUserInterfaces ├── CalculatorFrame.java ├── CurrencyConversionFrame.java ├── MovableRectangleFrame.java ├── RGBCheckBoxesFrame.java ├── RGBColorFrame.java └── RGBPanelFrame.java ├── 12-ObjectOrientedDesign ├── invoice │ ├── Address.java │ ├── Invoice.java │ ├── InvoicePrinter.java │ ├── LineItem.java │ └── Product.java └── tictactoe │ ├── GameFrame.java │ ├── GameViewer.java │ ├── tic-tac-toe-o.png │ └── tic-tac-toe-x.png ├── 13-Recursion ├── eightqueens │ ├── EightQueens.java │ ├── PartialSolution.java │ └── Queen.java ├── expressions │ ├── Evaluator.java │ ├── ExpressionCalculator.java │ └── ExpressionTokenizer.java └── tasks │ ├── AreaOfPolygon.java │ ├── Finder.java │ ├── IndexOf.java │ ├── LargestElementFinder.java │ ├── Rectangle.java │ ├── Square.java │ ├── StringReverser.java │ ├── SubsetGenerator.java │ ├── SubstringGenerator.java │ └── Sum.java └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Eclipse 2 | *.pydevproject 3 | .project 4 | .metadata 5 | bin/** 6 | tmp/** 7 | tmp/**/* 8 | *.tmp 9 | *.bak 10 | *.swp 11 | *~.nib 12 | local.properties 13 | .classpath 14 | .settings/ 15 | .loadpath 16 | 17 | # Java 18 | *.class 19 | 20 | # Mobile Tools for Java (J2ME) 21 | .mtj.tmp/ 22 | 23 | # Package Files 24 | *.jar 25 | *.war 26 | *.ear 27 | 28 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 29 | hs_err_pid* 30 | /bin/ 31 | -------------------------------------------------------------------------------- /01-Introduction/P1_01.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that prints a greeting of your choice, 3 | perhaps in a language other than English. 4 | */ 5 | 6 | public class P1_01 { 7 | public static void main(String[] args){ 8 | System.out.println("Здравей!"); 9 | } 10 | } -------------------------------------------------------------------------------- /01-Introduction/P1_02.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that prints the sum of the first ten positive integers, 3 | 1 + 2 + ... + 10. 4 | */ 5 | 6 | public class P1_02 { 7 | public static void main(String[] args){ 8 | int sum = 0; 9 | 10 | for (int i = 1; i <= 10; i++) { 11 | sum += i; 12 | } 13 | 14 | System.out.println(sum); 15 | } 16 | } -------------------------------------------------------------------------------- /01-Introduction/P1_03.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that prints the product of the first ten positive integers, 3 | 1 × 2 × ... × 10. (Use * to indicate multiplication in Java.) 4 | */ 5 | 6 | public class P1_03 { 7 | public static void main(String[] args){ 8 | int product = 1; 9 | 10 | for (int i = 2; i <= 10; i++) { 11 | product *= i; 12 | } 13 | 14 | System.out.println(product); 15 | } 16 | } -------------------------------------------------------------------------------- /01-Introduction/P1_04.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that prints the balance of an account after the first, second, and 3 | third year. The account has an initial balance of $1,000 and earns 5 percent interest 4 | per year. 5 | */ 6 | 7 | public class P1_04 { 8 | public static void main(String[] args){ 9 | double balance = 1000; 10 | double percentInterestPerYear = 0.05; 11 | 12 | for(int year = 1; year <= 3; year++){ 13 | balance = balance + balance * percentInterestPerYear; 14 | System.out.printf("Year balance for %d year is %.2f \n", year, balance); 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /01-Introduction/P1_05.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that displays your name inside a box on the screen, like this: Dave 3 | Do your best to approximate lines with characters such as |- + . 4 | */ 5 | 6 | public class P1_05 { 7 | public static void main(String[] args) { 8 | System.out.println("+-------+"); 9 | System.out.println("|Stilyan|"); 10 | System.out.println("+-------+"); 11 | } 12 | } -------------------------------------------------------------------------------- /01-Introduction/P1_06.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that prints your name in large letters, such as 3 | * * ** **** **** * * 4 | * * * * * * * * * * 5 | ****** * * **** **** * * 6 | * * ****** * * * * * 7 | * * * * * * * * * 8 | */ 9 | 10 | public class P1_06 { 11 | public static void main(String[] args) { 12 | System.out.println(" *** ***** *** * * * ** ** *"); 13 | System.out.println(" ** * * * * * * * * * *"); 14 | System.out.println(" ** * * * * * * * * * *"); 15 | System.out.println(" ** * * * * * * * * *"); 16 | System.out.println(" ** * * * * ****** * * *"); 17 | System.out.println(" ** ** * * * * * * * * *"); 18 | System.out.println(" ** * *** **** * * * * **"); 19 | } 20 | 21 | } -------------------------------------------------------------------------------- /01-Introduction/P1_07.java: -------------------------------------------------------------------------------- 1 | /*Write a program that prints a face similar to (but different from) the following: 2 | ///// 3 | +"""""+ 4 | (| o o |) 5 | | ^ | 6 | | ‘-’ | 7 | +-----+ 8 | */ 9 | 10 | public class P1_07 { 11 | public static void main(String[] args) { 12 | System.out.println(" \\|||||/ "); 13 | System.out.println(" ( ~ ~ ) "); 14 | System.out.println("@( 0 0 )@"); 15 | System.out.println(" ( C )"); 16 | System.out.println(" \\ \\_/ /"); 17 | System.out.println(" |___| "); 18 | System.out.println(" |___| "); 19 | } 20 | } -------------------------------------------------------------------------------- /01-Introduction/P1_09.java: -------------------------------------------------------------------------------- 1 | /*Write a program that prints a house that looks exactly like the following: 2 | + 3 | + + 4 | + + 5 | +-----+ 6 | | .-. | 7 | | | | | 8 | +-+-+-+ 9 | */ 10 | 11 | public class P1_09 { 12 | public static void main(String[] args) { 13 | System.out.println(" +"); 14 | System.out.println(" + +"); 15 | System.out.println(" + +"); 16 | System.out.println("+-----+"); 17 | System.out.println("| .-. |"); 18 | System.out.println("| | | |"); 19 | System.out.println("+-+-+-+"); 20 | 21 | } 22 | } -------------------------------------------------------------------------------- /01-Introduction/P1_10.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that prints an animal speaking a greeting, 3 | similar to (but different from) the following: 4 | /\_/\ ----- 5 | ( ‘ ’ ) / Hello \' 6 | ( - ) < Junior | 7 | | | | \ Coder!/ 8 | (__|__) ----- 9 | */ 10 | 11 | public class P1_10 { 12 | public static void main(String[] args) { 13 | System.out.println(" _,\'| _.-''``-...___..--';)"); 14 | System.out.println(" /_ \\'. __..-' , ,--...--\'\'\'"); 15 | System.out.println("Meoow! <\\ .`--''' ` /\'"); 16 | System.out.println(" `-';' ; ; ;"); 17 | System.out.println(" __...--'' ___...--_..' .;.'"); 18 | System.out.println(" (,__....----\'\'\' (,..--\'\' "); 19 | } 20 | } -------------------------------------------------------------------------------- /01-Introduction/P1_11.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that prints three items, such as the names of your three best friends 3 | or favorite movies, on three separate lines. 4 | */ 5 | 6 | public class P1_11 { 7 | public static void main(String[] args) { 8 | System.out.println("Chair"); 9 | System.out.println("Table"); 10 | System.out.println("House"); 11 | } 12 | } -------------------------------------------------------------------------------- /01-Introduction/P1_12.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that prints a poem of your choice. If you don’t have a favorite 3 | poem, search the Internet for “Emily Dickinson” or “e e cummings”. 4 | */ 5 | 6 | public class P1_12 { 7 | public static void main(String[] args) { 8 | System.out.println("I thought I had forgotten,"); 9 | System.out.println("But it all came back again"); 10 | System.out.println("To-night with the first spring thunder"); 11 | System.out.println("In a rush of rain."); 12 | } 13 | } -------------------------------------------------------------------------------- /01-Introduction/P1_13.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that prints the United States flag, using * and = characters. 3 | */ 4 | 5 | public class P1_13 { 6 | public static void main(String[] args) { 7 | System.out.println("|* * * * * * * * * * =========================|"); 8 | System.out.println("| * * * * * * * * * =========================|"); 9 | System.out.println("| * * * * * * * * * =========================|"); 10 | System.out.println("| * * * * * * * * * =========================|"); 11 | System.out.println("| * * * * * * * * * =========================|"); 12 | System.out.println("| * * * * * * * * * =========================|"); 13 | System.out.println("|=============================================|"); 14 | System.out.println("|=============================================|"); 15 | System.out.println("|=============================================|"); 16 | System.out.println("|=============================================|"); 17 | System.out.println("|=============================================|"); 18 | System.out.println("|=============================================|"); 19 | } 20 | } -------------------------------------------------------------------------------- /01-Introduction/P1_14.java: -------------------------------------------------------------------------------- 1 | /* 2 | Type in and run the following program: 3 | Then modify the program to show the message “Hello, your name!”. 4 | */ 5 | 6 | import javax.swing.JOptionPane; 7 | 8 | public class P1_14 9 | { 10 | public static void main(String[] args) 11 | { 12 | JOptionPane.showMessageDialog(null, "Hello, Stilyan!"); 13 | } 14 | } -------------------------------------------------------------------------------- /01-Introduction/P1_15.java: -------------------------------------------------------------------------------- 1 | /* 2 | Type in and run the following program: 3 | Then modify the program to print “Hello, name!”, displaying the name that the user typed in. 4 | */ 5 | 6 | import javax.swing.JOptionPane; 7 | 8 | public class P1_15 9 | { 10 | public static void main(String[] args) 11 | { 12 | 13 | String name = JOptionPane.showInputDialog("What is your name?"); 14 | JOptionPane.showMessageDialog(null, String.format("Hello %s!", name)); 15 | } 16 | } -------------------------------------------------------------------------------- /01-Introduction/P1_16.java: -------------------------------------------------------------------------------- 1 | /* 2 | Modify the program from Exercise P1.15 so that the dialog continues with the mes- 3 | sage “My name is Hal! What would you like me to do?” Discard the user’s input and 4 | display a message such as 5 | I'm sorry, Dave. I'm afraid I can't do that. 6 | Replace Dave with the name that was provided by the user. 7 | */ 8 | 9 | import javax.swing.JOptionPane; 10 | 11 | public class P1_16 { 12 | public static void main(String[] args) { 13 | String name = JOptionPane.showInputDialog("What is your name?"); 14 | JOptionPane.showMessageDialog(null, String.format("Hello %s!", name)); 15 | JOptionPane.showInputDialog("My name is Hal! What would you like me to do?"); 16 | JOptionPane.showMessageDialog(null, String.format("I\'m sorry, %s. I'm afraid I can't do that.", name)); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /01-Introduction/P1_17.java: -------------------------------------------------------------------------------- 1 | /* 2 | Type in and run the following program: 3 | Then modify it to show a different greeting and image. 4 | */ 5 | 6 | import java.net.URL; 7 | import javax.swing.ImageIcon; 8 | import javax.swing.JOptionPane; 9 | 10 | public class P1_17 { 11 | public static void main(String[] args) throws Exception{ 12 | URL imageLocation = new URL( 13 | "http://img2.wikia.nocookie.net/__cb20130319035908/vampirediaries/images/f/fb/Sheldon_cooper_spock-41675976.jpg"); 14 | 15 | JOptionPane.showMessageDialog(null, "Bazinga!", "Title", 16 | JOptionPane.PLAIN_MESSAGE, new ImageIcon(imageLocation)); 17 | } 18 | } -------------------------------------------------------------------------------- /01-Introduction/P1_18.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that prints a two-column list of your friends’ birthdays. In the 3 | first column, print the names of your best friends; in the second column, print their 4 | birthdays. 5 | */ 6 | 7 | public class P1_18 { 8 | public static void main(String[] args) { 9 | System.out.println("|| Hristo || 07.02.1994 ||"); 10 | System.out.println("|| Joro || 22.09.1994 ||"); 11 | System.out.println("|| Tihomir || 18.12.1994 ||"); 12 | } 13 | } -------------------------------------------------------------------------------- /01-Introduction/P1_19.java: -------------------------------------------------------------------------------- 1 | /* 2 | In the United States there is no federal sales tax, so every state may impose its own 3 | sales taxes. Look on the Internet for the sales tax charged in five U.S. states, then 4 | write a program that prints the tax rate for five states of your choice. 5 | Sales Tax Rates 6 | --------------- 7 | Alaska: 0% 8 | Hawaii: 4% 9 | */ 10 | 11 | public class P1_19 { 12 | public static void main(String[] args) { 13 | System.out.println("Sales Tax Rates"); 14 | System.out.println("-------------------"); 15 | System.out.println("Alabama || 4%"); 16 | System.out.println("Idaho || 6%"); 17 | System.out.println("Vermont || 6%"); 18 | System.out.println("Oregon || 0%"); 19 | System.out.println("Montana || 0%"); 20 | } 21 | } -------------------------------------------------------------------------------- /01-Introduction/P1_20.java: -------------------------------------------------------------------------------- 1 | /* 2 | To speak more than one language is a valuable skill in the labor market today. One of 3 | the basic skills is learning to greet people. Write a program that prints a two-column 4 | list with the greeting phrases shown in the following table; in the first column, print 5 | the phrase in English, in the second column, print the phrase in a language of your 6 | choice. If you don’t speak any language other than English, use an online translator 7 | or ask a friend. 8 | */ 9 | 10 | public class P1_20 { 11 | public static void main(String[] args) { 12 | System.out.println(" List of Phrases to Translate"); 13 | System.out.println("Good Morning. || Добро утро."); 14 | System.out.println("It is pleasure to meet you. || Приятно ми е да се запознаем."); 15 | System.out.println("Please call me tommorow. || Моля, обади ми се утре."); 16 | System.out.println("Have a nice day. || Приятен ден."); 17 | } 18 | } -------------------------------------------------------------------------------- /02-FundamentalDataTypes/P2_01.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that displays the dimensions of a letter-size 3 | (8.5 × 11 inches) sheet of paper in millimeters. There are 25.4 millimeters 4 | per inch. Use con­stants and comments in your program. 5 | */ 6 | 7 | import java.util.Scanner; 8 | 9 | public class P2_01 { 10 | public static void main(String[] args) { 11 | final double MILLIMETERS_PER_INCH = 25.4; 12 | 13 | Scanner in = new Scanner(System.in); 14 | 15 | System.out.print("Enter Height: "); 16 | double heightInInches = in.nextDouble(); 17 | double heightInMillimeters = heightInInches * MILLIMETERS_PER_INCH; 18 | 19 | System.out.print("Enter Width: "); 20 | double widthInInches = in.nextDouble(); 21 | double widthInMillimeters = widthInInches * MILLIMETERS_PER_INCH; 22 | 23 | System.out.println("Dimensions of letter in millimeters are: "); 24 | System.out.printf("%.2f - Height \n", heightInMillimeters); 25 | System.out.printf("%.2f - Width \n", widthInMillimeters); 26 | 27 | in.close(); 28 | } 29 | } -------------------------------------------------------------------------------- /02-FundamentalDataTypes/P2_02.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that computes and displays 3 | the perimeter of a letter-size (8.5 × 11 inches) 4 | sheet of paper and the length of its diagonal. 5 | */ 6 | 7 | import java.util.Scanner; 8 | 9 | public class P2_02 { 10 | public static void main(String[] args) { 11 | Scanner in = new Scanner(System.in); 12 | 13 | System.out.print("Enter Height: "); 14 | double height = in.nextDouble(); 15 | 16 | System.out.print("Enter Width: "); 17 | double width = in.nextDouble(); 18 | 19 | double letterPerimeter = (height + width) * 2; 20 | double letterArea = height * width; 21 | double letterDiagonal = Math.sqrt(Math.pow(height, 2) + Math.pow(width, 2)); 22 | 23 | System.out.println("Perimeter is: " + letterPerimeter); 24 | System.out.println("Area is: " + letterArea); 25 | System.out.println("Diagonal is: " + letterDiagonal); 26 | 27 | in.close(); 28 | } 29 | } -------------------------------------------------------------------------------- /02-FundamentalDataTypes/P2_03.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that reads a number and displays 3 | the square, cube, and fourth power. Use the Math.pow method 4 | only for the fourth power. 5 | */ 6 | 7 | import java.util.Scanner; 8 | 9 | public class P2_03 { 10 | public static void main(String[] args) { 11 | Scanner in = new Scanner(System.in); 12 | 13 | System.out.print("Please enter a number: "); 14 | double number = in.nextDouble(); 15 | 16 | double square = number * number; 17 | double cube = number * number * number; 18 | double fourth = Math.pow(number, 4); 19 | 20 | System.out.println("Square of number is: " + square); 21 | System.out.println("Cube of number is: " + cube); 22 | System.out.println("Fourth of number is: " + fourth); 23 | 24 | in.close(); 25 | } 26 | } -------------------------------------------------------------------------------- /02-FundamentalDataTypes/P2_04.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that prompts the user for two integers and then prints 3 | • The sum 4 | • The difference 5 | • The product 6 | • The average 7 | • The distance (absolute value of the difference) 8 | • The maximum (the larger of the two) 9 | • The minimum (the smaller of the two) 10 | Hint: The max and min functions are declared in the Math class. 11 | */ 12 | 13 | import java.util.Scanner; 14 | 15 | public class P2_04 { 16 | public static void main(String[] args) { 17 | Scanner in = new Scanner(System.in); 18 | 19 | System.out.print("Please enter a first number: "); 20 | int first = in.nextInt(); 21 | System.out.print("Please enter a second number: "); 22 | int second = in.nextInt(); 23 | 24 | int sum = first + second; 25 | int difference = first - second; 26 | int product = first * second; 27 | int average = (first + second) / 2; 28 | int distance = Math.abs(difference); 29 | int maximum = Math.max(first, second); 30 | int minimum = Math.min(first, second); 31 | 32 | System.out.println("Sum is: " + sum); 33 | System.out.println("Difference is: " + difference); 34 | System.out.println("Product is: " + product); 35 | System.out.println("Average is: " + average); 36 | System.out.println("Distance is: " + distance); 37 | System.out.println("Maximum is: " + maximum); 38 | System.out.println("Minimum is: " + minimum); 39 | 40 | in.close(); 41 | } 42 | } -------------------------------------------------------------------------------- /02-FundamentalDataTypes/P2_05.java: -------------------------------------------------------------------------------- 1 | /* 2 | Enhance the output of Exercise P2.4 so that the numbers are properly aligned: 3 | Sum: 45 4 | Difference: -5 5 | Product: 500 6 | Average: 22.50 7 | Distance: 5 8 | Maximum: 25 9 | Minimum: 20 10 | */ 11 | 12 | import java.util.Scanner; 13 | 14 | public class P2_05 { 15 | public static void main(String[] args) { 16 | Scanner in = new Scanner(System.in); 17 | 18 | System.out.print("Please enter a first number: "); 19 | int first = in.nextInt(); 20 | 21 | System.out.print("Please enter a second number: "); 22 | int second = in.nextInt(); 23 | 24 | int sum = first + second; 25 | int difference = first - second; 26 | int product = first * second; 27 | int average = (first + second) / 2; 28 | int distance = Math.abs(difference); 29 | int maximum = Math.max(first, second); 30 | int minimum = Math.min(first, second); 31 | 32 | System.out.printf("Sum is: %5d\n", sum); 33 | System.out.printf("Difference is: %5d\n", difference); 34 | System.out.printf("Product is: %5d\n", product); 35 | System.out.printf("Average is: %5d\n", average); 36 | System.out.printf("Distance is: %5d\n", distance); 37 | System.out.printf("Maximum is: %5d\n", maximum); 38 | System.out.printf("Minimum is: %5d\n", minimum); 39 | 40 | in.close(); 41 | } 42 | } -------------------------------------------------------------------------------- /02-FundamentalDataTypes/P2_06.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that prompts the user for a measurement 3 | in meters and then con­verts it to miles, feet, and inches. 4 | */ 5 | 6 | import java.util.Scanner; 7 | 8 | public class P2_06 { 9 | public static void main(String[] args) { 10 | 11 | final double MILES_PER_METER = 0.000621371192; 12 | final double FEETS_PER_METER = 3.2808399; 13 | final double INCHES_PER_METER = 39.3700787; 14 | 15 | Scanner in = new Scanner(System.in); 16 | 17 | System.out.print("Please enter measurments in meters: "); 18 | double measurmentsInMeters = in.nextDouble(); 19 | 20 | double measurmentsInMiles = measurmentsInMeters * MILES_PER_METER; 21 | double measurmentsInFeets = measurmentsInMeters * FEETS_PER_METER; 22 | double measurmentsInInches = measurmentsInMeters * INCHES_PER_METER; 23 | 24 | System.out.printf("%.2f Meters - %.2f Miles\n", measurmentsInMeters, measurmentsInMiles); 25 | System.out.printf("%.2f Meters - %.2f Feets\n", measurmentsInMeters, measurmentsInFeets); 26 | System.out.printf("%.2f Meters - %.2f Inches\n", measurmentsInMeters, measurmentsInInches); 27 | 28 | in.close(); 29 | } 30 | } -------------------------------------------------------------------------------- /02-FundamentalDataTypes/P2_07.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that prompts the user for a radius and then prints 3 | • The area and circumference of a circle with that radius 4 | • The volume and surface area of a sphere with that radius 5 | */ 6 | 7 | import java.util.Scanner; 8 | 9 | public class P2_07 { 10 | public static void main(String[] args) { 11 | Scanner in = new Scanner(System.in); 12 | 13 | System.out.print("Please enter a radius: "); 14 | double radius = in.nextDouble(); 15 | 16 | double areaOfCircle = Math.PI * radius * radius; 17 | double circumferenceOfCircle = 2 * Math.PI * radius; 18 | double volumeOfSphere = (4 / 3) * Math.PI * Math.pow(radius, 3); 19 | double surfaceAreaOfSphere = 4 * Math.PI * radius * radius; 20 | 21 | System.out.printf("Area of circle is: %.2f\n", areaOfCircle); 22 | System.out.printf("Circumference of circle is: %.2f\n", circumferenceOfCircle); 23 | System.out.printf("Volume of sphere is: %.2f\n", volumeOfSphere); 24 | System.out.printf("Surface area of sphere is: %.2f\n", surfaceAreaOfSphere); 25 | 26 | in.close(); 27 | } 28 | } -------------------------------------------------------------------------------- /02-FundamentalDataTypes/P2_08.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that asks the user for the lengths 3 | of the sides of a rectangle. Then print 4 | • The area and perimeter of the rectangle 5 | • The length of the diagonal (use the Pythagorean theorem) 6 | */ 7 | 8 | import java.util.Scanner; 9 | 10 | public class P2_08 { 11 | public static void main(String[] args) { 12 | Scanner in = new Scanner(System.in); 13 | 14 | System.out.println("Please enter height: "); 15 | double height = in.nextDouble(); 16 | System.out.println("Please enter width: "); 17 | double width = in.nextDouble(); 18 | 19 | double area = height * width; 20 | double perimeter = (height + width) * 2; 21 | double diagonal = Math.sqrt(Math.pow(height, 2) + Math.pow(width, 2)); 22 | 23 | System.out.printf("Area of rectangle is %.2f", area); 24 | System.out.printf("Perimeter of rectangle is %.2f", perimeter); 25 | System.out.printf("Diagonal of rectangle is %.2f", diagonal); 26 | 27 | in.close(); 28 | } 29 | } -------------------------------------------------------------------------------- /02-FundamentalDataTypes/P2_09.java: -------------------------------------------------------------------------------- 1 | /* 2 | Improve the program discussed in How To 2.1 to allow input of quar­ters in addition 3 | to bills. 4 | */ 5 | 6 | import java.util.Scanner; 7 | 8 | public class P2_09 { 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | 12 | final int PENNIES_PER_DOLLAR = 100; 13 | final int PENNIES_PER_QUARTER = 25; 14 | 15 | System.out.print("Enter dollar value (1 = $1 dollar, 5 = $5 dollar, etc.): "); 16 | int dollarValue = in.nextInt(); 17 | 18 | System.out.print("Enter quarter value (1 = $0.25 dollar, 2 = $0.50 dollar, etc.): "); 19 | int quarterValue = in.nextInt(); 20 | 21 | System.out.print("Enter item price in pennies: "); 22 | int itemPrice = in.nextInt(); 23 | 24 | // Compute change due 25 | int valueInPennies = PENNIES_PER_DOLLAR * dollarValue + PENNIES_PER_QUARTER * quarterValue; 26 | int changeInPennies = valueInPennies - itemPrice; 27 | 28 | int dollarCoins = changeInPennies / PENNIES_PER_DOLLAR; 29 | changeInPennies = changeInPennies % PENNIES_PER_DOLLAR; 30 | int quarterCoins = changeInPennies / PENNIES_PER_QUARTER; 31 | 32 | System.out.printf("Dollar coins: %5d", dollarCoins); 33 | System.out.println(); 34 | System.out.printf("Quarters coins: %5d", quarterCoins); 35 | System.out.println(); 36 | 37 | in.close(); 38 | } 39 | } -------------------------------------------------------------------------------- /02-FundamentalDataTypes/P2_11.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that asks the user to input 3 | • The number of gallons of gas in the tank 4 | • The fuel efficiency in miles per gallon 5 | • The price of gas per gallon 6 | Then print the cost per 100 miles and how far the car can go with the gas in the tank. 7 | */ 8 | 9 | import java.util.Scanner; 10 | 11 | public class P2_11 { 12 | public static void main(String[] args) { 13 | Scanner in = new Scanner(System.in); 14 | 15 | final int hundredMiles = 100; 16 | 17 | System.out.print("Please enter gallons of gas in the tank: "); 18 | double gallonsOfGasInTank = in.nextDouble(); 19 | 20 | System.out.print("Please enter the fuel efficiency in miles per gallon: "); 21 | double fuelEfficiency = in.nextDouble(); 22 | 23 | System.out.print("Please enter the price of gas per gallon: "); 24 | double pricePerGallon = in.nextDouble(); 25 | 26 | double costPerHundredMiles = (hundredMiles / fuelEfficiency) * pricePerGallon; 27 | System.out.printf("The cost per 100 miles is: %.2f\n", costPerHundredMiles); 28 | 29 | double totalMiles = gallonsOfGasInTank * fuelEfficiency; 30 | System.out.printf("The miles that car can go are: %.2f\n", totalMiles); 31 | 32 | in.close(); 33 | } 34 | } -------------------------------------------------------------------------------- /02-FundamentalDataTypes/P2_12.java: -------------------------------------------------------------------------------- 1 | /* 2 | File names and extensions. Write a program that prompts the user for 3 | the drive letter ( C ), the path ( \Windows\System ), the file name ( Readme ), 4 | and the extension ( txt ). Then print the complete file name C:\Windows\System\Readme.txt. 5 | (If you use UNIX or a Macintosh, skip the drive name 6 | and use / instead of \ to separate directories.) 7 | */ 8 | 9 | import java.util.Scanner; 10 | 11 | public class P2_12 { 12 | public static void main(String[] args) { 13 | Scanner in = new Scanner(System.in); 14 | 15 | System.out.print("Please enter drive letter: "); 16 | String driveLetter = in.nextLine(); 17 | System.out.print("Please enter the path: "); 18 | String path = in.nextLine(); 19 | System.out.print("Please enter the file name: "); 20 | String filename = in.nextLine(); 21 | System.out.print("Please the extension: "); 22 | String extension = in.nextLine(); 23 | 24 | String wholeFilename = driveLetter + ":" + path + "\\" + filename + "." + extension; 25 | System.out.println("Completed filename is: " + wholeFilename); 26 | in.close(); 27 | } 28 | } -------------------------------------------------------------------------------- /02-FundamentalDataTypes/P2_13.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that reads a number between 1,000 and 999,999 from the user, 3 | where the user enters a comma in the input. Then print the number without a 4 | comma. Here is a sample dialog; the user input is in color: 5 | Please enter an integer between 1,000 and 999,999: 23,456 6 | 23456 7 | Hint: Read the input as a string. Measure the length of the string. Suppose it contains 8 | n characters. Then extract substrings consisting of the first n – 4 characters and the 9 | last three characters. 10 | */ 11 | 12 | import java.util.Scanner; 13 | 14 | public class P2_13 { 15 | public static void main(String[] args) { 16 | Scanner in = new Scanner(System.in); 17 | 18 | System.out.print("Please enter an integer between 1,000 and 999,999: "); 19 | String integer = in.nextLine(); 20 | 21 | String leftPart = integer.substring(0, integer.length() - 4); 22 | String rightPart = integer.substring(integer.length() - 3); 23 | 24 | System.out.println(leftPart + rightPart); 25 | 26 | in.close(); 27 | } 28 | } -------------------------------------------------------------------------------- /02-FundamentalDataTypes/P2_14.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that reads a number between 1,000 and 999,999 from the user and 3 | prints it with a comma separating the thousands. Here is a sample dialog; the user 4 | input is in color: 5 | Please enter an integer between 1000 and 999999: 23456 6 | 23,456 7 | */ 8 | 9 | import java.util.Scanner; 10 | 11 | public class P2_14 { 12 | public static void main(String[] args) { 13 | Scanner in = new Scanner(System.in); 14 | String integer = in.nextLine(); 15 | 16 | String leftPart = integer.substring(0, integer.length() - 3); 17 | String rightPart = integer.substring(integer.length() - 3); 18 | 19 | System.out.println(leftPart + "," + rightPart); 20 | 21 | in.close(); 22 | } 23 | } -------------------------------------------------------------------------------- /02-FundamentalDataTypes/P2_15.java: -------------------------------------------------------------------------------- 1 | /* 2 | Printing a grid. Write a program that prints the following grid to play tic-tac-toe. 3 | +--+--+--+ 4 | | | | | 5 | +--+--+--+ 6 | | | | | 7 | +--+--+--+ 8 | | | | | 9 | +--+--+--+ 10 | Of course, you could simply write seven statements of the form 11 | System.out.println("+--+--+--+"); 12 | You should do it the smart way, though. Declare string variables to hold two kinds 13 | of patterns: a comb-shaped pattern and the bottom line. Print the comb three times 14 | and the bottom line once. 15 | */ 16 | 17 | public class P2_15 { 18 | public static void main(String[] args) { 19 | String combShapedPattern = "+--+--+--+\n| | | |"; 20 | String bottomLine = "+--+--+--+"; 21 | 22 | System.out.println(combShapedPattern); 23 | System.out.println(combShapedPattern); 24 | System.out.println(combShapedPattern); 25 | System.out.println(bottomLine); 26 | } 27 | } -------------------------------------------------------------------------------- /02-FundamentalDataTypes/P2_16.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that reads in an integer and breaks it into a sequence of individual 3 | digits. For example, the input 16384 is displayed as 4 | 1 6 3 8 4 5 | You may assume that the input has no more than five digits and is not negative. 6 | */ 7 | 8 | import java.util.Scanner; 9 | 10 | public class P2_16 { 11 | public static void main(String[] args) { 12 | Scanner in = new Scanner(System.in); 13 | int number = in.nextInt(); 14 | 15 | int first = number / 10000; 16 | number = number % 10000; 17 | 18 | int second = number / 1000; 19 | number = number % 1000; 20 | 21 | int third = number / 100; 22 | number = number % 100; 23 | 24 | int fourth = number / 10; 25 | number = number % 10; 26 | 27 | int fifth = number; 28 | 29 | System.out.println(first + " " + second + " " + third + " " + fourth + " " + fifth); 30 | 31 | in.close(); 32 | } 33 | } -------------------------------------------------------------------------------- /02-FundamentalDataTypes/P2_18.java: -------------------------------------------------------------------------------- 1 | /* 2 | Writing large letters. A large letter H can be produced like this: 3 | * * 4 | * * 5 | ***** 6 | * * 7 | * * 8 | It can be declared as a string literal like this: 9 | final string LETTER_H = "* *\n* *\n*****\n* *\n* *\n"; 10 | (The \n escape sequence denotes a “newline” character that causes subsequent 11 | characters to be printed on a new line.) Do the same for the letters E , L , and O . Then 12 | write the message 13 | H 14 | E 15 | L 16 | L 17 | O 18 | in large letters. 19 | */ 20 | 21 | public class P2_18 { 22 | public static void main(String[] args) { 23 | final String letterH = "* *\n* *\n*****\n* *\n* *\n"; 24 | final String letterE = "*****\n* \n*****\n* \n*****\n"; 25 | final String letterL = "* \n* \n* \n* \n*****\n"; 26 | final String letterO = "*****\n* *\n* *\n* *\n*****\n"; 27 | 28 | System.out.println(letterH); 29 | System.out.println(letterE); 30 | System.out.println(letterL); 31 | System.out.println(letterL); 32 | System.out.println(letterO); 33 | } 34 | } -------------------------------------------------------------------------------- /02-FundamentalDataTypes/P2_19.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that transforms numbers 1 , 2 , 3 , ..., 12 3 | into the corresponding month names January , February , 4 | March , ..., December . Hint: Make a very long string "January 5 | February March ..." , in which you add spaces such that each 6 | month name has the same length. Then use sub­string to 7 | extract the month you want. 8 | */ 9 | 10 | import java.util.Scanner; 11 | 12 | public class P2_19 { 13 | public static void main(String[] args) { 14 | final int charactersInMostLongMonth = 9; 15 | 16 | Scanner in = new Scanner(System.in); 17 | int number = in.nextInt(); 18 | 19 | String months = "January February March April May June July August SeptemberOctober November December "; 20 | int leftBorder = (number - 1) * charactersInMostLongMonth; 21 | int rightBorder = (number - 1) * charactersInMostLongMonth + 9; 22 | String yourMonth = months.substring(leftBorder, rightBorder); 23 | 24 | System.out.println("Your month is: " + yourMonth); 25 | 26 | in.close(); 27 | } 28 | } -------------------------------------------------------------------------------- /02-FundamentalDataTypes/P2_20.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program that prints a ­Christmas tree: 3 | /\' 4 | / \' 5 | / \' 6 | / \' 7 | -------- 8 | " " 9 | " " 10 | " " 11 | Remember to use escape sequences. 12 | */ 13 | 14 | public class P2_20 { 15 | public static void main(String[] args) { 16 | System.out.print(" /\\' \n / \\' \n / \\' \n/ \\'\n"); 17 | System.out.println("--------"); 18 | System.out.println(" \" \" "); 19 | System.out.println(" \" \" "); 20 | System.out.println(" \" \" "); 21 | } 22 | } -------------------------------------------------------------------------------- /02-FundamentalDataTypes/P2_22.java: -------------------------------------------------------------------------------- 1 | /* 2 | The following pseudocode describes how a bookstore computes the price of an 3 | order from the total price and the number of the books that were ordered. 4 | Read the total book price and the number of books. 5 | Compute the tax (7.5 percent of the total book price). 6 | Compute the shipping charge ($2 per book). 7 | The price of the order is the sum of the total book price, the tax, and the shipping charge. 8 | Print the price of the order. 9 | Translate this pseudocode into a Java program. 10 | */ 11 | 12 | import java.util.Scanner; 13 | 14 | public class P2_22 { 15 | public static void main(String[] args) { 16 | Scanner in = new Scanner(System.in); 17 | 18 | final int SHIPPING_CHARGE_PER_BOOK = 2; 19 | 20 | double totalBookPrice = in.nextDouble(); 21 | int numberOfbooks = in.nextInt(); 22 | 23 | double tax = (totalBookPrice * 7.5) / 100; 24 | int totalShippingPrice = SHIPPING_CHARGE_PER_BOOK * numberOfbooks; 25 | 26 | double priceOfOrder = totalBookPrice + tax + totalShippingPrice; 27 | System.out.printf("Total price of order is: %.2f", priceOfOrder); 28 | 29 | in.close(); 30 | } 31 | } -------------------------------------------------------------------------------- /02-FundamentalDataTypes/P2_23.java: -------------------------------------------------------------------------------- 1 | /* 2 | The following pseudocode describes how to turn a string containing a ten-digit 3 | phone number (such as "4155551212" ) into a more readable string with parentheses 4 | and dashes, like this: "(415) 555-1212" . 5 | Take the substring consisting of the first three characters and surround it with "(" and ") ". This is the 6 | area code. 7 | Concatenate the area code, the substring consisting of the next three characters, a hyphen, and the 8 | substring consisting of the last four characters. This is the formatted number. 9 | Translate this pseudocode into a Java program that reads a telephone number into a 10 | string variable, com­putes the formatted number, and prints it. 11 | */ 12 | 13 | import java.util.Scanner; 14 | 15 | public class P2_23 { 16 | public static void main(String[] args) { 17 | Scanner in = new Scanner(System.in); 18 | 19 | String number = in.next(); 20 | 21 | String firstThree = number.substring(0, 3); 22 | String secondThree = number.substring(3, 6); 23 | String lastPart = number.substring(6); 24 | 25 | System.out.printf("Telephone number is: (%s) %s-%s", firstThree, secondThree, lastPart); 26 | 27 | in.close(); 28 | } 29 | } -------------------------------------------------------------------------------- /02-FundamentalDataTypes/P2_24.java: -------------------------------------------------------------------------------- 1 | /* 2 | The following pseudocode describes how to extract the dollars and cents from a 3 | price given as a floating-point value. For example, a price 2.95 yields values 2 and 95 4 | for the dollars and cents. 5 | Assign the price to an integer variable dollars. 6 | Multiply the difference price - dollars by 100 and add 0.5. 7 | Assign the result to an integer variable cents. 8 | */ 9 | 10 | import java.util.Scanner; 11 | 12 | public class P2_24 { 13 | public static void main(String[] args) { 14 | Scanner in = new Scanner(System.in); 15 | 16 | double price = in.nextDouble(); 17 | int dollars = (int) price; 18 | int cents = (int) ((price - dollars) * 100 + 0.5); 19 | 20 | System.out.println(dollars); 21 | System.out.println(cents); 22 | 23 | in.close(); 24 | } 25 | } -------------------------------------------------------------------------------- /02-FundamentalDataTypes/P2_27.java: -------------------------------------------------------------------------------- 1 | /* 2 | A video club wants to reward its best members with a discount based on the mem- 3 | ber’s number of movie rentals and the number of new members referred by the 4 | member. The discount is in percent and is equal to the sum of the rentals and the 5 | referrals, but it cannot exceed 75 percent. (Hint: Math.min .) Write a program Discount- 6 | Calculator to calculate the value of the discount. 7 | Here is a sample run: 8 | Enter the number of movie rentals: 56 9 | Enter the number of members referred to the video club: 3 10 | The discount is equal to: 59.00 percent. 11 | */ 12 | 13 | import java.util.Scanner; 14 | 15 | public class P2_27 { 16 | public static void main(String[] args) { 17 | Scanner in = new Scanner(System.in); 18 | 19 | System.out.print("Enter the number of movie rentals: \n"); 20 | int movieRentals = in.nextInt(); 21 | System.out.print("Enter the number of members referred to the video club: \n"); 22 | int referredMembers = in.nextInt(); 23 | 24 | int percents = Math.min(movieRentals + referredMembers, 75); 25 | System.out.printf("The discount is equal to: %d percent", percents); 26 | 27 | in.close(); 28 | } 29 | } -------------------------------------------------------------------------------- /03-Decisions/P3_01.java: -------------------------------------------------------------------------------- 1 | /*Write a program that reads an integer and prints 2 | whether it is negative, zero, or positive.*/ 3 | 4 | import java.util.Scanner; 5 | 6 | public class P3_01 { 7 | public static void main(String[] args) { 8 | Scanner in = new Scanner(System.in); 9 | 10 | int number = in.nextInt(); 11 | 12 | if (number > 0) { 13 | System.out.println("Positive number"); 14 | } 15 | else if (number < 0) { 16 | System.out.println("Negative number"); 17 | } 18 | else { 19 | System.out.println("Number is equal to zero!"); 20 | } 21 | 22 | in.close(); 23 | } 24 | } -------------------------------------------------------------------------------- /03-Decisions/P3_02.java: -------------------------------------------------------------------------------- 1 | /*Write a program that reads a floating-point number and prints “zero” if the number 2 | is zero. Otherwise, print “positive” or “negative”. Add “small” if the absolute value 3 | of the number is less than 1, or “large” if it exceeds 1,000,000.*/ 4 | 5 | import java.util.Scanner; 6 | 7 | public class P3_02 { 8 | public static void main(String[] args) { 9 | Scanner in = new Scanner(System.in); 10 | double number = in.nextDouble(); 11 | 12 | if (number > 0) { 13 | if (number < 1) { 14 | System.out.println("Positive small"); 15 | } 16 | else if (number > 1000000) { 17 | System.out.println("Positive large"); 18 | } 19 | else { 20 | System.out.println("Positive"); 21 | } 22 | } 23 | else if (number < 0) { 24 | if (Math.abs(number) < 1) { 25 | System.out.println("Negative small"); 26 | } 27 | else if (Math.abs(number) > 1000000) { 28 | System.out.println("Negative large"); 29 | } 30 | else { 31 | System.out.println("Positive"); 32 | } 33 | } 34 | else { 35 | System.out.println("Zero"); 36 | } 37 | 38 | in.close(); 39 | } 40 | } -------------------------------------------------------------------------------- /03-Decisions/P3_04.java: -------------------------------------------------------------------------------- 1 | /*Write a program that reads three numbers and prints “all the same” if they are all the 2 | same, “all different” if they are all different, and “neither” otherwise.*/ 3 | 4 | import java.util.Scanner; 5 | 6 | public class P3_04 { 7 | public static void main(String[] args) { 8 | Scanner in = new Scanner(System.in); 9 | 10 | int first = in.nextInt(); 11 | int second = in.nextInt(); 12 | int third = in.nextInt(); 13 | 14 | if (first == second && second == third) { 15 | System.out.println("all the same"); 16 | } 17 | else if (first != second && second != third && first != third) { 18 | System.out.println("all different"); 19 | } 20 | else { 21 | System.out.println("neither"); 22 | } 23 | 24 | in.close(); 25 | } 26 | } -------------------------------------------------------------------------------- /03-Decisions/P3_05.java: -------------------------------------------------------------------------------- 1 | /*Write a program that reads three numbers and prints “increasing” if they are in 2 | increasing order, “decreasing” if they are in decreasing order, and “neither” other­ 3 | wise. Here, “increasing” means “strictly increasing”, with each value larger than its 4 | pre­decessor. The sequence 3 4 4 would not be considered increasing.*/ 5 | 6 | import java.util.Scanner; 7 | 8 | public class P3_05 { 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | 12 | int first = in.nextInt(); 13 | int second = in.nextInt(); 14 | int third = in.nextInt(); 15 | 16 | if (first < second && second < third) { 17 | System.out.println("increasing"); 18 | } 19 | else if (first > second && second > third) { 20 | System.out.println("decreasing"); 21 | } 22 | else { 23 | System.out.println("neither"); 24 | } 25 | 26 | in.close(); 27 | 28 | } 29 | } -------------------------------------------------------------------------------- /03-Decisions/P3_06.java: -------------------------------------------------------------------------------- 1 | /*Repeat Exercise P3.5, but before reading the numbers, ask the user whether 2 | increas­ing/decreasing should be “strict” or “lenient”. In lenient mode, the sequence 3 4 4 is 3 | increasing and the sequence 4 4 4 is both increasing and decreasing.*/ 4 | 5 | import java.util.Scanner; 6 | 7 | public class P3_06 { 8 | public static void main(String[] args) { 9 | Scanner in = new Scanner(System.in); 10 | 11 | System.out.println("Strict or lenient? "); 12 | String input = in.next().toLowerCase(); 13 | 14 | int first = in.nextInt(); 15 | int second = in.nextInt(); 16 | int third = in.nextInt(); 17 | 18 | if (input.equals("strict")) { 19 | if (first < second && second < third) { 20 | System.out.println("increasing"); 21 | } 22 | else if (first > second && second > third) { 23 | System.out.println("decreasing"); 24 | } 25 | else { 26 | System.out.println("neither"); 27 | } 28 | } 29 | else if (input.equals("lenient")) { 30 | if ((first <= second && second < third) || (first < second && second <= third)) { 31 | System.out.println("increasing"); 32 | } 33 | else if ((first >= second && second > third) || (first > second && second >= third)) { 34 | System.out.println("decreasing"); 35 | } 36 | else if ((first == second) && (second == third)) { 37 | System.out.println("increasing and decreasing"); 38 | } 39 | else { 40 | System.out.println("neither"); 41 | } 42 | } 43 | 44 | in.close(); 45 | } 46 | } -------------------------------------------------------------------------------- /03-Decisions/P3_07.java: -------------------------------------------------------------------------------- 1 | /*Write a program that reads in three integers and prints “in order” if they are sorted in 2 | ascending or descending order, or “not in order” otherwise.*/ 3 | 4 | import java.util.Scanner; 5 | 6 | public class P3_07 { 7 | public static void main(String[] args) { 8 | Scanner in = new Scanner(System.in); 9 | 10 | int first = in.nextInt(); 11 | int second = in.nextInt(); 12 | int third = in.nextInt(); 13 | 14 | if ((first > second && second > third) || (first < second && second < third) || 15 | (first >= second && second > third) || (first <= second && second < third) || 16 | (first > second && second >= third) || (first < second && second <= third)) { 17 | System.out.println("In order"); 18 | } 19 | else { 20 | System.out.println("Not in order"); 21 | } 22 | 23 | in.close(); 24 | } 25 | } -------------------------------------------------------------------------------- /03-Decisions/P3_08.java: -------------------------------------------------------------------------------- 1 | /*Write a program that reads four integers and prints “two pairs” if the input consists 2 | of two matching pairs (in some order) and “not two pairs” otherwise. For example, 3 | 1 2 2 1 4 | 1 2 2 3 5 | 2 2 2 2 6 | two pairs 7 | not two pairs 8 | two pairs*/ 9 | 10 | import java.util.Scanner; 11 | 12 | public class P3_08 { 13 | public static void main(String[] args) { 14 | Scanner in = new Scanner(System.in); 15 | 16 | int first = in.nextInt(); 17 | int second = in.nextInt(); 18 | int third = in.nextInt(); 19 | int fourth = in.nextInt(); 20 | 21 | if ((first == second && third == fourth) || 22 | (first == third && second == fourth) || 23 | (first == fourth && second == third)) { 24 | 25 | System.out.println("Two pairs"); 26 | } 27 | else { 28 | System.out.println("Not two pairs"); 29 | } 30 | 31 | in.close(); 32 | } 33 | } -------------------------------------------------------------------------------- /03-Decisions/P3_13.java: -------------------------------------------------------------------------------- 1 | /*Write a program that translates a number between 0 and 4 into the closest letter 2 | grade. For example, the number 2.8 (which might have been the average of several 3 | grades) would be converted to B–. Break ties in favor of the better grade; for exam­ple 4 | 2.85 should be a B.*/ 5 | 6 | import java.util.Scanner; 7 | 8 | public class P3_13 { 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | double mark = in.nextDouble(); 12 | in.close(); 13 | 14 | String grade = null; 15 | 16 | if (mark < 0 || mark > 4) { 17 | System.out.println("Mark is outside the boundaries!"); 18 | return; 19 | } 20 | else if (mark >= 3.85) { 21 | grade = "A"; 22 | } 23 | else if (mark >= 3.7) { 24 | grade = "A-"; 25 | } 26 | else if (mark >= 3.0) { 27 | grade = "B+"; 28 | } 29 | else if (mark >= 2.85) { 30 | grade = "B"; 31 | } 32 | else if (mark >= 2.7) { 33 | grade = "B-"; 34 | } 35 | else if (mark >= 2.0) { 36 | grade = "C+"; 37 | } 38 | else if (mark >= 1.85) { 39 | grade = "C"; 40 | } 41 | else if (mark >= 1.7) { 42 | grade = "C-"; 43 | } 44 | else if (mark >= 1.0) { 45 | grade = "D+"; 46 | } 47 | else if (mark > 0.85) { 48 | grade = "D"; 49 | } 50 | else if (mark > 0.7) { 51 | grade = "D-"; 52 | } 53 | else { 54 | grade = "F"; 55 | } 56 | 57 | System.out.printf("Grade of student is %s", grade); 58 | 59 | in.close(); 60 | } 61 | } -------------------------------------------------------------------------------- /03-Decisions/P3_14.java: -------------------------------------------------------------------------------- 1 | /*Write a program that takes user input describing a playing card in the following 2 | shorthand notation: 3 | A 4 | 2 ... 10 5 | J 6 | Q 7 | K 8 | D 9 | H 10 | S 11 | C 12 | Ace 13 | Card values 14 | Jack 15 | Queen 16 | King 17 | Diamonds 18 | Hearts 19 | Spades 20 | Clubs 21 | Your program should print the full description of the card. For example, 22 | Enter the card notation: QS 23 | Queen of Spades*/ 24 | 25 | import java.util.Scanner; 26 | 27 | public class P3_14 { 28 | public static void main(String[] args) { 29 | Scanner input = new Scanner(System.in); 30 | String card = input.nextLine(); 31 | input.close(); 32 | 33 | char rank = card.charAt(0); 34 | char suit = card.charAt(1); 35 | 36 | String cardName = null; 37 | 38 | if (rank == 'A') { 39 | cardName += "Ace"; 40 | } 41 | else if (rank == 'J') { 42 | cardName += "Jack"; 43 | } 44 | else if (rank == 'Q') { 45 | cardName += "Queen"; 46 | } 47 | else if (rank == 'K') { 48 | cardName += "King"; 49 | } 50 | else { 51 | cardName += rank; 52 | } 53 | 54 | cardName += "of"; 55 | 56 | if (suit == 'S') { 57 | cardName += "Spades"; 58 | } 59 | else if (suit == 'D') { 60 | cardName += "Diamonds"; 61 | } 62 | else if (suit == 'H') { 63 | cardName += "Hearts"; 64 | } 65 | else if (suit == 'C') { 66 | cardName += "Clubs"; 67 | } 68 | 69 | System.out.printf("The card is: %s", cardName); 70 | } 71 | } -------------------------------------------------------------------------------- /03-Decisions/P3_15.java: -------------------------------------------------------------------------------- 1 | /*Write a program that reads in three floating-point numbers and prints the largest of 2 | the three inputs. For example: 3 | Please enter three numbers: 4 9 2.5 4 | The largest number is 9.*/ 5 | 6 | import java.util.Scanner; 7 | 8 | public class P3_15 { 9 | public static void main(String[] args) { 10 | Scanner input = new Scanner(System.in); 11 | 12 | double first = input.nextDouble(); 13 | double second = input.nextDouble(); 14 | double third = input.nextDouble(); 15 | 16 | double maximum = Math.max(first, second); 17 | 18 | if (maximum < third) { 19 | maximum = third; 20 | } 21 | 22 | System.out.printf("The largest number is %.1f", maximum); 23 | 24 | input.close(); 25 | } 26 | } -------------------------------------------------------------------------------- /03-Decisions/P3_19.java: -------------------------------------------------------------------------------- 1 | /*Write a program that reads in two floating-point numbers and tests whether they are 2 | the same up to two decimal places. Here are two sample runs. 3 | Enter two floating-point numbers: 2.0 1.99998 4 | They are the same up to two decimal places. 5 | Enter two floating-point numbers: 2.0 1.98999 6 | They are different.*/ 7 | 8 | import java.util.Scanner; 9 | 10 | public class P3_19 { 11 | public static void main(String[] args) { 12 | Scanner input = new Scanner(System.in); 13 | 14 | double first = input.nextDouble(); 15 | double second = input.nextDouble(); 16 | 17 | if (Math.abs(first - second) < 0.01) { 18 | System.out.println("They are the same!"); 19 | } 20 | else { 21 | System.out.println("They are different!"); 22 | } 23 | 24 | input.close(); 25 | } 26 | } -------------------------------------------------------------------------------- /03-Decisions/P3_21.java: -------------------------------------------------------------------------------- 1 | /*The original U.S. income tax of 1913 was quite simple. The tax was 2 | • 1 percent on the first $50,000. 3 | • 2 percent on the amount over $50,000 up to $75,000. 4 | • 3 percent on the amount over $75,000 up to $100,000. 5 | • 4 percent on the amount over $100,000 up to $250,000. 6 | • 5 percent on the amount over $250,000 up to $500,000. 7 | • 6 percent on the amount over $500,000. 8 | There was no separate schedule for single or married taxpayers. Write a program that 9 | computes the income tax according to this schedule.*/ 10 | 11 | import java.util.Scanner; 12 | 13 | public class P3_21 { 14 | public static void main(String[] args) { 15 | Scanner input = new Scanner(System.in); 16 | 17 | System.out.print("Please enter your income: "); 18 | double income = input.nextDouble(); 19 | double tax = 0; 20 | 21 | if (income > 50000) { 22 | tax = income * 0.01; 23 | } 24 | else if (income >= 50000 && income <= 75000) { 25 | tax = income * 0.02; 26 | } 27 | else if (income >= 75000 && income <= 100000) { 28 | tax = income * 0.03; 29 | } 30 | else if (income >= 100000 && income <= 250000) { 31 | tax = income * 0.04; 32 | } 33 | else if (income >= 250000 && income <= 500000) { 34 | tax = income * 0.05; 35 | } 36 | else if (income >= 500000) { 37 | tax = income * 0.06; 38 | } 39 | 40 | System.out.printf("Income tax is: %.2f", tax); 41 | 42 | input.close(); 43 | } 44 | } -------------------------------------------------------------------------------- /03-Decisions/P3_25.java: -------------------------------------------------------------------------------- 1 | /*Write a program that prompts the user to provide a single character from the alpha­ 2 | bet. Print Vowel or Consonant, depending on the user input. If the user input is 3 | not a letter (between a and z or A and Z), or is a string of length > 1, print an error 4 | message.*/ 5 | 6 | import java.util.Scanner; 7 | 8 | public class P3_25 { 9 | public static void main(String[] args) { 10 | Scanner input = new Scanner(System.in); 11 | System.out.print("Please enter single character from alphabet: "); 12 | String character = input.nextLine().toLowerCase(); 13 | input.close(); 14 | 15 | if (character.length() == 1 && Character.isLetter(character.charAt(0))) { 16 | if (character.charAt(0) == 'a' || character.charAt(0) == 'o' 17 | || character.charAt(0) == 'e' || character.charAt(0) == 'i' 18 | || character.charAt(0) == 'y' || character.charAt(0) == 'u') { 19 | System.out.println("Vowel"); 20 | } 21 | else { 22 | System.out.println("Consonant"); 23 | } 24 | } 25 | else { 26 | System.out.println("Error with string!"); 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /03-Decisions/P3_27.java: -------------------------------------------------------------------------------- 1 | /*Write a program that asks the user to enter a month (1 for January, 2 for February, 2 | and so on) and then prints the number of days in the month. For February, print “28 3 | or 29 days”. 4 | Enter a month: 5 5 | 30 days 6 | Do not use a separate if/else branch for each month. Use Boolean operators.*/ 7 | 8 | import java.util.Scanner; 9 | 10 | public class P3_27 { 11 | public static void main(String[] args) { 12 | System.out.print("Enter a month: "); 13 | Scanner input = new Scanner(System.in); 14 | int month = input.nextInt(); 15 | input.close(); 16 | 17 | if (month == 2) { 18 | System.out.println("28 or 29 days in leap year!"); 19 | } 20 | else if (month <= 7) { 21 | if (month % 2 == 1) { 22 | System.out.println("31 days"); 23 | } 24 | else { 25 | System.out.println("30 days"); 26 | } 27 | 28 | } 29 | else { 30 | if (month % 2 == 1) { 31 | System.out.println("30 days"); 32 | } 33 | else { 34 | System.out.println("31 days"); 35 | } 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /03-Decisions/P3_28.java: -------------------------------------------------------------------------------- 1 | /*A year with 366 days is called a leap year. Leap years are necessary to keep the cal­ 2 | endar synchronized with the sun because the earth revolves around the sun once 3 | every 365.25 days. Actually, that figure is not entirely precise, and for all dates after 4 | 1582 the Gregorian correction applies. Usually years that are divisible by 4 are leap 5 | years, for example 1996. However, years that are divisible by 100 (for example, 1900) 6 | are not leap years, but years that are divisible by 400 are leap years (for exam­ple, 7 | 2000). Write a program that asks the user for a year and computes whether that year 8 | is a leap year. Use a single if statement and Boolean operators.*/ 9 | 10 | import java.util.Scanner; 11 | 12 | public class P3_28 { 13 | public static void main(String[] args) { 14 | System.out.print("Please enter a year: "); 15 | Scanner input = new Scanner(System.in); 16 | int year = input.nextInt(); 17 | input.close(); 18 | 19 | if ((year % 4 == 0 || year % 400 == 0) && !(year % 100 == 0)) { 20 | System.out.println("Leap!"); 21 | } 22 | else { 23 | System.out.println("Not Leap!"); 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /03-Decisions/P3_31.java: -------------------------------------------------------------------------------- 1 | /*Write a program that reads in the name and salary of an employee. Here the salary 2 | will denote an hourly wage, such as $9.25. Then ask how many hours the employee 3 | worked in the past week. Be sure to accept fractional hours. Compute the pay. Any 4 | overtime work (over 40 hours per week) is paid at 150 percent of the regular wage. 5 | Print a paycheck for the employee.*/ 6 | 7 | import java.util.Scanner; 8 | 9 | public class P3_31 { 10 | public static void main(String[] args) { 11 | Scanner input = new Scanner(System.in); 12 | 13 | System.out.println("Employee name: "); 14 | String name = input.nextLine(); 15 | System.out.println("Employee salary: "); 16 | double salary = input.nextDouble(); 17 | System.out.println("How many hours employee work last week: "); 18 | double hours = input.nextDouble(); 19 | 20 | input.close(); 21 | 22 | double payment = 0; 23 | 24 | if (hours > 40) { 25 | payment = 1.5 * salary * (hours - 40) + 40 * salary; 26 | } 27 | else { 28 | payment = salary * hours; 29 | } 30 | 31 | System.out.printf("Pay for %s is %.2f", name, payment); 32 | } 33 | } -------------------------------------------------------------------------------- /03-Decisions/P3_33.java: -------------------------------------------------------------------------------- 1 | /*Calculating the tip when you go to a restaurant is not difficult, but your restaurant 2 | wants to suggest a tip according to the service diners receive. Write a program that 3 | calculates a tip according to the diner’s satisfaction as follows: 4 | • Ask for the diners’ satisfaction level using these ratings: 1 = Totally satisfied, 2 5 | = Satisfied, 3 = Dissatisfied. 6 | • If the diner is totally satisfied, calculate a 20 percent tip. 7 | • If the diner is satisfied, calculate a 15 percent tip. 8 | • If the diner is dissatisfied, calculate a 10 percent tip. 9 | • Report the satisfaction level and tip in dollars and cents.*/ 10 | 11 | import java.util.Scanner; 12 | 13 | public class P3_33 { 14 | public static void main(String[] args) { 15 | Scanner input = new Scanner(System.in); 16 | 17 | System.out.println("Enter dinner payment: "); 18 | double dinnerPay = input.nextDouble(); 19 | 20 | System.out.println("Enter satisfaction level(Tottaly satisfied, Satisfied, Dissatisfied): "); 21 | int satisfactionLevel = input.nextInt(); 22 | 23 | double tip = 0; 24 | 25 | if (satisfactionLevel == 1) { 26 | tip = dinnerPay * 0.2; 27 | } 28 | else if (satisfactionLevel == 2){ 29 | tip = dinnerPay * 0.15; 30 | } 31 | else if (satisfactionLevel == 3) { 32 | tip = dinnerPay * 0.1; 33 | } 34 | 35 | System.out.printf("Pay was: %.2f, tip was %.2f", dinnerPay, tip); 36 | 37 | input.close(); 38 | } 39 | } -------------------------------------------------------------------------------- /03-Decisions/P3_34.java: -------------------------------------------------------------------------------- 1 | /*A supermarket awards coupons depending on how much a customer spends on 2 | groceries. For example, if you spend $50, you will get a coupon worth eight percent 3 | of that amount. The following table shows the percent used to calculate the coupon 4 | awarded for different amounts spent. Write a program that calculates and prints the 5 | value of the coupon a person can receive based on groceries purchased. 6 | Here is a sample run: 7 | Please enter the cost of your groceries: 14 8 | You win a discount coupon of $ 1.12. (8% of your purchase)*/ 9 | 10 | import java.util.Scanner; 11 | 12 | public class P3_34 { 13 | public static void main(String[] args) { 14 | Scanner input = new Scanner(System.in); 15 | 16 | System.out.print("Please enter groceries price: "); 17 | double groceries = input.nextInt(); 18 | 19 | input.close(); 20 | 21 | double couponPrice = 0; 22 | if (groceries > 10 && groceries < 60) { 23 | couponPrice = groceries * 0.08; 24 | } 25 | else if (groceries > 60 && groceries < 150) { 26 | couponPrice = groceries * 0.1; 27 | } 28 | else if (groceries > 150 && groceries < 210) { 29 | couponPrice = groceries * 0.12; 30 | } 31 | else if (groceries > 210) { 32 | couponPrice = groceries * 0.14; 33 | } 34 | 35 | if (couponPrice > 0) { 36 | System.out.printf("You win a coupon with price of %.2f", couponPrice); 37 | } 38 | else { 39 | System.out.printf("You don't win a coupon!"); 40 | } 41 | } 42 | } -------------------------------------------------------------------------------- /04-Loops/P4_02A.java: -------------------------------------------------------------------------------- 1 | /*Write programs that read a sequence of integer inputs and print 2 | a. The smallest and largest of the inputs. 3 | b. The number of even and odd inputs. 4 | c. Cumulative totals. For example, if the input is 1 7 2 9, the program should print 1 8 10 19. 5 | d. All adjacent duplicates. For example, if the input is 1 3 3 4 5 5 6 6 6 2, the 6 | program should print 3 5 6.*/ 7 | 8 | import java.util.Scanner; 9 | 10 | public class P4_02A { 11 | public static void main(String[] args) { 12 | Scanner input = new Scanner(System.in); 13 | 14 | int largest = Integer.MIN_VALUE; 15 | int smallest = Integer.MAX_VALUE; 16 | 17 | while (input.hasNextInt()) { 18 | int newNumber = input.nextInt(); 19 | 20 | if (newNumber > largest) { 21 | largest = newNumber; 22 | } 23 | 24 | if (newNumber < smallest) { 25 | smallest = newNumber; 26 | } 27 | } 28 | 29 | System.out.printf("Largest number is: %d\n", largest); 30 | System.out.printf("Smallest number is: %d\n", smallest); 31 | 32 | input.close(); 33 | } 34 | } -------------------------------------------------------------------------------- /04-Loops/P4_02B.java: -------------------------------------------------------------------------------- 1 | /*Write programs that read a sequence of integer inputs and print 2 | a. The smallest and largest of the inputs. 3 | b. The number of even and odd inputs. 4 | c. Cumulative totals. For example, if the input is 1 7 2 9, the program should print 1 8 10 19. 5 | d. All adjacent duplicates. For example, if the input is 1 3 3 4 5 5 6 6 6 2, the 6 | program should print 3 5 6.*/ 7 | 8 | import java.util.Scanner; 9 | 10 | public class P4_02B { 11 | public static void main(String[] args) { 12 | Scanner input = new Scanner(System.in); 13 | int countOfEvenNumbers = 0; 14 | int countOfOddNumbers = 0; 15 | 16 | while (input.hasNextInt()) { 17 | int newNumber = input.nextInt(); 18 | 19 | if (newNumber % 2 == 0) { 20 | countOfEvenNumbers++; 21 | } 22 | 23 | if (newNumber % 2 == 1) { 24 | countOfOddNumbers++; 25 | } 26 | } 27 | 28 | System.out.printf("Count of even numbers is: %d\n", countOfEvenNumbers); 29 | System.out.printf("Count of odd numbers is: %d\n", countOfOddNumbers); 30 | 31 | input.close(); 32 | } 33 | } -------------------------------------------------------------------------------- /04-Loops/P4_02C.java: -------------------------------------------------------------------------------- 1 | /*Write programs that read a sequence of integer inputs and print 2 | a. The smallest and largest of the inputs. 3 | b. The number of even and odd inputs. 4 | c. Cumulative totals. For example, if the input is 1 7 2 9, the program should print 1 8 10 19. 5 | d. All adjacent duplicates. For example, if the input is 1 3 3 4 5 5 6 6 6 2, the 6 | program should print 3 5 6.*/ 7 | 8 | import java.util.Scanner; 9 | 10 | public class P4_02C { 11 | public static void main(String[] args) { 12 | Scanner input = new Scanner(System.in); 13 | 14 | String cumulativeTotals = ""; 15 | int cumulativeSum = 0; 16 | 17 | while (input.hasNextInt()) { 18 | int newNumber = input.nextInt(); 19 | 20 | cumulativeSum += newNumber; 21 | cumulativeTotals = cumulativeTotals + " " + cumulativeSum; 22 | } 23 | 24 | System.out.printf("Cumulative totals are: %s\n", cumulativeTotals); 25 | input.close(); 26 | } 27 | } -------------------------------------------------------------------------------- /04-Loops/P4_02D.java: -------------------------------------------------------------------------------- 1 | /*Write programs that read a sequence of integer inputs and print 2 | a. The smallest and largest of the inputs. 3 | b. The number of even and odd inputs. 4 | c. Cumulative totals. For example, if the input is 1 7 2 9, the program should print 1 8 10 19. 5 | d. All adjacent duplicates. For example, if the input is 1 3 3 4 5 5 6 6 6 2, the 6 | program should print 3 5 6.*/ 7 | 8 | import java.util.Scanner; 9 | 10 | public class P4_02D { 11 | public static void main(String[] args) { 12 | Scanner input = new Scanner(System.in); 13 | String adjacentDuplicates = ""; 14 | 15 | int previousNumber = input.nextInt(); 16 | boolean isMarked = false; 17 | 18 | while (input.hasNextInt()) { 19 | int newNumber = input.nextInt(); 20 | if (newNumber != previousNumber) { 21 | isMarked = false; 22 | } 23 | 24 | if (previousNumber == newNumber && !isMarked) { 25 | adjacentDuplicates = adjacentDuplicates + " " + newNumber; 26 | isMarked = true; 27 | } 28 | 29 | previousNumber = newNumber; 30 | } 31 | 32 | if (adjacentDuplicates != "") { 33 | System.out.printf("Adjacent numbers are: %s", adjacentDuplicates); 34 | } 35 | else { 36 | System.out.println("There aren't adjacent duplicates!"); 37 | } 38 | 39 | input.close(); 40 | } 41 | } -------------------------------------------------------------------------------- /04-Loops/P4_04.java: -------------------------------------------------------------------------------- 1 | /*Complete the program in How To 4.1 on page 169. Your program should read twelve 2 | temperature values and print the month with the highest temperature.*/ 3 | 4 | import java.util.Scanner; 5 | 6 | public class P4_04 { 7 | public static void main(String[] args) { 8 | Scanner input = new Scanner(System.in); 9 | double highestTemperature = input.nextDouble(); 10 | int month = 1; 11 | 12 | for (int i = 1; i < 12; i++) { 13 | double newTemparature = input.nextDouble(); 14 | if (newTemparature > highestTemperature) { 15 | highestTemperature = newTemparature; 16 | month = 1; 17 | } 18 | } 19 | 20 | System.out.printf("Month with highest temperature %.2f degrees is: %d", highestTemperature, month); 21 | 22 | input.close(); 23 | } 24 | } -------------------------------------------------------------------------------- /04-Loops/P4_05.java: -------------------------------------------------------------------------------- 1 | /*Write a program that reads a set of floating-point values. Ask the user to enter the values, then print 2 | • the average of the values. 3 | • the smallest of the values. 4 | • the largest of the values. 5 | • the range, that is the difference between the smallest and largest. 6 | Of course, you may only prompt for the values once.*/ 7 | 8 | import java.util.Scanner; 9 | 10 | public class P4_05 { 11 | public static void main(String[] args) { 12 | Scanner input = new Scanner(System.in); 13 | 14 | int smallest = Integer.MAX_VALUE; 15 | int largest = Integer.MIN_VALUE; 16 | int average = 0; 17 | int currentSum = 0; 18 | int countNumbers = 0; 19 | int range = 0; 20 | 21 | while (input.hasNextInt()) { 22 | int newInteger = input.nextInt(); 23 | 24 | if (newInteger > largest) { 25 | largest = newInteger; 26 | } 27 | 28 | if (newInteger < smallest) { 29 | smallest = newInteger; 30 | } 31 | 32 | currentSum += newInteger; 33 | countNumbers++; 34 | average = currentSum / countNumbers; 35 | 36 | range = Math.abs(smallest - largest); 37 | } 38 | 39 | System.out.printf("Smallest value is: % d\n", smallest); 40 | System.out.printf("Largest value is: % d\n", largest); 41 | System.out.printf("Average value is: % d\n", average); 42 | System.out.printf("Range between %d and %d is: %d\n", smallest, largest, range); 43 | 44 | input.close(); 45 | } 46 | } -------------------------------------------------------------------------------- /04-Loops/P4_06.java: -------------------------------------------------------------------------------- 1 | /*Translate the following pseudocode for finding the minimum value from a set of inputs into a Java program. 2 | Set a Boolean variable "first" to true. 3 | While another value has been read successfully 4 | If first is true 5 | Set the minimum to the value. 6 | Set first to false. 7 | Else if the value is less than the minimum 8 | Set the minimum to the value. 9 | Print the minimum.*/ 10 | 11 | import java.util.Scanner; 12 | 13 | public class P4_06 { 14 | public static void main(String[] args) { 15 | Scanner input = new Scanner(System.in); 16 | 17 | boolean first = true; 18 | double minimum = Double.MAX_VALUE; 19 | while (input.hasNextDouble()) { 20 | double newDouble = input.nextDouble(); 21 | if (first) { 22 | minimum = newDouble; 23 | first = false; 24 | } 25 | else if (newDouble < minimum) { 26 | minimum = newDouble; 27 | } 28 | } 29 | 30 | System.out.printf("Minimum values is %.2f", minimum); 31 | input.close(); 32 | } 33 | } -------------------------------------------------------------------------------- /04-Loops/P4_07.java: -------------------------------------------------------------------------------- 1 | /*Translate the following pseudocode for randomly permuting the characters in a string into a Java program. 2 | Read a word. 3 | Repeat word.length() times 4 | Pick a random position i in the word, but not the last position. 5 | Pick a random position j > i in the word. 6 | Swap the letters at positions j and i. 7 | Print the word. 8 | Then replace the string with 9 | first + word.charAt(j) + middle + word.charAt(i) + last*/ 10 | 11 | import java.util.Random; 12 | import java.util.Scanner; 13 | 14 | public class P4_07 { 15 | public static void main(String[] args) { 16 | Scanner input = new Scanner(System.in); 17 | String word = input.next(); 18 | input.close(); 19 | 20 | Random random = new Random(); 21 | for (int times = 0; times < word.length(); times++) { 22 | int i = random.nextInt(word.length() - 1); 23 | int j = random.nextInt(word.length() - i - 1) + i + 1; 24 | String first = word.substring(0, i); 25 | String middle = word.substring(i + 1, j); 26 | String last = word.substring(j + 1); 27 | 28 | word = first + word.charAt(i) + middle + word.charAt(j) + last; 29 | } 30 | 31 | System.out.printf("New word is: \"%s\"", word); 32 | } 33 | } -------------------------------------------------------------------------------- /04-Loops/P4_08.java: -------------------------------------------------------------------------------- 1 | /*Write a program that reads a word and prints each character of the word on a sepa­rate line. 2 | For example, if the user provides the input "Harry" , the program prints 3 | H 4 | a 5 | r 6 | r 7 | y 8 | */ 9 | 10 | import java.util.Scanner; 11 | 12 | public class P4_08 { 13 | public static void main(String[] args) { 14 | Scanner input = new Scanner(System.in); 15 | 16 | String word = input.next(); 17 | 18 | for (int i = 0; i < word.length(); i++) { 19 | System.out.println(word.charAt(i)); 20 | } 21 | 22 | input.close(); 23 | } 24 | } -------------------------------------------------------------------------------- /04-Loops/P4_09.java: -------------------------------------------------------------------------------- 1 | /*Write a program that reads a word and prints the word in reverse. For example, if the 2 | user provides the input "Harry" , the program prints 3 | yrraH 4 | */ 5 | 6 | import java.util.Scanner; 7 | 8 | public class P4_09 { 9 | public static void main(String[] args) { 10 | Scanner input = new Scanner(System.in); 11 | 12 | String word = input.next(); 13 | for (int i = word.length() - 1; i >= 0; i--) { 14 | System.out.print(word.charAt(i)); 15 | } 16 | 17 | input.close(); 18 | } 19 | } -------------------------------------------------------------------------------- /04-Loops/P4_10.java: -------------------------------------------------------------------------------- 1 | /*Write a program that reads a word and prints the number of vowels in the word. For 2 | this exercise, assume that a e i o u y are vowels. For example, if the user pro­vides the 3 | input "Harry", the program prints 2 vowels .*/ 4 | 5 | import java.util.Scanner; 6 | 7 | public class P4_10 { 8 | public static void main(String[] args) { 9 | Scanner input = new Scanner(System.in); 10 | String word = input.next(); 11 | input.close(); 12 | 13 | for (int i = 0; i < word.length(); i++) { 14 | if (word.charAt(i) == 'a' || word.charAt(i) == 'o' || word.charAt(i) == 'e'|| 15 | word.charAt(i) == 'u' || word.charAt(i) == 'i' || word.charAt(i) == 'y') { 16 | System.out.print(word.charAt(i) + " "); 17 | } 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /04-Loops/P4_11.java: -------------------------------------------------------------------------------- 1 | /*Write a program that reads a word and prints the number of syllables in the word. 2 | For this exercise, assume that syllables are determined as follows: Each sequence of 3 | adjacent vowels a e i o u y , except for the last e in a word, is a syllable. However, if 4 | that algorithm yields a count of 0, change it to 1. For example, 5 | Word Syllables 6 | Harry 2 7 | hairy 2 8 | hare 1 9 | the 1 10 | */ 11 | 12 | import java.util.Scanner; 13 | 14 | public class P4_11 { 15 | public static void main(String[] args) { 16 | Scanner input = new Scanner(System.in); 17 | System.out.print("Word: "); 18 | String word = input.next(); 19 | input.close(); 20 | 21 | int numberOfSyllables = 0; 22 | boolean isSyllable = false; 23 | for (int i = 0; i < word.length(); i++) { 24 | char currentCharacter = Character.toLowerCase(word.charAt(i)); 25 | if (currentCharacter == 'a' || currentCharacter == 'o' || 26 | currentCharacter == 'u' || currentCharacter == 'i' || 27 | currentCharacter == 'y' || 28 | (currentCharacter == 'e' && i != word.length() - 1)) { 29 | if (isSyllable) { 30 | isSyllable = false; 31 | } 32 | else { 33 | numberOfSyllables++; 34 | isSyllable = true; 35 | } 36 | } 37 | } 38 | 39 | if (numberOfSyllables == 0) { 40 | numberOfSyllables = 1; 41 | } 42 | 43 | System.out.printf("Number of syllables: %d", numberOfSyllables); 44 | } 45 | } -------------------------------------------------------------------------------- /04-Loops/P4_12.java: -------------------------------------------------------------------------------- 1 | /*Write a program that reads a word and prints all substrings, sorted by length. For 2 | example, if the user provides the input "rum" , the program prints 3 | r 4 | u 5 | m 6 | ru 7 | um 8 | rum 9 | */ 10 | 11 | import java.util.Scanner; 12 | 13 | public class P4_12 { 14 | public static void main(String[] args) { 15 | Scanner input = new Scanner(System.in); 16 | String word = input.next(); 17 | input.close(); 18 | for (int i = 0; i < word.length(); i++) { 19 | for (int j = 0; j < word.length() - i; j++) { 20 | System.out.println(word.substring(j, j + i + 1)); 21 | } 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /04-Loops/P4_13.java: -------------------------------------------------------------------------------- 1 | /*Write a program that prints all powers of 2 from 2 0 up to 2 20 .*/ 2 | 3 | public class P4_13 { 4 | public static void main(String[] args){ 5 | for (int i = 0; i <= 20; i++) { 6 | System.out.printf("Pow of 2 to %d is: %d\n",i, (int)Math.pow(2, i)); 7 | } 8 | } 9 | } -------------------------------------------------------------------------------- /04-Loops/P4_14.java: -------------------------------------------------------------------------------- 1 | /*Write a program that reads a number and prints all of its binary digits: Print the 2 | remainder number % 2 , then replace the number with number / 2 . Keep going until the 3 | number is 0. For example, if the user provides the input 13, the output should be 4 | 1 5 | 0 6 | 1 7 | 1 8 | */ 9 | 10 | import java.util.Scanner; 11 | 12 | public class P4_14 { 13 | public static void main(String[] args) { 14 | Scanner input = new Scanner(System.in); 15 | int number = input.nextInt(); 16 | input.close(); 17 | 18 | while (number > 0) { 19 | int remainder = number % 2; 20 | System.out.println(remainder); 21 | number = number / 2; 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /04-Loops/P4_15.java: -------------------------------------------------------------------------------- 1 | /*Mean and standard deviation. Write a program that reads a set of floating-point data 2 | values. Choose an appropriate mechanism for prompting for the end of the data set. 3 | When all values have been read, print out the count of the values, the aver age, and 4 | the standard deviation.*/ 5 | 6 | import java.util.Scanner; 7 | 8 | public class P4_15 { 9 | public static void main(String[] args) { 10 | Scanner input = new Scanner(System.in); 11 | System.out.print("Please enter a set of numbers: "); 12 | 13 | int countAllValues = 0; 14 | int sumAllValues = 0; 15 | double standartDeviation = 0; 16 | 17 | while (input.hasNextDouble()) { 18 | double number = input.nextDouble(); 19 | standartDeviation += (number * number); 20 | sumAllValues += number; 21 | countAllValues++; 22 | } 23 | 24 | double average = sumAllValues / countAllValues; 25 | 26 | standartDeviation = standartDeviation - (1 / countAllValues) * Math.pow(sumAllValues, 2); 27 | standartDeviation = standartDeviation / (sumAllValues - 1); 28 | standartDeviation = Math.sqrt(standartDeviation); 29 | 30 | System.out.printf("Count of all values is: %d\n", countAllValues); 31 | System.out.printf("Average of all values is: %.2f\n", average); 32 | System.out.printf("Standart deviation of all values is: %.2f\n", standartDeviation); 33 | 34 | input.close(); 35 | } 36 | } -------------------------------------------------------------------------------- /04-Loops/P4_16.java: -------------------------------------------------------------------------------- 1 | /*The Fibonacci numbers are defined by the sequence 2 | f 1 = 1 3 | f 2 = 1 4 | f n = f n − 1 + f n − 2 5 | Reformulate that as 6 | Fibonacci numbers describe the 7 | growth of a rabbit population. 8 | fold1 = 1; 9 | fold2 = 1; 10 | fnew = fold1 + fold2; 11 | After that, discard fold2 , which is no longer needed, and set fold2 to fold1 and fold1 to 12 | fnew . Repeat an appropriate number of times. 13 | Implement a program that prompts the user for an integer n and prints the nth 14 | Fibonacci number, using the above algorithm.*/ 15 | 16 | import java.util.Scanner; 17 | 18 | public class P4_16 { 19 | public static void main(String[] args) { 20 | Scanner input = new Scanner(System.in); 21 | int number = input.nextInt(); 22 | 23 | if (number > 2) { 24 | int firstNumber = 1; 25 | int secondNumber = 1; 26 | int newNumber = 0; 27 | for (int i = 0; i < number - 2; i++) { 28 | newNumber = firstNumber + secondNumber; 29 | firstNumber = secondNumber; 30 | secondNumber = newNumber; 31 | } 32 | System.out.printf("%d number is: %d", number, newNumber); 33 | } 34 | else { 35 | System.out.printf("%d number is: %d", number, 1); 36 | } 37 | 38 | input.close(); 39 | } 40 | } -------------------------------------------------------------------------------- /04-Loops/P4_17.java: -------------------------------------------------------------------------------- 1 | /*Factoring of integers. Write a program that asks the user for an integer and then 2 | prints out all its factors. For example, when the user enters 150, the program should 3 | print 4 | 2 5 | 3 6 | 5 7 | 5 8 | */ 9 | 10 | import java.util.Scanner; 11 | 12 | public class P4_17 { 13 | public static void main(String[] args) { 14 | Scanner input = new Scanner(System.in); 15 | System.out.print("Please enter a number: "); 16 | int number = input.nextInt(); 17 | input.close(); 18 | 19 | int factor = 2; 20 | while (number > 1) { 21 | if (number % factor == 0) { 22 | System.out.println(factor); 23 | number = number / factor; 24 | } 25 | else { 26 | factor++; 27 | } 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /04-Loops/P4_18.java: -------------------------------------------------------------------------------- 1 | /*Prime numbers. Write a program that prompts the user for an integer and then prints 2 | out all prime numbers up to that integer. For example, when the user enters 20, the 3 | program should print 4 | 2 5 | 3 6 | 5 7 | 7 8 | 11 9 | 13 10 | 17 11 | 19 12 | Recall that a number is a prime number if it is not divisible by any number except 1 13 | and itself.*/ 14 | 15 | import java.util.Scanner; 16 | 17 | public class P4_18 { 18 | public static void main(String[] args) { 19 | Scanner input = new Scanner(System.in); 20 | int number = input.nextInt(); 21 | input.close(); 22 | 23 | boolean isPrime = true; 24 | for (int i = 2; i <= number; i++) { 25 | int currentNumber = i; 26 | for (int j = 2; j < currentNumber; j++) { 27 | if (currentNumber % j == 0) { 28 | isPrime = false; 29 | break; 30 | } 31 | } 32 | if (isPrime) { 33 | System.out.println(currentNumber); 34 | } 35 | 36 | isPrime = true; 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /04-Loops/P4_19.java: -------------------------------------------------------------------------------- 1 | /*Write a program that prints a multiplication table, like this: 2 | 1 2 3 4 5 6 7 8 9 10 3 | 2 4 6 8 10 12 14 16 18 20 4 | 3 6 9 12 15 18 21 24 27 30 5 | . . . 6 | 10 20 30 40 50 60 70 80 90 100 7 | */ 8 | 9 | public class P4_19 { 10 | public static void main(String[] args) { 11 | for (int i = 1; i <= 10; i++) { 12 | for (int j = 1; j <= 10; j++) { 13 | System.out.printf("%3d ", i * j); 14 | } 15 | 16 | System.out.println(); 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /04-Loops/P4_20.java: -------------------------------------------------------------------------------- 1 | /*Write a program that reads an integer and displays, using asterisks, a filled and hollow square, 2 | placed next to each other. For example if the side length is 5, the program should display 3 | ***** ***** 4 | ***** * * 5 | ***** * * 6 | ***** * * 7 | ***** ***** 8 | */ 9 | 10 | import java.util.Scanner; 11 | 12 | public class P4_20 { 13 | public static void main(String[] args) { 14 | Scanner input = new Scanner(System.in); 15 | int number = input.nextInt(); 16 | input.close(); 17 | 18 | for (int i = 0; i < number; i++) { 19 | for (int j = 0; j < number * 2 + 1; j++) { 20 | if (j == number || (i > 0 && i < number - 1 && j > number + 1 && j < number * 2)) { 21 | System.out.print(" "); 22 | } 23 | else { 24 | System.out.print("*"); 25 | } 26 | } 27 | System.out.println(); 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /04-Loops/P4_21.java: -------------------------------------------------------------------------------- 1 | /*Write a program that reads an integer and displays, using asterisks, a filled diamond 2 | of the given side length. For example, if the side length is 4, the program should dis­play 3 | * 4 | *** 5 | ***** 6 | ******* 7 | ***** 8 | *** 9 | * 10 | */ 11 | 12 | import java.util.Scanner; 13 | 14 | public class P4_21 { 15 | public static void main(String[] args) { 16 | Scanner input = new Scanner(System.in); 17 | int number = input.nextInt(); 18 | input.close(); 19 | 20 | for (int i = 0; i < number - 1; i++) { 21 | for (int j = 0; j < number * 2 - 1; j++) { 22 | if ((j < number - 1 && i + j < number - 1) || (j > number - 1 && j - i >= number)) { 23 | System.out.print(" "); 24 | } 25 | else { 26 | System.out.print("*"); 27 | } 28 | } 29 | System.out.println(); 30 | } 31 | 32 | for (int i = 0; i < number * 2 - 1; i++) { 33 | System.out.print("*"); 34 | } 35 | System.out.println(); 36 | 37 | for (int i = number; i < number * 2 - 1; i++) { 38 | for (int j = 0; j < number * 2 - 1; j++) { 39 | if ((j == number - 1) || (j < number - 1 && i - j < number) || 40 | (j > number - 1 && i + j < number * 2 + (number - 2))) { 41 | System.out.print("*"); 42 | } 43 | else { 44 | System.out.print(" "); 45 | } 46 | } 47 | System.out.println(); 48 | } 49 | } 50 | } -------------------------------------------------------------------------------- /04-Loops/P4_23.java: -------------------------------------------------------------------------------- 1 | /*The Drunkard’s Walk. A drunkard in a grid of streets randomly picks one of four 2 | directions and stumbles to the next intersection, then again randomly picks one of 3 | four directions, and so on. You might think that on average the drunkard doesn’t 4 | move very far because the choices cancel each other out, but that is actually not the case. 5 | Represent locations as integer pairs (x, y). Implement the drunkard’s walk over 100 6 | intersections, starting at (0, 0), and print the ending location.*/ 7 | 8 | import java.util.Random; 9 | import java.util.Scanner; 10 | 11 | public class P4_23 { 12 | public static void main(String[] args) { 13 | Scanner input = new Scanner(System.in); 14 | Random random = new Random(); 15 | 16 | int startingX = 0; 17 | int startingY = 0; 18 | 19 | System.out.print("Please enter number of steps: "); 20 | int steps = input.nextInt(); 21 | 22 | for (int i = 0; i < steps; i++) { 23 | int direction = random.nextInt(4) + 1; 24 | if (direction == 1) { 25 | startingX += 1; 26 | } 27 | else if (direction == 2) { 28 | startingY += 1; 29 | } 30 | else if (direction == 3) { 31 | startingX -= 1; 32 | } 33 | else if (direction == 4) { 34 | startingY -= 1; 35 | } 36 | } 37 | 38 | System.out.printf("End point is: (%d, %d)", startingX, startingY); 39 | 40 | input.close(); 41 | } 42 | } -------------------------------------------------------------------------------- /04-Loops/P4_25.java: -------------------------------------------------------------------------------- 1 | /*A simple random generator is obtained by the formula 2 | r new = (a ⋅ r old + b) % m 3 | and then setting r old to r new . If m is chosen as 2 32 , then you can compute 4 | r new = a ⋅ r old + b 5 | because the truncation of an overflowing result to the int type is 6 | equivalent to computing the remainder. 7 | Write a program that asks the user to enter a seed value for r old .(Such a value is often 8 | called a seed). Then print the first 100 random integers generated by this formula, 9 | using a = 32310901 and b = 1729.*/ 10 | 11 | import java.util.Scanner; 12 | 13 | public class P4_25 { 14 | public static void main(String[] args) { 15 | final int a = 32310901; 16 | final int b = 1729; 17 | 18 | Scanner input = new Scanner(System.in); 19 | 20 | System.out.print("Please enter a seed: "); 21 | int seed = input.nextInt(); 22 | System.out.print("Please enter m: "); 23 | int m = input.nextInt(); 24 | 25 | for (int i = 0; i < 100; i++) { 26 | int newValue = (a * seed + b) % m; 27 | System.out.println(newValue); 28 | seed = newValue; 29 | } 30 | 31 | input.close(); 32 | } 33 | } -------------------------------------------------------------------------------- /04-Loops/P4_27.java: -------------------------------------------------------------------------------- 1 | /*Currency conversion. Write a program 2 | that first asks the user to type today’s 3 | price for one dollar in Japanese yen, 4 | then reads U.S. dollar values and 5 | converts each to yen. Use 0 as a sentinel.*/ 6 | 7 | import java.util.Scanner; 8 | 9 | public class P4_27 { 10 | public static void main(String[] args) { 11 | Scanner input = new Scanner(System.in); 12 | System.out.print("Please enter price for 1$ to JPY(Japanese yen): "); 13 | double priceForDollar = input.nextDouble(); 14 | 15 | System.out.print("USD dollars: "); 16 | while (input.hasNextDouble()) { 17 | double dollars = input.nextDouble(); 18 | if (dollars == 0) { 19 | break; 20 | } 21 | double yen = priceForDollar * dollars; 22 | System.out.printf("%.2f$ to JPY(Japanese yen): %.2f", dollars, yen); 23 | } 24 | 25 | input.close(); 26 | } 27 | } -------------------------------------------------------------------------------- /04-Loops/P4_28.java: -------------------------------------------------------------------------------- 1 | /*Write a program that first asks the user 2 | to type in today’s price of one dollar 3 | in Jap­anese yen, then reads U.S. dollar 4 | values and converts each to Japanese 5 | yen. Use 0 as the sentinel value to denote the end of dollar inputs. Then the program 6 | reads a sequence of yen amounts and converts them to dollars. The second sequence 7 | is ter­minated by another zero value.*/ 8 | 9 | import java.util.Scanner; 10 | 11 | public class P4_28 { 12 | public static void main(String[] args) { 13 | Scanner input = new Scanner(System.in); 14 | 15 | System.out.printf("Enter price of 1$ in JPY(Japanese yen): "); 16 | double priceOfDollar = input.nextDouble(); 17 | 18 | System.out.printf("Enter dollar value: "); 19 | while (input.hasNextDouble()) { 20 | double dollarValue = input.nextDouble(); 21 | 22 | if (dollarValue == 0) { 23 | break; 24 | } 25 | 26 | double yen = dollarValue * priceOfDollar; 27 | System.out.printf("%.2f$ in yen are: %.2f", dollarValue, yen); 28 | } 29 | 30 | System.out.printf("Enter yen value: "); 31 | while (input.hasNextDouble()) { 32 | double yenValue = input.nextDouble(); 33 | 34 | if (yenValue == 0) { 35 | break; 36 | } 37 | 38 | double dollars = yenValue / priceOfDollar; 39 | System.out.printf("%.2f yen in dollars are: %.2f", yenValue, dollars); 40 | } 41 | 42 | input.close(); 43 | } 44 | } -------------------------------------------------------------------------------- /04-Loops/P4_29.java: -------------------------------------------------------------------------------- 1 | /*Your company has shares of stock it would like to sell when their value exceeds a 2 | certain target price. Write a program that reads the target price and then reads the 3 | current stock price until it is at least the target price. Your program should use a 4 | Scanner to read a sequence of double values from standard input. Once the minimum 5 | is reached, the program should report that the stock price exceeds the target price.*/ 6 | 7 | import java.util.Scanner; 8 | 9 | public class P4_29 { 10 | public static void main(String[] args) { 11 | Scanner input = new Scanner(System.in); 12 | 13 | System.out.print("Enter target price: "); 14 | double targetPrice = input.nextDouble(); 15 | 16 | System.out.print("Enter current stock price: "); 17 | double currentStockPrice = 0; 18 | 19 | while (input.hasNextDouble()) { 20 | currentStockPrice = input.nextDouble(); 21 | if (currentStockPrice >= targetPrice) { 22 | break; 23 | } 24 | } 25 | 26 | System.out.println("Stock price exceed target price!"); 27 | System.out.printf("Stock price is: %.2f", currentStockPrice); 28 | 29 | input.close(); 30 | } 31 | } -------------------------------------------------------------------------------- /04-Loops/P4_30.java: -------------------------------------------------------------------------------- 1 | /*Write an application to pre-sell a limited number of cinema tickets. Each buyer can 2 | buy as many as 4 tickets. No more than 100 tickets can be sold. Implement a pro­gram 3 | called TicketSeller that prompts the user for the desired number of tickets and 4 | then displays the number of remaining tickets. Repeat until all tickets have been 5 | sold, and then display the total number of buyers.*/ 6 | 7 | import java.util.Scanner; 8 | 9 | public class P4_30 { 10 | public static void main(String[] args) { 11 | Scanner input = new Scanner(System.in); 12 | int numberOfTickets = 100; 13 | int buyers = 0; 14 | 15 | while (numberOfTickets > 0) { 16 | int buyerTickets = 0; 17 | do { 18 | System.out.print("Enter number of tickets you want to buy: "); 19 | buyerTickets = input.nextInt(); 20 | } 21 | while (buyerTickets > 4 || numberOfTickets - buyerTickets < 0); 22 | 23 | buyers++; 24 | 25 | numberOfTickets = numberOfTickets - buyerTickets; 26 | System.out.printf("Tickets left: %d\n", numberOfTickets); 27 | } 28 | 29 | System.out.printf("Number of buyers are: %d", buyers); 30 | input.close(); 31 | } 32 | } -------------------------------------------------------------------------------- /04-Loops/P4_31.java: -------------------------------------------------------------------------------- 1 | /*You need to control the number of people who can be in an oyster bar at the same 2 | time. Groups of people can always leave the bar, but a group cannot enter the bar 3 | if they would make the number of people in the bar exceed the maximum of 100 4 | occupants. Write a program that reads the sizes of the groups that arrive or depart. 5 | Use negative numbers for departures. After each input, display the current number 6 | of occupants. As soon as the bar holds the maximum number of people, report that 7 | the bar is full and exit the program.*/ 8 | 9 | import java.util.Scanner; 10 | 11 | public class P4_31 { 12 | public static void main(String[] args) { 13 | Scanner input = new Scanner(System.in); 14 | 15 | int maxOccupants = 100; 16 | int currentOccupants = 0; 17 | while (currentOccupants < maxOccupants) { 18 | System.out.print("Enter size of group that arrive or depart: "); 19 | int size = input.nextInt(); 20 | currentOccupants += size; 21 | System.out.printf("Current occupants are: %d\n", currentOccupants); 22 | } 23 | 24 | System.out.println("The bar is already full!"); 25 | input.close(); 26 | } 27 | } -------------------------------------------------------------------------------- /05-Methods/P5_01.java: -------------------------------------------------------------------------------- 1 | /*Write the following methods and provide a program to test them. 2 | a. double smallest(double x, double y, double z) , returning the smallest of the 3 | arguments 4 | b. double average(double x, double y, double z) , returning the average of the 5 | arguments*/ 6 | 7 | public class P5_01 { 8 | public static void main(String[] args) { 9 | System.out.println(smallest(3, 4, 5)); 10 | System.out.println(smallest(3, 3, 6)); 11 | System.out.println(average(1, 2, 3)); 12 | System.out.println(average(3, 3, 3)); 13 | } 14 | 15 | public static double smallest(double x, double y, double z) { 16 | return Math.min(Math.min(x, y), z); 17 | } 18 | 19 | public static double average(double x, double y, double z) { 20 | return (x + y + z) / 3; 21 | } 22 | } -------------------------------------------------------------------------------- /05-Methods/P5_02.java: -------------------------------------------------------------------------------- 1 | /*Write the following methods and provide a program to test them. 2 | a. boolean allTheSame(double x, double y, double z) , returning true if the arguments are all the same 3 | b. boolean allDifferent(double x, double y, double z) , returning true if the arguments are all different 4 | c. boolean sorted(double x, double y, double z) , returning true if the arguments are 5 | sorted, with the smallest one coming first*/ 6 | 7 | public class P5_02 { 8 | public static void main(String[] args) { 9 | System.out.println(allTheSame(3, 3, 3)); 10 | System.out.println(allTheSame(3, 4, 4)); 11 | System.out.println(allTheSame(3, 4, 5)); 12 | 13 | System.out.println(allDifferent(3, 4, 5)); 14 | System.out.println(allDifferent(3, 4, 4)); 15 | System.out.println(allDifferent(3, 3, 3)); 16 | 17 | System.out.println(sorted(3, 4, 5)); 18 | System.out.println(sorted(5, 4, 3)); 19 | System.out.println(sorted(4, 4, 4)); 20 | } 21 | 22 | public static boolean allTheSame(double x, double y, double z) { 23 | return x == y && y == z; 24 | } 25 | 26 | public static boolean allDifferent(double x, double y, double z) { 27 | return x != y && y != z && x != z; 28 | } 29 | 30 | public static boolean sorted(double x, double y, double z) { 31 | return x < y && y < z; 32 | } 33 | } -------------------------------------------------------------------------------- /05-Methods/P5_03.java: -------------------------------------------------------------------------------- 1 | /*Write the following methods. 2 | a. int firstDigit(int n) , returning the first digit of the argument 3 | b. int lastDigit(int n) , returning the last digit of the argument 4 | c. int digits(int n) , returning the number of digits of the argument 5 | For example, firstDigit(1729) is 1, lastDigit(1729) is 9, and digits(1729) is 4. Provide a 6 | program that tests your methods.*/ 7 | 8 | public class P5_03 { 9 | public static void main(String[] args) { 10 | System.out.println(firstDigit(101)); 11 | System.out.println(firstDigit(8801)); 12 | System.out.println(lastDigit(10)); 13 | System.out.println(lastDigit(1008)); 14 | System.out.println(digits(202020)); 15 | System.out.println(digits(2414)); 16 | } 17 | 18 | public static int firstDigit(int n) { 19 | while (n > 9) { 20 | n = n / 10; 21 | } 22 | 23 | return n; 24 | } 25 | 26 | public static int lastDigit(int n) { 27 | return n % 10; 28 | } 29 | 30 | public static int digits(int n) { 31 | int counterOfDigits = 0; 32 | 33 | while (n > 0) { 34 | n = n / 10; 35 | counterOfDigits++; 36 | } 37 | 38 | return counterOfDigits; 39 | } 40 | } -------------------------------------------------------------------------------- /05-Methods/P5_04.java: -------------------------------------------------------------------------------- 1 | /*Write a method 2 | public static String middle(String str) 3 | that returns a string containing the middle character in str if the length of str is odd, 4 | or the two middle characters if the length is even. For example, middle("middle") 5 | returns "dd" .*/ 6 | 7 | public class P5_04 { 8 | public static void main(String[] args) { 9 | System.out.println(middle("blabla")); 10 | System.out.println(middle("software")); 11 | System.out.println(middle("Informatics")); 12 | } 13 | 14 | public static String middle(String str) { 15 | if (str.length() % 2 == 0) { 16 | int last = (str.length() / 2) + 1; 17 | int first = (str.length() / 2) - 1; 18 | 19 | return str.substring(first, last); 20 | } else { 21 | int position = str.length() / 2; 22 | 23 | return str.substring(position, position + 1); 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /05-Methods/P5_05.java: -------------------------------------------------------------------------------- 1 | /*Write a method 2 | public static String repeat(String str, int n) 3 | that returns the string str repeated n times. 4 | For example, repeat("ho", 3) returns "hohoho".*/ 5 | 6 | public class P5_05 { 7 | public static void main(String[] args) { 8 | System.out.println(repeat("ho", 3)); 9 | System.out.println(repeat("mechka", 5)); 10 | } 11 | 12 | public static String repeat(String str, int n) { 13 | String newWord = ""; 14 | for (int i = 0; i < n; i++) { 15 | newWord += str; 16 | } 17 | 18 | return newWord; 19 | } 20 | } -------------------------------------------------------------------------------- /05-Methods/P5_06.java: -------------------------------------------------------------------------------- 1 | /*Write a method 2 | public static int countVowels(String str) 3 | that returns a count of all vowels in the string str. 4 | Vowels are the letters a, e, i, o, and u, and their upper­case variants.*/ 5 | 6 | public class P5_06 { 7 | public static void main(String[] args) { 8 | System.out.println(countVowels("agajgkalarE")); 9 | } 10 | 11 | public static int countVowels(String str) { 12 | int counterOfVowels = 0; 13 | 14 | for (int i = 0; i < str.length(); i++) { 15 | char currentChar = Character.toLowerCase(str.charAt(i)); 16 | 17 | if (currentChar == 'a' || currentChar == 'o' || currentChar == 'e' 18 | || currentChar == 'y' || currentChar == 'u' || currentChar == 'i') { 19 | counterOfVowels++; 20 | } 21 | } 22 | 23 | return counterOfVowels; 24 | } 25 | } -------------------------------------------------------------------------------- /05-Methods/P5_07.java: -------------------------------------------------------------------------------- 1 | /*Write a method 2 | public static int countWords(String str) 3 | that returns a count of all words in the string str . Words are separated by spaces. For 4 | example, count­Words("Mary had a little lamb") should return 5.*/ 5 | 6 | public class P5_07 { 7 | public static void main(String[] args) { 8 | System.out.println(countWords("asaf aaf faf")); 9 | System.out.println(countWords("Dog Cat Mouse Mice")); 10 | } 11 | 12 | public static int countWords(String str) { 13 | int countWords = 1; 14 | 15 | for (int i = 0; i < str.length(); i++) { 16 | if (str.charAt(i) == ' ') { 17 | countWords++; 18 | } 19 | } 20 | 21 | return countWords; 22 | } 23 | } -------------------------------------------------------------------------------- /05-Methods/P5_10.java: -------------------------------------------------------------------------------- 1 | /*Write a method 2 | public static double readDouble(String prompt) 3 | that displays the prompt string, followed by a space, reads a floating-point number 4 | in, and returns it. Here is a typical usage: 5 | salary = readDouble("Please enter your salary:"); 6 | percentageRaise = readDouble("What percentage raise would you like?");*/ 7 | 8 | import java.util.Scanner; 9 | 10 | public class P5_10 { 11 | public static void main(String[] args){ 12 | double salary = readDouble("Please enter your salary: "); 13 | double percentageRaise = readDouble("What percentage raise would you like?"); 14 | 15 | System.out.printf("Salary is: %.2f", salary); 16 | System.out.printf("Salary is: %.2f", percentageRaise); 17 | } 18 | 19 | public static double readDouble(String prompt){ 20 | System.out.println(prompt); 21 | 22 | Scanner input = new Scanner(System.in); 23 | double value = input.nextDouble(); 24 | input.close(); 25 | 26 | return value; 27 | } 28 | } -------------------------------------------------------------------------------- /05-Methods/P5_15.java: -------------------------------------------------------------------------------- 1 | /*Write a recursive method 2 | public static String reverse(String str) that computes the reverse of a string. 3 | For example, reverse("flow") should return "wolf" . Hint: Reverse the substring 4 | starting at the second character, then add the first character at the end. For example, 5 | to reverse "flow" , first reverse "low" to "wol" , then add the "f" at the end.*/ 6 | 7 | import java.util.Scanner; 8 | 9 | public class P5_15 { 10 | public static void main(String[] args) { 11 | Scanner input = new Scanner(System.in); 12 | System.out.print("Please enter word to reverse: "); 13 | String word = input.next(); 14 | System.out.println(reverse(word)); 15 | input.close(); 16 | } 17 | 18 | public static String reverse(String str) { 19 | if (str.length() > 1) { 20 | return reverse(str.substring(1)) + str.charAt(0); 21 | } 22 | return str; 23 | } 24 | } -------------------------------------------------------------------------------- /05-Methods/P5_16.java: -------------------------------------------------------------------------------- 1 | /*Write a recursive method 2 | public static boolean isPalindrome(String str) 3 | that returns true if str is a palindrome, that is, a word that is the same when reversed. 4 | Examples of palin­drome are “deed”, “rotor”, or “aibohphobia”. Hint: A word is a 5 | palindrome if the first and last letters match and the remainder is also a palindrome.*/ 6 | 7 | import java.util.Scanner; 8 | 9 | public class P5_16 { 10 | public static void main(String[] args) { 11 | Scanner input = new Scanner(System.in); 12 | System.out.println("Please enter word: "); 13 | String word = input.next(); 14 | System.out.println(isPalindrome(word)); 15 | input.close(); 16 | } 17 | 18 | public static boolean isPalindrome(String str) { 19 | if (str.charAt(0) != str.charAt(str.length() - 1)) { 20 | return false; 21 | } else if (str.length() <= 2) { 22 | return true; 23 | } else { 24 | return isPalindrome(str.substring(1, str.length() - 1)); 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /05-Methods/P5_17.java: -------------------------------------------------------------------------------- 1 | /*Use recursion to implement a method 2 | public static boolean find(String str, String match) 3 | that tests whether match is contained in str : 4 | boolean b = find("Mississippi", "sip"); // Sets b to true 5 | Hint: If str starts with match , then you are done. If not, consider the string that you 6 | obtain by removing the first character.*/ 7 | 8 | public class P5_17 { 9 | public static void main(String[] args) { 10 | System.out.println(find("Mississippi", "sip")); 11 | System.out.println(find("Donau", "ue")); 12 | } 13 | 14 | public static boolean find(String str, String match) { 15 | if (str.length() < match.length()) { 16 | return false; 17 | } else if (str.substring(0, match.length()).equals(match)) { 18 | return true; 19 | } else { 20 | return find(str.substring(1), match); 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /05-Methods/P5_18.java: -------------------------------------------------------------------------------- 1 | /*Use recursion to determine the number of digits in an integer n . Hint: If n is < 10, it 2 | has one digit. Otherwise, it has one more digit than n / 10 .*/ 3 | 4 | import java.util.Scanner; 5 | 6 | public class P5_18 { 7 | public static void main(String[] args) { 8 | Scanner input = new Scanner(System.in); 9 | System.out.print("Please enter a number: "); 10 | int number = input.nextInt(); 11 | System.out.println(numberOfDigits(number)); 12 | input.close(); 13 | } 14 | 15 | public static int numberOfDigits(int number) { 16 | if (number >= 10) { 17 | return numberOfDigits(number / 10) + 1; 18 | } else { 19 | return 1; 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /05-Methods/P5_19.java: -------------------------------------------------------------------------------- 1 | /*Use recursion to compute a n , where n is a positive integer. Hint: If n is 1, then 2 | n = a. If n is even, then a n = (a n/2 ) 2 . Otherwise, a n = a × a n–1 .*/ 3 | 4 | import java.util.Scanner; 5 | 6 | public class P5_19 { 7 | public static void main(String[] args) { 8 | Scanner input = new Scanner(System.in); 9 | System.out.println("Please enter a: "); 10 | int a = input.nextInt(); 11 | System.out.println("Please enter n: "); 12 | int n = input.nextInt(); 13 | input.close(); 14 | 15 | System.out.println(compute(a, n)); 16 | } 17 | 18 | public static int compute(int a, int n) { 19 | if (n == 1) { 20 | return a; 21 | } else if (n % 2 == 0) { 22 | return compute(a, n / 2) * compute(a, n / 2); 23 | } else { 24 | return a * compute(a, n - 1); 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /05-Methods/P5_20.java: -------------------------------------------------------------------------------- 1 | /*Leap years. Write a method 2 | public static boolean isLeapYear(int year) 3 | that tests whether a year is a leap year: that is, a year with 366 days. Exercise P3.28 4 | describes how to test whether a year is a leap year. In this exercise, use multiple if 5 | statements and return statements to return the result as soon as you know it.*/ 6 | 7 | import java.util.Scanner; 8 | 9 | public class P5_20 { 10 | public static void main(String[] args) { 11 | Scanner input = new Scanner(System.in); 12 | System.out.print("Please enter a year: "); 13 | int year = input.nextInt(); 14 | System.out.println(isLeapYear(year)); 15 | input.close(); 16 | } 17 | 18 | public static boolean isLeapYear(int year) { 19 | if (year % 100 == 0) { 20 | return false; 21 | } 22 | 23 | if (!(year % 4 == 0 || year % 400 == 0)) { 24 | return false; 25 | } 26 | 27 | return true; 28 | } 29 | } -------------------------------------------------------------------------------- /05-Methods/P5_22.java: -------------------------------------------------------------------------------- 1 | /*Write a method that computes the balance of a bank account with a given initial balance 2 | and interest rate, after a given number of years. Assume interest is com­pounded yearly.*/ 3 | 4 | import java.util.Scanner; 5 | 6 | public class P5_22 { 7 | public static void main(String[] args) { 8 | Scanner input = new Scanner(System.in); 9 | System.out.print("Please enter initial balance: "); 10 | double initialBalance = input.nextDouble(); 11 | System.out.print("Please enter interest rate: "); 12 | double interestRate = input.nextDouble(); 13 | System.out.print("Please enter years: "); 14 | int years = input.nextInt(); 15 | input.close(); 16 | 17 | System.out.printf("Balance is: %.2f", balance(initialBalance, interestRate, years)); 18 | } 19 | 20 | public static double balance(double initialBalance, double interestRate, int years) { 21 | double interest = initialBalance * (interestRate / 100.0); 22 | double balance = initialBalance + interest; 23 | 24 | while (years > 0) { 25 | balance += interest; 26 | interest = balance * (interestRate / 100.0); 27 | years--; 28 | } 29 | 30 | return balance; 31 | } 32 | } -------------------------------------------------------------------------------- /05-Methods/P5_28.java: -------------------------------------------------------------------------------- 1 | /*A non-governmental organization needs a program to calculate the amount of financial 2 | assistance for needy families. The formula is as follows: 3 | • If the annual household income is between $30,000 and $40,000 and the 4 | household has at least three children, the amount is $1,000 per child. 5 | • If the annual household income is between $20,000 and $30,000 and the 6 | household has at least two children, the amount is $1,500 per child. 7 | • If the annual household income is less than $20,000, the amount is $2,000 per child. 8 | Implement a method for this computation. Write a program that asks for the house- 9 | hold income and number of children for each applicant, printing the amount 10 | returned by your method. Use –1 as a sentinel value for the input.*/ 11 | 12 | import java.util.Scanner; 13 | 14 | public class P5_28 { 15 | public static void main(String[] args) { 16 | Scanner input = new Scanner(System.in); 17 | System.out.print("Please enter your income: "); 18 | int income = input.nextInt(); 19 | System.out.print("Please enter number of your children: "); 20 | int numberOfChildren = input.nextInt(); 21 | input.close(); 22 | 23 | int amount = amountOfAssistance(income, numberOfChildren); 24 | System.out.printf("Amount of assistance is: %d", amount); 25 | } 26 | 27 | public static int amountOfAssistance(double income, int numberOfChildren) { 28 | if (income > 30000 && income <= 40000) { 29 | return numberOfChildren * 1000; 30 | } else if (income > 20000 & income <= 30000) { 31 | return numberOfChildren * 1500; 32 | } else { 33 | return numberOfChildren * 2000; 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /06-ArraysAndArrayLists/P6_03.java: -------------------------------------------------------------------------------- 1 | /*Modify the LargestInArray.java program in Section 6.3 to mark both the smallest and 2 | the largest elements.*/ 3 | 4 | import java.util.Scanner; 5 | 6 | public class P6_03 { 7 | public static void main(String[] args) { 8 | Scanner input = new Scanner(System.in); 9 | int[] array = new int[10]; 10 | for (int i = 0; i < array.length; i++) { 11 | System.out.printf("%d element of array: ", i + 1); 12 | array[i] = input.nextInt(); 13 | } 14 | input.close(); 15 | 16 | int largest = largestElement(array); 17 | System.out.printf("Largest element in array is: %d\n", largest); 18 | 19 | int smallest = smallestElement(array); 20 | System.out.printf("Smallest element in array is: %d\n", smallest); 21 | } 22 | 23 | public static int largestElement(int[] array) { 24 | int largest = array[0]; 25 | for (int i = 1; i < array.length; i++) { 26 | if (array[i] > largest) { 27 | largest = array[i]; 28 | } 29 | } 30 | 31 | return largest; 32 | } 33 | 34 | public static int smallestElement(int[] array) { 35 | int smallest = array[0]; 36 | for (int i = 1; i < array.length; i++) { 37 | if (array[i] < smallest) { 38 | smallest = array[i]; 39 | } 40 | } 41 | 42 | return smallest; 43 | } 44 | } -------------------------------------------------------------------------------- /06-ArraysAndArrayLists/P6_04.java: -------------------------------------------------------------------------------- 1 | /*Write a method sumWithoutSmallest that computes the sum of an array of values, 2 | except for the smallest one, in a single loop. In the loop, update the sum and the 3 | smallest value. After the loop, return the difference.*/ 4 | 5 | import java.util.Scanner; 6 | 7 | public class P6_04 { 8 | public static void main(String[] args) { 9 | Scanner input = new Scanner(System.in); 10 | int[] array = new int[10]; 11 | for (int i = 0; i < array.length; i++) { 12 | System.out.printf("%d element of array: ", i + 1); 13 | array[i] = input.nextInt(); 14 | } 15 | input.close(); 16 | 17 | int sum = sumWithoutSmallest(array); 18 | System.out.printf("Sum without smallest one is: %d\n", sum); 19 | } 20 | 21 | public static int sumWithoutSmallest(int[] array) { 22 | int smallestValue = array[0]; 23 | int sum = smallestValue; 24 | 25 | for (int i = 1; i < array.length; i++) { 26 | if (array[i] < smallestValue) { 27 | smallestValue = array[i]; 28 | } 29 | sum += array[i]; 30 | } 31 | 32 | return sum - smallestValue; 33 | } 34 | } -------------------------------------------------------------------------------- /06-ArraysAndArrayLists/P6_05.java: -------------------------------------------------------------------------------- 1 | /*Write a method public static void removeMin that removes the minimum value from a 2 | partially filled array without calling other methods.*/ 3 | 4 | import java.util.Arrays; 5 | import java.util.Scanner; 6 | 7 | public class P6_05 { 8 | public static void main(String[] args) { 9 | Scanner input = new Scanner(System.in); 10 | int[] array = new int[10]; 11 | for (int i = 0; i < array.length; i++) { 12 | System.out.printf("%d element of array: ", i + 1); 13 | array[i] = input.nextInt(); 14 | } 15 | input.close(); 16 | 17 | int[] newArray = removeMin(array); 18 | System.out.printf("New array is: %s\n", Arrays.toString(newArray)); 19 | 20 | } 21 | 22 | public static int[] removeMin(int[] array) { 23 | int minIndex = 0; 24 | int[] newArray = new int[array.length - 1]; 25 | 26 | for (int i = 1; i < array.length; i++) { 27 | if (array[i] < array[minIndex]) { 28 | minIndex = i; 29 | } 30 | } 31 | 32 | for (int i = 0; i < minIndex; i++) { 33 | newArray[i] = array[i]; 34 | } 35 | 36 | for (int i = minIndex + 1; i < array.length; i++) { 37 | newArray[i - 1] = array[i]; 38 | } 39 | 40 | return newArray; 41 | } 42 | } -------------------------------------------------------------------------------- /06-ArraysAndArrayLists/P6_06.java: -------------------------------------------------------------------------------- 1 | /*Compute the alternating sum of all elements in an array. For example, if your pro­gram 2 | reads the input then it computes 3 | 1 4 9 16 9 7 4 9 11 4 | 1 – 4 + 9 – 16 + 9 – 7 + 4 – 9 + 11 = –2*/ 5 | 6 | import java.util.Scanner; 7 | 8 | public class P6_06 { 9 | public static void main(String[] args) { 10 | Scanner input = new Scanner(System.in); 11 | int[] array = new int[10]; 12 | for (int i = 0; i < array.length; i++) { 13 | System.out.printf("%d element of array: ", i + 1); 14 | array[i] = input.nextInt(); 15 | } 16 | input.close(); 17 | 18 | int sum = alternatingSum(array); 19 | System.out.printf("Alternating sum is: %d\n", sum); 20 | } 21 | 22 | public static int alternatingSum(int[] array) { 23 | int sum = 0; 24 | 25 | for (int i = 0; i < array.length; i++) { 26 | if (i % 2 == 0) { 27 | sum += array[i]; 28 | } else if (i % 2 != 0) { 29 | sum += -array[i]; 30 | } 31 | } 32 | 33 | return sum; 34 | } 35 | } -------------------------------------------------------------------------------- /06-ArraysAndArrayLists/P6_07.java: -------------------------------------------------------------------------------- 1 | /*Write a method that reverses the sequence of elements in an array. For example, if 2 | you call the method with the array 3 | 1 4 9 16 9 7 4 9 11 4 | then the array is changed to 5 | 11 9 4 7 9 16 9 4 1*/ 6 | 7 | import java.util.Arrays; 8 | import java.util.Scanner; 9 | 10 | public class P6_07 { 11 | public static void main(String[] args) { 12 | Scanner input = new Scanner(System.in); 13 | int[] array = new int[10]; 14 | for (int i = 0; i < array.length; i++) { 15 | System.out.printf("%d element of array: ", i + 1); 16 | array[i] = input.nextInt(); 17 | } 18 | input.close(); 19 | 20 | reverse(array); 21 | System.out.printf("Reversed array: %s", Arrays.toString(array)); 22 | } 23 | 24 | public static void reverse(int[] array) { 25 | int middleIndex = (array.length) / 2; 26 | 27 | for (int i = 0; i < middleIndex; i++) { 28 | int temporaryVariable = array[i]; 29 | array[i] = array[array.length - 1 - i]; 30 | array[array.length - 1 - i] = temporaryVariable; 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /06-ArraysAndArrayLists/P6_08.java: -------------------------------------------------------------------------------- 1 | /*Write a method that implements the algorithm developed in Section 6.6.*/ 2 | 3 | import java.util.Arrays; 4 | import java.util.Scanner; 5 | 6 | public class P6_08 { 7 | public static void main(String[] args) { 8 | Scanner input = new Scanner(System.in); 9 | int[] array = new int[10]; 10 | for (int i = 0; i < array.length; i++) { 11 | System.out.printf("%d element of array: ", i + 1); 12 | array[i] = input.nextInt(); 13 | } 14 | input.close(); 15 | 16 | swapElements(array); 17 | System.out.printf("Swapped elements of array: %s\n", Arrays.toString(array)); 18 | } 19 | 20 | public static void swapElements(int[] array) { 21 | int i = 0; 22 | int j = array.length / 2; 23 | 24 | while (i < array.length / 2) { 25 | int temporaryVariable = array[i]; 26 | array[i] = array[j]; 27 | array[j] = temporaryVariable; 28 | 29 | i += 1; 30 | j += 1; 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /06-ArraysAndArrayLists/P6_09.java: -------------------------------------------------------------------------------- 1 | /*Write a method 2 | public static boolean equals(int[] a, int[] b) 3 | that checks whether two arrays have the same elements in the same order.*/ 4 | 5 | import java.util.Scanner; 6 | 7 | public class P6_09 { 8 | public static void main(String[] args) { 9 | Scanner input = new Scanner(System.in); 10 | 11 | int[] firstArray = new int[10]; 12 | for (int i = 0; i < firstArray.length; i++) { 13 | System.out.printf("%d element of array: ", i + 1); 14 | firstArray[i] = input.nextInt(); 15 | } 16 | 17 | int[] secondArray = new int[10]; 18 | for (int i = 0; i < secondArray.length; i++) { 19 | System.out.printf("%d element of array: ", i + 1); 20 | secondArray[i] = input.nextInt(); 21 | } 22 | 23 | boolean isEqual = equals(firstArray, secondArray); 24 | if (isEqual) { 25 | System.out.println("Arrays are equal!"); 26 | } else { 27 | System.out.println("Arrays are not equal!"); 28 | } 29 | 30 | input.close(); 31 | } 32 | 33 | public static boolean equals(int[] a, int[] b) { 34 | for (int i = 0; i < a.length; i++) { 35 | if (a[i] != b[i]) { 36 | return false; 37 | } 38 | } 39 | 40 | return true; 41 | } 42 | } -------------------------------------------------------------------------------- /06-ArraysAndArrayLists/P6_10.java: -------------------------------------------------------------------------------- 1 | /*Write a method 2 | public static boolean sameSet(int[] a, int[] b) 3 | that checks whether two arrays have the same elements in some order, ignoring 4 | duplicates. For example, the two arrays 5 | 1 4 9 16 9 7 4 9 11 6 | and 7 | 11 11 7 9 16 4 1 8 | would be considered identical. You will probably need one or more helper methods.*/ 9 | 10 | import java.util.Scanner; 11 | 12 | public class P6_10 { 13 | public static void main(String[] args) { 14 | Scanner input = new Scanner(System.in); 15 | 16 | int[] firstArray = new int[5]; 17 | for (int i = 0; i < firstArray.length; i++) { 18 | System.out.printf("%d element of array: ", i + 1); 19 | firstArray[i] = input.nextInt(); 20 | } 21 | 22 | int[] secondArray = new int[5]; 23 | for (int i = 0; i < secondArray.length; i++) { 24 | System.out.printf("%d element of array: ", i + 1); 25 | secondArray[i] = input.nextInt(); 26 | } 27 | 28 | input.close(); 29 | 30 | boolean isSameSets = sameSet(firstArray, secondArray); 31 | System.out.printf("Is sets same? %s", isSameSets); 32 | } 33 | 34 | public static boolean sameSet(int[] a, int[] b) { 35 | boolean isSameNumbers = false; 36 | for (int i = 0; i < a.length; i++) { 37 | for (int j = 0; j < b.length; j++) { 38 | if (a[i] == b[j]) { 39 | isSameNumbers = true; 40 | } 41 | } 42 | 43 | if (!isSameNumbers) { 44 | return false; 45 | } 46 | } 47 | 48 | return true; 49 | } 50 | } -------------------------------------------------------------------------------- /06-ArraysAndArrayLists/P6_14.java: -------------------------------------------------------------------------------- 1 | /*Write a program that generates a sequence of 20 random values between 0 and 99 in 2 | an array, prints the sequence, sorts it, and prints the sorted sequence. Use the sort 3 | method from the standard Java library.*/ 4 | 5 | import java.util.Arrays; 6 | import java.util.Random; 7 | 8 | public class P6_14 { 9 | public static void main(String[] args) { 10 | Random random = new Random(); 11 | 12 | int[] values = new int[20]; 13 | for (int i = 0; i < values.length; i++) { 14 | values[i] = random.nextInt(100); 15 | } 16 | 17 | System.out.print("Initial values: "); 18 | printSequence(values); 19 | 20 | sortSequence(values); 21 | 22 | System.out.print("After sorting values: "); 23 | printSequence(values); 24 | } 25 | 26 | public static void printSequence(int[] array) { 27 | for (int i = 0; i < array.length; i++) { 28 | System.out.print(array[i] + " "); 29 | } 30 | 31 | System.out.println(); 32 | } 33 | 34 | public static void sortSequence(int[] array) { 35 | Arrays.sort(array); 36 | } 37 | } -------------------------------------------------------------------------------- /06-ArraysAndArrayLists/P6_21.java: -------------------------------------------------------------------------------- 1 | /*Write a program that reads a sequence of input values and displays a bar chart of the 2 | values, using asterisks, like this: 3 | ********************** 4 | **************************************** 5 | **************************** 6 | ************************** 7 | ************** 8 | You may assume that all values are positive. First figure out the maximum value. 9 | That value’s bar should be drawn with 40 asterisks. Shorter bars should use 10 | proportionally fewer asterisks.*/ 11 | 12 | import java.util.Scanner; 13 | 14 | public class P6_21 { 15 | public static void main(String[] args) { 16 | Scanner input = new Scanner(System.in); 17 | 18 | System.out.print("Please enter length of sequence: "); 19 | int lengthOfSequence = input.nextInt(); 20 | int[] array = new int[lengthOfSequence]; 21 | for (int i = 0; i < array.length; i++) { 22 | System.out.print("Please enter number: "); 23 | array[i] = input.nextInt(); 24 | } 25 | 26 | input.close(); 27 | 28 | printAsterisks(array); 29 | } 30 | 31 | public static void printAsterisks(int[] array) { 32 | for (int i = 0; i < array.length; i++) { 33 | if (array[i] >= 40) { 34 | System.out.println("****************************************"); 35 | } else { 36 | for (int j = 0; j < array[i]; j++) { 37 | System.out.print("*"); 38 | } 39 | 40 | System.out.println(); 41 | } 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /06-ArraysAndArrayLists/P6_22.java: -------------------------------------------------------------------------------- 1 | /*Improve the program of Exercise P6.21 to work correctly when the data set contains 2 | nega­tive values.*/ 3 | 4 | import java.util.Scanner; 5 | 6 | public class P6_22 { 7 | public static void main(String[] args) { 8 | Scanner input = new Scanner(System.in); 9 | 10 | System.out.print("Please enter length of sequence: "); 11 | int lengthOfSequence = input.nextInt(); 12 | int[] array = new int[lengthOfSequence]; 13 | for (int i = 0; i < array.length; i++) { 14 | System.out.print("Please enter number: "); 15 | array[i] = input.nextInt(); 16 | 17 | if (array[i] < 0) { 18 | array[i] = -array[i]; 19 | } 20 | } 21 | 22 | input.close(); 23 | 24 | printAsterisks(array); 25 | } 26 | 27 | public static void printAsterisks(int[] array) { 28 | for (int i = 0; i < array.length; i++) { 29 | if (array[i] >= 40) { 30 | System.out.println("****************************************"); 31 | } else { 32 | for (int j = 0; j < array[i]; j++) { 33 | System.out.print("*"); 34 | } 35 | 36 | System.out.println(); 37 | } 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /06-ArraysAndArrayLists/P6_23.java: -------------------------------------------------------------------------------- 1 | /*Improve the program of Exercise P6.21 by adding captions for each bar. Prompt the 2 | user for the captions and data values. The output should look like this: 3 | Egypt ********************** 4 | France **************************************** 5 | Japan **************************** 6 | Uruguay ************************** 7 | Switzerland ************** 8 | */ 9 | 10 | import java.util.Scanner; 11 | 12 | public class P6_23 { 13 | public static void main(String[] args) { 14 | Scanner input = new Scanner(System.in); 15 | 16 | System.out.print("Please enter length of sequence: "); 17 | int lengthOfSequence = input.nextInt(); 18 | 19 | int[] numbers = new int[lengthOfSequence]; 20 | String[] captions = new String[lengthOfSequence]; 21 | for (int i = 0; i < lengthOfSequence; i++) { 22 | System.out.print("Please enter caption: "); 23 | captions[i] = input.next(); 24 | System.out.print("Please enter number: "); 25 | numbers[i] = input.nextInt(); 26 | 27 | if (numbers[i] < 0) { 28 | numbers[i] = -numbers[i]; 29 | } 30 | } 31 | 32 | printElements(lengthOfSequence, captions, numbers); 33 | input.close(); 34 | } 35 | 36 | public static void printElements(int length, String[] names, int[] numbers) { 37 | for (int i = 0; i < length; i++) { 38 | System.out.printf("%10s ", names[i]); 39 | 40 | for (int j = 0; j < numbers[i]; j++) { 41 | System.out.print("*"); 42 | } 43 | 44 | System.out.println(); 45 | } 46 | } 47 | } -------------------------------------------------------------------------------- /07-InputOutputAndExceptionHandling/P7_01.java: -------------------------------------------------------------------------------- 1 | /*Write a program that carries out the following tasks: 2 | Open a file with the name hello.txt. 3 | Store the message “Hello, World!” in the file. 4 | Close the file. 5 | Open the same file again. 6 | Read the message into a string variable and print it.*/ 7 | 8 | import java.io.File; 9 | import java.io.FileNotFoundException; 10 | import java.io.PrintWriter; 11 | import java.util.Scanner; 12 | 13 | public class P7_01 { 14 | public static void main(String[] args) { 15 | writeInFile(); 16 | String content = readFromFile("hello.txt"); 17 | 18 | System.out.println(content); 19 | } 20 | 21 | public static String readFromFile(String filename) { 22 | File file = new File(filename); 23 | String content = null; 24 | 25 | try (Scanner input = new Scanner(file)) { 26 | content = input.nextLine(); 27 | } catch (FileNotFoundException e) { 28 | System.out.println("File not found!"); 29 | } 30 | 31 | return content; 32 | 33 | } 34 | 35 | public static void writeInFile() { 36 | File file = new File("hello.txt"); 37 | 38 | try (PrintWriter out = new PrintWriter(file)) { 39 | out.write("Hello, World!"); 40 | } catch (FileNotFoundException e) { 41 | System.out.println("File not found!"); 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /07-InputOutputAndExceptionHandling/P7_03.java: -------------------------------------------------------------------------------- 1 | /*Repeat Exercise P7.2, but allow the user to specify the file name on the command- 2 | line. If the user doesn’t specify any file name, then prompt the user for the name.*/ 3 | 4 | import java.io.File; 5 | import java.io.FileNotFoundException; 6 | import java.io.PrintWriter; 7 | import java.util.Scanner; 8 | 9 | public class P7_03 { 10 | public static void main(String[] args) { 11 | File fileReading = new File(args[0]); 12 | Scanner in = null; 13 | File fileWriting = new File(args[1]); 14 | PrintWriter out = null; 15 | 16 | try { 17 | in = new Scanner(fileReading); 18 | out = new PrintWriter(fileWriting); 19 | } catch (FileNotFoundException e1) { 20 | System.out.println("Files are not founded!"); 21 | } 22 | 23 | int lineNumber = 1; 24 | while (in.hasNextLine()) { 25 | String line = in.nextLine(); 26 | out.write(String.format("/* %d */ %s\n", lineNumber, line)); 27 | lineNumber++; 28 | } 29 | 30 | out.close(); 31 | in.close(); 32 | 33 | System.out.println("File was read and written!"); 34 | } 35 | } -------------------------------------------------------------------------------- /07-InputOutputAndExceptionHandling/P7_04.java: -------------------------------------------------------------------------------- 1 | /*Write a program that reads a file containing two columns of floating-point ­numbers. 2 | Prompt the user for the file name. Print the average of each column.*/ 3 | 4 | import java.io.File; 5 | import java.io.FileNotFoundException; 6 | import java.util.Scanner; 7 | 8 | public class P7_04 { 9 | public static void main(String[] args) { 10 | Scanner input = new Scanner(System.in); 11 | System.out.print("Please enter file name: "); 12 | String fileName = input.next(); 13 | input.close(); 14 | 15 | File file = new File(fileName); 16 | Scanner in = null; 17 | 18 | try { 19 | in = new Scanner(file); 20 | } catch (FileNotFoundException e) { 21 | System.out.println("File doesn't exist!"); 22 | } 23 | 24 | double firstColumnSum = 0; 25 | double secondColumnSum = 0; 26 | int allRows = 0; 27 | while (in.hasNextLine()) { 28 | String[] row = in.nextLine().split("\\s+"); 29 | firstColumnSum += Double.parseDouble(row[0]); 30 | secondColumnSum += Double.parseDouble(row[1]); 31 | allRows++; 32 | } 33 | 34 | in.close(); 35 | 36 | System.out.printf("First column sum is: %.2f\n", firstColumnSum / allRows); 37 | System.out.printf("Second column sum is: %.2f\n", secondColumnSum / allRows); 38 | } 39 | } -------------------------------------------------------------------------------- /07-InputOutputAndExceptionHandling/P7_05.java: -------------------------------------------------------------------------------- 1 | /*Write a program that asks the user for a file name and prints the number of charac­ters, 2 | words, and lines in that file.*/ 3 | 4 | import java.io.File; 5 | import java.io.FileNotFoundException; 6 | import java.util.Scanner; 7 | 8 | public class P7_05 { 9 | public static void main(String[] args) { 10 | Scanner input = new Scanner(System.in); 11 | System.out.print("Please enter file name: "); 12 | String fileName = input.next(); 13 | input.close(); 14 | 15 | File file = new File(fileName); 16 | Scanner in = null; 17 | 18 | try { 19 | in = new Scanner(file); 20 | } catch (FileNotFoundException e) { 21 | System.out.println("File was not found!"); 22 | } 23 | 24 | int numberOfLines = 0; 25 | int numberOfWords = 0; 26 | int numberOfCharacters = 0; 27 | while (in.hasNextLine()) { 28 | String line = in.nextLine(); 29 | String[] words = line.split("\\s+"); 30 | 31 | numberOfLines += 1; 32 | numberOfCharacters += line.length(); 33 | numberOfWords = words.length; 34 | } 35 | 36 | in.close(); 37 | 38 | System.out.printf("Number of lines are: %d\n", numberOfLines); 39 | System.out.printf("Number of words are: %d\n", numberOfWords); 40 | System.out.printf("Number of characters are: %d\n", numberOfCharacters); 41 | } 42 | } -------------------------------------------------------------------------------- /07-InputOutputAndExceptionHandling/P7_06.java: -------------------------------------------------------------------------------- 1 | /*Write a program Find that searches all files specified on the command line and prints 2 | out all lines containing a specified word. For example, if you call 3 | java Find ring report.txt address.txt Homework.java 4 | then the program might print 5 | report.txt: has broken up an international ring of DVD bootleggers that 6 | address.txt: Kris Kringle, North Pole 7 | address.txt: Homer Simpson, Springfield 8 | Homework.java: String filename; 9 | The specified word is always the first command line argument.*/ 10 | 11 | import java.io.File; 12 | import java.io.FileNotFoundException; 13 | import java.util.Scanner; 14 | 15 | public class P7_06 { 16 | public static void main(String[] args) { 17 | String word = args[0]; 18 | 19 | for (int i = 1; i < args.length; i++) { 20 | File file = new File(args[i]); 21 | Scanner in = null; 22 | 23 | try { 24 | in = new Scanner(file); 25 | } catch (FileNotFoundException e) { 26 | System.out.println("File was not found!"); 27 | } 28 | 29 | while (in.hasNextLine()) { 30 | String line = in.nextLine(); 31 | if (line.contains(word)) { 32 | System.out.printf("%s: %s\n", args[i], line); 33 | } 34 | } 35 | 36 | in.close(); 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /07-InputOutputAndExceptionHandling/P7_08.java: -------------------------------------------------------------------------------- 1 | /*Write a program that replaces each line of a file with its reverse. For example, if you 2 | run 3 | java Reverse HelloPrinter.java 4 | then the contents of HelloPrinter.java are changed to 5 | retnirPolleH ssalc cilbup 6 | { 7 | )sgra ][gnirtS(niam diov citats cilbup 8 | { 9 | wodniw elosnoc eht ni gniteerg a yalpsiD // 10 | ;)"!dlroW ,olleH"(nltnirp.tuo.metsyS 11 | } 12 | }*/ 13 | 14 | import java.io.File; 15 | import java.io.FileNotFoundException; 16 | import java.util.Scanner; 17 | 18 | public class P7_08 { 19 | public static void main(String[] args) { 20 | String filename = args[0]; 21 | readFile(filename); 22 | } 23 | 24 | public static void readFile(String filename) { 25 | File file = new File(filename); 26 | Scanner in = null; 27 | 28 | try { 29 | in = new Scanner(file); 30 | } catch (FileNotFoundException e) { 31 | System.out.println("File not found!"); 32 | } 33 | 34 | while (in.hasNextLine()) { 35 | String currentLine = in.nextLine(); 36 | System.out.println(reverse(currentLine)); 37 | } 38 | in.close(); 39 | } 40 | 41 | public static String reverse(String line) { 42 | String newLine = ""; 43 | 44 | for (int i = line.length() - 1; i >= 0; i--) { 45 | newLine += line.charAt(i); 46 | } 47 | 48 | return newLine; 49 | } 50 | } -------------------------------------------------------------------------------- /07-InputOutputAndExceptionHandling/P7_13.java: -------------------------------------------------------------------------------- 1 | /*Write a program that asks the user to input a set of floating-point values. When the 2 | user enters a value that is not a number, give the user a second chance to enter the 3 | value. After two chances, quit reading input. Add all correctly specified values and 4 | print the sum when the user is done entering data. Use exception handling to detect 5 | improper inputs.*/ 6 | 7 | import java.util.InputMismatchException; 8 | import java.util.Scanner; 9 | 10 | public class P7_13 { 11 | public static void main(String[] args) { 12 | Scanner input = new Scanner(System.in); 13 | 14 | int times = 2; 15 | int allNumbers = 0; 16 | double sum = 0; 17 | 18 | while (times > 0) { 19 | try { 20 | System.out.print("Enter a number: "); 21 | double currentNumber = input.nextDouble(); 22 | sum += currentNumber; 23 | allNumbers++; 24 | } catch (InputMismatchException e) { 25 | System.out.println("Enter valid number!"); 26 | times--; 27 | input.next(); 28 | } 29 | } 30 | 31 | System.out.printf("Average of all numbers is: %.2f\n", sum / allNumbers); 32 | 33 | input.close(); 34 | } 35 | } -------------------------------------------------------------------------------- /07-InputOutputAndExceptionHandling/P7_14.java: -------------------------------------------------------------------------------- 1 | /*Using the mechanism described in Special Topic 7.1, write a program that reads all 2 | data from a web page and writes them to a file. Prompt the user for the web page 3 | URL and the file.*/ 4 | 5 | import java.io.File; 6 | import java.io.FileNotFoundException; 7 | import java.io.IOException; 8 | import java.io.PrintWriter; 9 | import java.util.Scanner; 10 | 11 | import org.jsoup.Jsoup; 12 | import org.jsoup.nodes.Document; 13 | 14 | public class P7_14 { 15 | public static void main(String[] args) throws IOException { 16 | Scanner input = new Scanner(System.in); 17 | System.out.print("Please enter file to write content: "); 18 | String filename = input.nextLine(); 19 | System.out.print("Please enter webpage to get html from it: "); 20 | String webpage = input.nextLine(); 21 | input.close(); 22 | 23 | String webHTML = getHTMLFromWebpage(webpage); 24 | writeContentInFile(filename, webHTML); 25 | } 26 | 27 | public static void writeContentInFile(String filename, String content) throws FileNotFoundException { 28 | File file = new File(filename); 29 | PrintWriter out = new PrintWriter(file); 30 | out.write(content); 31 | out.close(); 32 | System.out.println("Information was saved in the file!"); 33 | } 34 | 35 | public static String getHTMLFromWebpage(String webpage) throws IOException { 36 | Document doc = Jsoup.connect(webpage).userAgent("Mozilla").get(); 37 | String webpageHTML = doc.html(); 38 | 39 | return webpageHTML; 40 | } 41 | } -------------------------------------------------------------------------------- /07-InputOutputAndExceptionHandling/P7_15.java: -------------------------------------------------------------------------------- 1 | /*Using the mechanism described in Special Topic 7.1, write a program that reads all 2 | data from a web page and prints all hyperlinks of the form 3 | link text */ 4 | 5 | import java.io.IOException; 6 | import java.util.ArrayList; 7 | import java.util.Scanner; 8 | 9 | import org.jsoup.Jsoup; 10 | import org.jsoup.nodes.Document; 11 | import org.jsoup.nodes.Element; 12 | import org.jsoup.select.Elements; 13 | 14 | public class P7_15 { 15 | public static void main(String[] args) throws IOException { 16 | Scanner input = new Scanner(System.in); 17 | System.out.print("Please enter webpage to get links from html it: "); 18 | String webpage = input.nextLine(); 19 | input.close(); 20 | 21 | getHTMLLinksFromPage(webpage); 22 | } 23 | 24 | public static ArrayList getHTMLLinksFromPage(String webpage) throws IOException { 25 | ArrayList links = new ArrayList(); 26 | 27 | Document doc = Jsoup.connect(webpage).userAgent("Mozilla").get(); 28 | Elements allTags = doc.getElementsByTag("a"); 29 | 30 | for (Element tag : allTags) { 31 | links.add(tag.toString()); 32 | } 33 | 34 | return links; 35 | } 36 | } -------------------------------------------------------------------------------- /08-ObjectsAndClasses/P8_01.java: -------------------------------------------------------------------------------- 1 | /*We want to add a button to the tally counter in Section 8.2 that allows an operator to 2 | undo an accidental button click. Provide a method public void undo() 3 | that simulates such a button. As an added precaution, make sure that the operator 4 | cannot click the undo button more often than the count button.*/ 5 | 6 | public class P8_01 { 7 | private int value; 8 | 9 | public int getValue() { 10 | return this.value; 11 | } 12 | 13 | public void count() { 14 | this.value = this.value + 1; 15 | } 16 | 17 | public void reset() { 18 | this.value = 0; 19 | } 20 | 21 | public void undo() { 22 | if (this.value > 0) { 23 | this.value -= 1; 24 | } else { 25 | this.value = 0; 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /08-ObjectsAndClasses/P8_02.java: -------------------------------------------------------------------------------- 1 | /*Simulate a tally counter that can be used to admit a limited number of people. First, 2 | the limit is set with a call 3 | public void setLimit(int maximum) 4 | If the count button was clicked more often than the limit, simulate an alarm by 5 | printing out a message “Limit exceeded”.*/ 6 | 7 | public class P8_02 { 8 | private int value; 9 | private int limit; 10 | 11 | public int getValue() { 12 | return this.value; 13 | } 14 | 15 | public void setLimit(int maximum) { 16 | this.limit = maximum; 17 | } 18 | 19 | public void count() { 20 | if (this.value == this.limit) { 21 | System.out.println("Limit exceeded"); 22 | } else { 23 | this.value = this.value + 1; 24 | } 25 | } 26 | 27 | public void undo() { 28 | if (this.value > 0) { 29 | this.value -= 1; 30 | } else { 31 | this.value = 0; 32 | } 33 | } 34 | 35 | public void reset() { 36 | this.value = 0; 37 | } 38 | } -------------------------------------------------------------------------------- /08-ObjectsAndClasses/P8_03.java: -------------------------------------------------------------------------------- 1 | /*Reimplement the Menu class so that it stores all menu items in one long string. 2 | Hint: Keep a separate counter for the number of options. When a new option is 3 | added, append the option count, the option, and a newline character.*/ 4 | 5 | import java.util.Scanner; 6 | 7 | public class P8_03 { 8 | String options; 9 | int numberOfOptions; 10 | 11 | public P8_03() { 12 | this.options = ""; 13 | this.numberOfOptions = 0; 14 | } 15 | 16 | public String getOptins() { 17 | return this.options; 18 | } 19 | 20 | public void addOptins(String option) { 21 | this.numberOfOptions++; 22 | this.options += String.format("%s%d|", option, this.numberOfOptions); 23 | } 24 | 25 | public void getInput() { 26 | Scanner console = new Scanner(System.in); 27 | int choice; 28 | 29 | do { 30 | System.out.print("Choice: "); 31 | choice = console.nextInt(); 32 | } while (choice < 1 || choice > this.numberOfOptions); 33 | 34 | console.close(); 35 | } 36 | } -------------------------------------------------------------------------------- /08-ObjectsAndClasses/P8_04.java: -------------------------------------------------------------------------------- 1 | /*Implement a class Address . An address has a house number, a street, an optional 2 | apartment number, a city, a state, and a postal code. Supply two constructors: one 3 | with an apartment number and one without. Supply a print method that prints the 4 | address with the street on one line and the city, state, and zip code on the next line. 5 | Supply a method public boolean comesBefore(Address other) that tests whether this 6 | address comes before another when the addresses are compared by postal code.*/ 7 | 8 | public class P8_04 { 9 | int houseNumber; 10 | String street; 11 | int apartmentNumber; 12 | String city; 13 | String state; 14 | int postalCode; 15 | 16 | public P8_04(int houseNumber, String street, String city, String state, int postalCode) { 17 | this.houseNumber = houseNumber; 18 | this.street = street; 19 | this.city = city; 20 | this.state = state; 21 | this.postalCode = postalCode; 22 | } 23 | 24 | public P8_04(int houseNumber, String street, int apartmentNumber, String city, String state, int postalCode) { 25 | this(houseNumber, street, city, state, postalCode); 26 | this.apartmentNumber = apartmentNumber; 27 | } 28 | 29 | public void printAddress() { 30 | System.out.printf("Street: %s House number: %s \n", this.street, this.houseNumber); 31 | System.out.printf("City: %s State: %s Postal Code: %d\n", this.city, this.state, this.postalCode); 32 | } 33 | 34 | public boolean comesBefore(P8_04 other) { 35 | if (this.postalCode < other.postalCode) { 36 | return true; 37 | } else { 38 | return false; 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /08-ObjectsAndClasses/P8_05.java: -------------------------------------------------------------------------------- 1 | /*Implement a class SodaCan with methods getSurfaceArea() and get­­Volume(). 2 | In the constructor, supply the height and radius of the can.*/ 3 | 4 | public class P8_05 { 5 | double height; 6 | double radius; 7 | 8 | public P8_05(double height, double radius) { 9 | this.height = height; 10 | this.radius = radius; 11 | } 12 | 13 | public double getSurfaceArea() { 14 | return 2 * Math.PI * this.radius * (this.radius + this.height); 15 | } 16 | 17 | public double getVolume() { 18 | return Math.PI * this.radius * this.radius * this.height; 19 | } 20 | } -------------------------------------------------------------------------------- /08-ObjectsAndClasses/P8_06.java: -------------------------------------------------------------------------------- 1 | /*Implement a class Car with the following properties. A car has a cer­tain fuel 2 | efficiency (measured in miles/gallon) and a certain amount of fuel in the gas tank. 3 | The efficiency is specified in the constructor, and the initial fuel level is 0. 4 | Supply a method drive that simulates driving the car for a certain distance, 5 | reducing the fuel level in the gas tank, and methods getGasLevel , to return the 6 | current fuel level, and addGas , to tank up. Sample usage: 7 | Car myHybrid = new Car(50); // 50 miles per gallon 8 | myHybrid.addGas(20); // Tank 20 gallons 9 | myHybrid.drive(100); // Drive 100 miles 10 | System.out.println(myHybrid.getGasLevel()); // Print fuel remaining 11 | */ 12 | 13 | public class P8_06 { 14 | double fuelEfficiency; 15 | double amountOfFuel; 16 | 17 | public P8_06(double fuelEfficiency) { 18 | this.fuelEfficiency = fuelEfficiency; 19 | this.amountOfFuel = 0; 20 | } 21 | 22 | public double getGasLevel() { 23 | return this.amountOfFuel; 24 | } 25 | 26 | public void addGas(double gas) { 27 | this.amountOfFuel += gas; 28 | } 29 | 30 | public void drive(double miles) { 31 | double burnedFuel = miles / fuelEfficiency; 32 | this.amountOfFuel -= burnedFuel; 33 | } 34 | } -------------------------------------------------------------------------------- /08-ObjectsAndClasses/P8_07.java: -------------------------------------------------------------------------------- 1 | /*Implement a class Student . For the purpose of this exercise, a student has a name 2 | and a total quiz score. Supply an appropriate constructor and methods getName() , 3 | addQuiz(int score) , getTotalScore() , and getAverageScore() . To compute the latter, you 4 | also need to store the number of quizzes that the student took.*/ 5 | 6 | public class P8_07 { 7 | String name; 8 | int totalQuizScore; 9 | int numberOfQuizzes; 10 | 11 | public P8_07(String name) { 12 | this.name = name; 13 | this.totalQuizScore = 0; 14 | this.numberOfQuizzes = 0; 15 | } 16 | 17 | public String getName() { 18 | return this.name; 19 | } 20 | 21 | public int getTotalScore() { 22 | return this.totalQuizScore; 23 | } 24 | 25 | public void addQuiz(int score) { 26 | this.numberOfQuizzes++; 27 | this.totalQuizScore += score; 28 | } 29 | 30 | public double getAverageScore() { 31 | return this.totalQuizScore / this.numberOfQuizzes; 32 | } 33 | } -------------------------------------------------------------------------------- /08-ObjectsAndClasses/P8_08A.java: -------------------------------------------------------------------------------- 1 | /*Modify the Student class of Exercise P8.7 to compute grade point averages. Meth­ods 2 | are needed to add a grade and get the current GPA. Specify grades as elements of a 3 | class Grade . Supply a constructor that constructs a grade from a string, such as "B+". 4 | You will also need a method that translates grades into their numeric values (for 5 | example, "B+" becomes 3.3).*/ 6 | 7 | public class P8_08A { 8 | String name; 9 | int totalSumOfGrades; 10 | int numberOfGrades; 11 | 12 | public P8_08A(String name) { 13 | this.name = name; 14 | this.totalSumOfGrades = 0; 15 | this.numberOfGrades = 0; 16 | } 17 | 18 | public String getName() { 19 | return this.name; 20 | } 21 | 22 | public double getAverageGrade() { 23 | return this.totalSumOfGrades / this.numberOfGrades; 24 | } 25 | 26 | public void addGrade(P8_08B grade) { 27 | this.numberOfGrades++; 28 | this.totalSumOfGrades += grade.getScore(); 29 | } 30 | } -------------------------------------------------------------------------------- /08-ObjectsAndClasses/P8_08B.java: -------------------------------------------------------------------------------- 1 | /*Modify the Student class of Exercise P8.7 to compute grade point averages. Meth­ods 2 | are needed to add a grade and get the current GPA. Specify grades as elements of a 3 | class Grade . Supply a constructor that constructs a grade from a string, such as "B+". 4 | You will also need a method that translates grades into their numeric values (for 5 | example, "B+" becomes 3.3).*/ 6 | 7 | public class P8_08B { 8 | private String grade; 9 | private double score; 10 | 11 | public P8_08B(String grade) { 12 | this.grade = grade; 13 | this.score = 0; 14 | } 15 | 16 | public void gradeToScore() { 17 | char gradeLetter = this.grade.charAt(0); 18 | char gradeSign = ' '; 19 | 20 | if (this.grade.length() == 2) { 21 | gradeSign = this.grade.charAt(1); 22 | } 23 | 24 | if (gradeLetter == 'A') { 25 | score = 4; 26 | } else if (gradeLetter == 'B') { 27 | score = 3; 28 | } else if (gradeLetter == 'C') { 29 | score = 2; 30 | } else if (gradeLetter == 'D') { 31 | score = 1; 32 | } else if (gradeLetter == 'F') { 33 | score = 0; 34 | } 35 | 36 | if (gradeSign == '+') { 37 | score += 0.3; 38 | } else if (gradeSign == '-') { 39 | score -= 0.3; 40 | } 41 | } 42 | 43 | public double getScore() { 44 | this.gradeToScore(); 45 | return this.score; 46 | } 47 | } -------------------------------------------------------------------------------- /08-ObjectsAndClasses/P8_10.java: -------------------------------------------------------------------------------- 1 | /*Implement a VotingMachine class that can be used for a simple election. Have meth­ods 2 | to clear the machine state, to vote for a Democrat, to vote for a Republican, and to 3 | get the tallies for both parties.*/ 4 | 5 | public class P8_10 { 6 | private int voteForDemocrat; 7 | private int voteForRepublican; 8 | 9 | public void clear() { 10 | this.voteForDemocrat = 0; 11 | this.voteForRepublican = 0; 12 | } 13 | 14 | public void voteDemocrats() { 15 | this.voteForDemocrat += 1; 16 | } 17 | 18 | public void voteRepublicans() { 19 | this.voteForRepublican += 1; 20 | } 21 | 22 | public void showVotes() { 23 | System.out.println("Democrats:" + this.voteForDemocrat); 24 | System.out.println("Republicans: " + this.voteForRepublican); 25 | } 26 | } -------------------------------------------------------------------------------- /08-ObjectsAndClasses/P8_11.java: -------------------------------------------------------------------------------- 1 | /*Provide a class for authoring a simple letter. In the constructor, supply the names of 2 | the sender and the recipient: 3 | public Letter(String from, String to) 4 | Supply a method 5 | public void addLine(String line) 6 | to add a line of text to the body of the letter. Supply a method 7 | public String getText() 8 | that returns the entire text of the letter. The text has the form: 9 | Dear recipient name : 10 | blank line 11 | first line of the body 12 | second line of the body 13 | last line of the body 14 | blank line 15 | Sincerely, 16 | blank line 17 | sender name 18 | Also supply a main method that prints this letter. 19 | Dear John: 20 | I am sorry we must part. 21 | I wish you all the best. 22 | Sincerely, 23 | Mary 24 | Construct an object of the Letter class and call addLine twice.*/ 25 | 26 | public class P8_11 { 27 | private String from; 28 | private String to; 29 | private String text; 30 | 31 | public P8_11(String from, String to) { 32 | this.from = from; 33 | this.to = to; 34 | this.text = ""; 35 | } 36 | 37 | public void addLine(String line) { 38 | this.text += String.format("%s\n", line); 39 | } 40 | 41 | public String getText() { 42 | return String.format("Dear %s\n\n%s\nSincerely,\n\n%s", this.from, this.text, this.to); 43 | } 44 | 45 | public static void main(String[] args) { 46 | P8_11 letter = new P8_11("John", "Mary"); 47 | letter.addLine("I am sorry we must part."); 48 | letter.addLine("I wish you all the best."); 49 | System.out.println(letter.getText()); 50 | } 51 | } -------------------------------------------------------------------------------- /08-ObjectsAndClasses/P8_12.java: -------------------------------------------------------------------------------- 1 | /*Write a class Bug that models a bug moving along a horizontal line. The bug moves 2 | either to the right or left. Initially, the bug moves to the right, but it can turn to 3 | change its direction. In each move, its position changes by one unit in the current 4 | direction. Provide a constructor 5 | public Bug(int initialPosition) 6 | and methods 7 | • public void turn() 8 | • public void move() 9 | • public int getPosition() 10 | Sample usage: 11 | Bug bugsy = new Bug(10); 12 | bugsy.move(); // Now the position is 11 13 | bugsy.turn(); 14 | bugsy.move(); // Now the position is 10 15 | Your main method should construct a bug, make it move and turn a few times, and 16 | print the actual and expected positions.*/ 17 | 18 | public class P8_12 { 19 | private int position; 20 | private boolean direction; 21 | 22 | public P8_12(int initialPosition) { 23 | this.position = initialPosition; 24 | this.direction = true; 25 | } 26 | 27 | public void turn() { 28 | if (this.direction) { 29 | this.direction = false; 30 | } else { 31 | this.direction = true; 32 | } 33 | } 34 | 35 | public void move() { 36 | if (this.direction) { 37 | this.position += 1; 38 | } else { 39 | this.position -= 1; 40 | } 41 | } 42 | 43 | public int getPosition() { 44 | return this.position; 45 | } 46 | } -------------------------------------------------------------------------------- /08-ObjectsAndClasses/P8_13.java: -------------------------------------------------------------------------------- 1 | /*Implement a class Moth that models a moth flying in a straight line. The moth has a 2 | position, the distance from a fixed origin. When the moth moves toward a point of 3 | light, its new position is halfway between its old position and the position of the 4 | light source. Supply a constructor 5 | public Moth(double initialPosition) 6 | and methods 7 | • public void moveToLight(double lightPosition) 8 | • public void getPosition() 9 | Your main method should construct a moth, move it toward a couple of light sources, 10 | and check that the moth’s position is as expected.*/ 11 | 12 | public class P8_13 { 13 | private double position; 14 | 15 | public P8_13(double initialPosition) { 16 | this.position = initialPosition; 17 | } 18 | 19 | public void moveToLight(double lightPosition) { 20 | this.position += (this.position + lightPosition) / 2; 21 | } 22 | 23 | public double getPosition() { 24 | return this.position; 25 | } 26 | } -------------------------------------------------------------------------------- /08-ObjectsAndClasses/P8_15A.java: -------------------------------------------------------------------------------- 1 | /*Solve Exercise P8.14 by implementing classes Sphere , Cylinder , and Cone . Which 2 | approach is more object-oriented?*/ 3 | 4 | public class P8_15A { 5 | private double radius; 6 | 7 | public P8_15A(int radius) { 8 | this.radius = radius; 9 | } 10 | 11 | public double sphereVolume() { 12 | return (4.0 / 3.0) * Math.PI * this.radius * this.radius * this.radius; 13 | } 14 | 15 | public double sphereSurface() { 16 | return 4 * Math.PI * this.radius * this.radius; 17 | } 18 | } -------------------------------------------------------------------------------- /08-ObjectsAndClasses/P8_15B.java: -------------------------------------------------------------------------------- 1 | /*Solve Exercise P8.14 by implementing classes Sphere , Cylinder , and Cone . Which 2 | approach is more object-oriented?*/ 3 | 4 | public class P8_15B { 5 | private double radius; 6 | private double height; 7 | 8 | public P8_15B(int radius, int height) { 9 | this.radius = radius; 10 | this.height = height; 11 | } 12 | 13 | public double cylinderVolume() { 14 | return Math.PI * this.radius * this.radius * this.height; 15 | } 16 | 17 | public double cylinderSurface() { 18 | return 2 * Math.PI * this.radius * (this.radius + this.height); 19 | } 20 | } -------------------------------------------------------------------------------- /08-ObjectsAndClasses/P8_15C.java: -------------------------------------------------------------------------------- 1 | /*Solve Exercise P8.14 by implementing classes Sphere , Cylinder , and Cone . Which 2 | approach is more object-oriented?*/ 3 | 4 | public class P8_15C { 5 | private double radius; 6 | private double height; 7 | 8 | public P8_15C(int radius, int height) { 9 | this.radius = radius; 10 | this.height = height; 11 | } 12 | 13 | public double coneVolume() { 14 | return (1.0 / 3.0) * Math.PI * this.radius * this.radius * this.height; 15 | } 16 | 17 | public double coneSurface() { 18 | double l = Math.sqrt((this.radius * this.radius) + (this.height * this.height)); 19 | 20 | return Math.PI * this.radius * (this.radius + l); 21 | } 22 | } -------------------------------------------------------------------------------- /09-InheritanceAndInterfaces/AnyCorrectChoiceQuestion.java: -------------------------------------------------------------------------------- 1 | /*Add a class AnyCorrectChoiceQuestion to the question hierarchy of Section 9.1 that 2 | allows multiple correct choices. The respondent should provide any one of the cor­rect 3 | choices. The answer string should contain all of the correct choices, separated by 4 | spaces. Provide instructions in the question text.*/ 5 | 6 | public class AnyCorrectChoiceQuestion extends ChoiceQuestion { 7 | public AnyCorrectChoiceQuestion() { 8 | super(); 9 | } 10 | 11 | public void setAnswer(String correctResponse) { 12 | String newAnswers = getAnswer(); 13 | newAnswers += correctResponse + " "; 14 | super.setAnswer(newAnswers); 15 | } 16 | 17 | public void addChoice(String choice, boolean correct) { 18 | super.setChoice(choice); 19 | if (correct) { 20 | setAnswer(choice); 21 | } 22 | } 23 | 24 | public boolean checkAnswer(String response) { 25 | return this.getAnswer().trim().toLowerCase().contains(response.trim().toLowerCase()); 26 | } 27 | 28 | public void display() { 29 | super.display(); 30 | System.out.println("Provide anyone of correct answers!"); 31 | System.out.println("If they are more than one provide them separated with spaces!"); 32 | } 33 | } -------------------------------------------------------------------------------- /09-InheritanceAndInterfaces/BetterRectangle.java: -------------------------------------------------------------------------------- 1 | /*The Rectangle class of the standard Java library does not supply a method to com­pute 2 | the area or the perimeter of a rectangle. Provide a subclass BetterRectangle of the 3 | Rectangle class that has getPerimeter and getArea methods. Do not add any instance 4 | variables. In the constructor, call the setLocation and setSize methods of the Rectangle 5 | class. Provide a program that tests the methods that you supplied. 6 | 7 | Repeat Exercise P9.10, but in the BetterRectangle constructor, invoke the superclass 8 | constructor.*/ 9 | 10 | import java.awt.Rectangle; 11 | 12 | @SuppressWarnings("serial") 13 | public class BetterRectangle extends Rectangle { 14 | 15 | public BetterRectangle(int x, int y, int width, int height) { 16 | super(x, y, width, height); 17 | } 18 | 19 | /*public BetterRectangle(int x, int y, int width, int height) { 20 | this.setLocation(x, y); 21 | this.setSize(width, height); 22 | }*/ 23 | 24 | public double getPerimeter() { 25 | return 2 * super.getHeight() + 2 * super.getWidth(); 26 | } 27 | 28 | public double getArea() { 29 | return super.getHeight() * super.getWidth(); 30 | } 31 | } -------------------------------------------------------------------------------- /09-InheritanceAndInterfaces/ChoiceQuestion.java: -------------------------------------------------------------------------------- 1 | /*Provide toString methods for the Question and ChoiceQuestion classes.*/ 2 | 3 | import java.util.ArrayList; 4 | 5 | public class ChoiceQuestion extends Question { 6 | private ArrayList choices; 7 | 8 | public ChoiceQuestion() { 9 | super(); 10 | choices = new ArrayList(); 11 | } 12 | 13 | public ArrayList getChoices() { 14 | return this.choices; 15 | } 16 | 17 | public void setChoice(String choice) { 18 | this.choices.add(choice); 19 | } 20 | 21 | public void addChoice(String choice, boolean correct) { 22 | setChoice(choice); 23 | if (correct) { 24 | setAnswer(choice); 25 | } 26 | } 27 | 28 | public void display() { 29 | super.display(); 30 | for (int i = 0; i < choices.size(); i++) { 31 | int choiceNumber = i + 1; 32 | System.out.println(choiceNumber + ": " + choices.get(i)); 33 | } 34 | } 35 | 36 | public String toString() { 37 | return getClass().getName(); 38 | } 39 | } -------------------------------------------------------------------------------- /09-InheritanceAndInterfaces/Daily.java: -------------------------------------------------------------------------------- 1 | /*Implement a superclass Appointment and subclasses Onetime , Daily , and Monthly. An 2 | appointment has adescription (for example, “see the dentist”) and a date. Write a 3 | method occursOn(int year, int month, int day) that checks whether the appointment occurs 4 | on that date. For example, for a monthly appointment, you must check whether the day of the 5 | month matches. Then fill an array of Appoint­ment objects with a mixture of appointments. 6 | Have the user enter a date and print out all appointments that occur on that date.*/ 7 | 8 | import java.text.ParseException; 9 | 10 | public class Daily extends Appointment { 11 | public Daily(String description, int day, int month, int year) throws ParseException { 12 | super(description, day, month, year); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /09-InheritanceAndInterfaces/Employee.java: -------------------------------------------------------------------------------- 1 | /*Make a class Employee with a name and salary. Make a class Manager inherit from 2 | Employee . Add an instance variable, named department , of type String . Supply a method 3 | toString that prints the manager’s name, department, and salary. Make a class Execu­tive 4 | inherit from Manager . Supply appropriate toString methods for all classes. Supply 5 | a test program that tests these classes and methods.*/ 6 | 7 | public class Employee { 8 | private String name; 9 | private double salary; 10 | 11 | public Employee(String name, double salary) { 12 | this.setName(name); 13 | this.setSalary(salary); 14 | } 15 | 16 | public String getName() { 17 | return name; 18 | } 19 | 20 | public void setName(String name) { 21 | this.name = name; 22 | } 23 | 24 | public double getSalary() { 25 | return salary; 26 | } 27 | 28 | public void setSalary(double salary) { 29 | this.salary = salary; 30 | } 31 | 32 | public String toString() { 33 | return getClass().getName() + " name: " + this.getName() + " salary: " + this.getSalary(); 34 | } 35 | } -------------------------------------------------------------------------------- /09-InheritanceAndInterfaces/Executive.java: -------------------------------------------------------------------------------- 1 | /*Make a class Employee with a name and salary. Make a class Manager inherit from 2 | Employee . Add an instance variable, named department , of type String . Supply a method 3 | toString that prints the manager’s name, department, and salary. Make a class Execu­tive 4 | inherit from Manager . Supply appropriate toString methods for all classes. Supply 5 | a test program that tests these classes and methods.*/ 6 | 7 | public class Executive extends Manager { 8 | private double bonus; 9 | 10 | public Executive(String name, double salary, String department, double bonus) { 11 | super(name, salary, department); 12 | setBonus(bonus); 13 | } 14 | 15 | public double getBonus() { 16 | return this.bonus; 17 | } 18 | 19 | public void setBonus(double bonus) { 20 | this.bonus = bonus; 21 | } 22 | 23 | public String toString() { 24 | return super.toString() + " bonus: " + this.getBonus(); 25 | } 26 | } -------------------------------------------------------------------------------- /09-InheritanceAndInterfaces/FillInQuestion.java: -------------------------------------------------------------------------------- 1 | /*Add a class FillInQuestion to the question hierarchy of Section 9.1. Such a question is 2 | constructed with a string that contains the answer, surrounded by _ _ , for exam­ple, 3 | "The inventor of Java was _James Gosling_" . The question should be displayed as 4 | The inventor of Java was _____*/ 5 | 6 | import java.util.Scanner; 7 | 8 | public class FillInQuestion extends Question { 9 | public FillInQuestion() { 10 | super(); 11 | } 12 | 13 | public void constructQuestionAndAnswer(String questionText) { 14 | Scanner parser = new Scanner(questionText); 15 | parser.useDelimiter("_"); 16 | String question = parser.next(); 17 | String answer = parser.next(); 18 | parser.close(); 19 | 20 | question += " "; 21 | for (int i = 0; i < answer.length(); i++) { 22 | question += "_ "; 23 | } 24 | 25 | this.setText(question); 26 | this.setAnswer(answer); 27 | } 28 | } -------------------------------------------------------------------------------- /09-InheritanceAndInterfaces/Filter.java: -------------------------------------------------------------------------------- 1 | /*Declare an interface Filter as follows: 2 | public interface Filter{ 3 | boolean accept(Object x); 4 | } 5 | Write a method 6 | public static ArrayList collectAll(ArrayList objects, Filter f) 7 | that returns all objects in the objects array that are accepted by the given filter. 8 | Provide a class ShortWordFilter whose filter method accepts all strings of length < 5. 9 | Then write a program that reads all words from System.in , puts them into an 10 | Array­List , calls collec­tAll , and prints a list of the short words.*/ 11 | 12 | public interface Filter { 13 | boolean accept(Object x); 14 | } -------------------------------------------------------------------------------- /09-InheritanceAndInterfaces/Instructor.java: -------------------------------------------------------------------------------- 1 | /*Implement a superclass Person . Make two classes, Student and Instructor , that inherit 2 | from Person . A person has a name and a year of birth. A student has a major, and 3 | an instructor has a salary. Write the class declarations, the constructors, and the 4 | methods toString for all classes. Supply a test program that tests these classes and 5 | methods.*/ 6 | 7 | public class Instructor extends Person { 8 | private double salary; 9 | 10 | public Instructor(String name, int yearOfBirth, double salary) { 11 | super(name, yearOfBirth); 12 | setSalary(salary); 13 | } 14 | 15 | public double getSalary() { 16 | return this.salary; 17 | } 18 | 19 | public void setSalary(double salary) { 20 | this.salary = salary; 21 | } 22 | 23 | public String toString() { 24 | return super.toString() + " salary: " + this.getSalary(); 25 | } 26 | } -------------------------------------------------------------------------------- /09-InheritanceAndInterfaces/LabeledPoint.java: -------------------------------------------------------------------------------- 1 | /*A labeled point has x- and y-coordinates and a string label. Provide a class Labeled­Point 2 | with a constructor LabeledPoint(int x, int y, String label) and a toString method that displays 3 | x, y and label*/ 4 | 5 | public class LabeledPoint { 6 | 7 | private double x; 8 | private double y; 9 | private String label; 10 | 11 | public LabeledPoint(int x, int y, String label) { 12 | this.setX(x); 13 | this.setY(y); 14 | this.setLabel(label); 15 | } 16 | 17 | public double getX() { 18 | return x; 19 | } 20 | 21 | public void setX(double x) { 22 | this.x = x; 23 | } 24 | 25 | public double getY() { 26 | return y; 27 | } 28 | 29 | public void setY(double y) { 30 | this.y = y; 31 | } 32 | 33 | public String getLabel() { 34 | return label; 35 | } 36 | 37 | public void setLabel(String label) { 38 | this.label = label; 39 | } 40 | 41 | public String toString() { 42 | return "x: " + this.getX() + "\ny: " + this.getY() + "\nlabel:" + this.getLabel(); 43 | } 44 | } -------------------------------------------------------------------------------- /09-InheritanceAndInterfaces/Manager.java: -------------------------------------------------------------------------------- 1 | /*Make a class Employee with a name and salary. Make a class Manager inherit from 2 | Employee . Add an instance variable, named department , of type String . Supply a method 3 | toString that prints the manager’s name, department, and salary. Make a class Execu­tive 4 | inherit from Manager . Supply appropriate toString methods for all classes. Supply 5 | a test program that tests these classes and methods.*/ 6 | 7 | public class Manager extends Employee { 8 | private String department; 9 | 10 | public Manager(String name, double salary, String department) { 11 | super(name, salary); 12 | this.setDepartment(department); 13 | } 14 | 15 | public String getDepartment() { 16 | return this.department; 17 | } 18 | 19 | public void setDepartment(String department) { 20 | this.department = department; 21 | } 22 | 23 | public String toString() { 24 | return super.toString() + " department: " + this.getDepartment(); 25 | } 26 | } -------------------------------------------------------------------------------- /09-InheritanceAndInterfaces/Measurable.java: -------------------------------------------------------------------------------- 1 | /*Write a method 2 | public static Measurable maximum(Measurable[] objects) 3 | that returns the object with the largest measure. Use that method to determine the 4 | country with the larg­est area from an array of countries.*/ 5 | 6 | public interface Measurable { 7 | double getMeasure(); 8 | } 9 | 10 | /*public static Measurable maximum(Measurable[] objects){ 11 | Measurable largest = objects[0]; 12 | 13 | for (int i = 1; i < objects.length; i++) { 14 | if (objects[i].getMeasure() > largest.getMeasure()) { 15 | largest = objects[i]; 16 | } 17 | } 18 | 19 | return largest; 20 | }*/ -------------------------------------------------------------------------------- /09-InheritanceAndInterfaces/ModifiedPoint.java: -------------------------------------------------------------------------------- 1 | /*Reimplement the LabeledPoint class of Exercise P9.12 by storing the location in a 2 | java.awt.Point object. Your toString method should invoke the toString method of 3 | the Point class.*/ 4 | 5 | import java.awt.Point; 6 | 7 | @SuppressWarnings("serial") 8 | public class ModifiedPoint extends Point { 9 | private String label; 10 | 11 | public ModifiedPoint(int x, int y, String label) { 12 | super(x, y); 13 | this.setLabel(label); 14 | } 15 | 16 | public String getLabel() { 17 | return label; 18 | } 19 | 20 | public void setLabel(String label) { 21 | this.label = label; 22 | } 23 | 24 | public String toString() { 25 | return super.toString() + String.format("[label=\"%s\"]", this.getLabel()); 26 | } 27 | } -------------------------------------------------------------------------------- /09-InheritanceAndInterfaces/Monthly.java: -------------------------------------------------------------------------------- 1 | /*Implement a superclass Appointment and subclasses Onetime , Daily , and Monthly. An 2 | appointment has adescription (for example, “see the dentist”) and a date. Write a 3 | method occursOn(int year, int month, int day) that checks whether the appointment occurs 4 | on that date. For example, for a monthly appointment, you must check whether the day of the 5 | month matches. Then fill an array of Appoint­ment objects with a mixture of appointments. 6 | Have the user enter a date and print out all appointments that occur on that date.*/ 7 | 8 | import java.text.ParseException; 9 | 10 | public class Monthly extends Appointment { 11 | public Monthly(String description, int day, int month, int year) throws ParseException { 12 | super(description, day, month, year); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /09-InheritanceAndInterfaces/MultiChoiceQuestion.java: -------------------------------------------------------------------------------- 1 | /*Add a class MultiChoiceQuestion to the question hierarchy of Section 9.1 that allows 2 | multiple correct choices. The respondent should provide all correct choices, sepa­rated 3 | by spaces. Provide instructions in the question text.*/ 4 | 5 | public class MultiChoiceQuestion extends ChoiceQuestion { 6 | public MultiChoiceQuestion() { 7 | super(); 8 | } 9 | 10 | public void setAnswer(String correctResponse) { 11 | String newAnswers = getAnswer(); 12 | newAnswers += correctResponse + " "; 13 | super.setAnswer(newAnswers); 14 | } 15 | 16 | public void addChoice(String choice, boolean correct) { 17 | super.setChoice(choice); 18 | if (correct) { 19 | setAnswer(choice); 20 | } 21 | } 22 | 23 | public void display() { 24 | super.display(); 25 | System.out.println("Provide everyone of correct answers!"); 26 | System.out.println("If they are more than one provide them separated with spaces!"); 27 | } 28 | } -------------------------------------------------------------------------------- /09-InheritanceAndInterfaces/NumericQuestion.java: -------------------------------------------------------------------------------- 1 | /*Add a class NumericQuestion to the question hierarchy of Section 9.1. If the response 2 | and the expected answer differ by no more than 0.01, then accept the response as 3 | correct.*/ 4 | 5 | public class NumericQuestion extends Question { 6 | public NumericQuestion() { 7 | super(); 8 | } 9 | 10 | public boolean checkAnswer(String response) { 11 | double expectedAnswer = Double.parseDouble(this.getAnswer()); 12 | double responseAnswer = Double.parseDouble(response); 13 | 14 | return Math.abs(expectedAnswer - responseAnswer) <= 0.01; 15 | } 16 | } -------------------------------------------------------------------------------- /09-InheritanceAndInterfaces/OneTime.java: -------------------------------------------------------------------------------- 1 | /*Implement a superclass Appointment and subclasses Onetime , Daily , and Monthly. An 2 | appointment has adescription (for example, “see the dentist”) and a date. Write a 3 | method occursOn(int year, int month, int day) that checks whether the appointment occurs 4 | on that date. For example, for a monthly appointment, you must check whether the day of the 5 | month matches. Then fill an array of Appoint­ment objects with a mixture of appointments. 6 | Have the user enter a date and print out all appointments that occur on that date.*/ 7 | 8 | import java.text.ParseException; 9 | 10 | public class OneTime extends Appointment { 11 | public OneTime(String description, int day, int month, int year) throws ParseException { 12 | super(description, day, month, year); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /09-InheritanceAndInterfaces/Person.java: -------------------------------------------------------------------------------- 1 | /*Implement a superclass Person . Make two classes, Student and Instructor , that inherit 2 | from Person . A person has a name and a year of birth. A student has a major, and 3 | an instructor has a salary. Write the class declarations, the constructors, and the 4 | methods toString for all classes. Supply a test program that tests these classes and 5 | methods.*/ 6 | 7 | public class Person { 8 | private String name; 9 | private int yearOfBirth; 10 | 11 | public Person(String name, int yearOfBirth) { 12 | this.setName(name); 13 | this.setYearOfBirth(yearOfBirth); 14 | } 15 | 16 | public String getName() { 17 | return this.name; 18 | } 19 | 20 | public void setName(String name) { 21 | this.name = name; 22 | } 23 | 24 | public int getYearOfBirth() { 25 | return this.yearOfBirth; 26 | } 27 | 28 | public void setYearOfBirth(int yearOfBirth) { 29 | this.yearOfBirth = yearOfBirth; 30 | } 31 | 32 | public String toString() { 33 | return getClass().getName() + " name: " + this.getName() + " year of birth: " + this.getYearOfBirth(); 34 | } 35 | } -------------------------------------------------------------------------------- /09-InheritanceAndInterfaces/PersonAverage.java: -------------------------------------------------------------------------------- 1 | /*A person has a name and a height in centimeters. Use the average method in Section 2 | 9.6 to process a collection of Person objects.*/ 3 | 4 | public class PersonAverage { 5 | public static double average(Person[] objects) { 6 | if (objects.length == 0) { 7 | return 0; 8 | } 9 | double sum = 0; 10 | for (Person obj : objects) { 11 | sum = sum + obj.getYearOfBirth(); 12 | } 13 | return sum / objects.length; 14 | } 15 | } -------------------------------------------------------------------------------- /09-InheritanceAndInterfaces/Question.java: -------------------------------------------------------------------------------- 1 | /*Modify the checkAnswer method of the Question class so that it does not take into 2 | account different spaces or upper/lowercase characters. For example, the response 3 | "JAMES gosling" should match an answer of "James Gosling" . 4 | Provide toString methods for the Question and ChoiceQuestion classes.*/ 5 | 6 | public class Question { 7 | private String text; 8 | private String answer; 9 | 10 | public Question() { 11 | this.text = ""; 12 | this.answer = ""; 13 | } 14 | 15 | public String getText() { 16 | return this.text; 17 | } 18 | 19 | public void setText(String questionText) { 20 | this.text = questionText; 21 | } 22 | 23 | public String getAnswer() { 24 | return this.answer; 25 | } 26 | 27 | public void setAnswer(String correctResponse) { 28 | this.answer = correctResponse; 29 | } 30 | 31 | public boolean checkAnswer(String response) { 32 | String realAnswer = this.getAnswer().trim().toLowerCase(); 33 | String responseAnswer = response.trim().toLowerCase(); 34 | 35 | return realAnswer.equals(responseAnswer); 36 | } 37 | 38 | public void display() { 39 | System.out.println(this.text); 40 | } 41 | 42 | public String toString() { 43 | return getClass().getName(); 44 | } 45 | } -------------------------------------------------------------------------------- /09-InheritanceAndInterfaces/ShortWordFilter.java: -------------------------------------------------------------------------------- 1 | /*Declare an interface Filter as follows: 2 | public interface Filter{ 3 | boolean accept(Object x); 4 | } 5 | Write a method 6 | public static ArrayList collectAll(ArrayList objects, Filter f) 7 | that returns all objects in the objects array that are accepted by the given filter. 8 | Provide a class ShortWordFilter whose filter method accepts all strings of length < 5. 9 | Then write a program that reads all words from System.in , puts them into an 10 | Array­List , calls collec­tAll , and prints a list of the short words.*/ 11 | 12 | import java.util.ArrayList; 13 | 14 | public class ShortWordFilter implements Filter { 15 | public boolean accept(Object x) { 16 | return x.toString().length() < 5; 17 | } 18 | 19 | public static ArrayList collectAll(ArrayList objects, Filter f) { 20 | ArrayList acceptibleObjects = new ArrayList(); 21 | 22 | for (int i = 0; i < objects.size(); i++) { 23 | if (f.accept(objects.get(i))) { 24 | acceptibleObjects.add(objects.get(i)); 25 | } 26 | } 27 | 28 | return acceptibleObjects; 29 | } 30 | } -------------------------------------------------------------------------------- /09-InheritanceAndInterfaces/SodaCan.java: -------------------------------------------------------------------------------- 1 | /*Modify the SodaCan class of Exercise P8.5 to implement the Measurable interface. The 2 | measure of a soda can should be its surface area. Write a program that computes the 3 | average surface area of an array of soda cans.*/ 4 | 5 | public class SodaCan implements Measurable { 6 | double height; 7 | double radius; 8 | 9 | public SodaCan(double height, double radius) { 10 | this.height = height; 11 | this.radius = radius; 12 | } 13 | 14 | public double getHeight() { 15 | return height; 16 | } 17 | 18 | public void setHeight(double height) { 19 | this.height = height; 20 | } 21 | 22 | public double getRadius() { 23 | return radius; 24 | } 25 | 26 | public void setRadius(double radius) { 27 | this.radius = radius; 28 | } 29 | 30 | public double getSurfaceArea() { 31 | return 2 * Math.PI * this.radius * (this.radius + this.height); 32 | } 33 | 34 | public double getVolume() { 35 | return Math.PI * this.radius * this.radius * this.height; 36 | } 37 | 38 | @Override 39 | public double getMeasure() { 40 | return getSurfaceArea(); 41 | } 42 | 43 | public static double averageSurfaceAreaOfSodaCans(Measurable[] sodaCans) { 44 | double average = 0; 45 | 46 | for (int i = 0; i < sodaCans.length; i++) { 47 | average += sodaCans[i].getMeasure(); 48 | } 49 | 50 | return average / sodaCans.length; 51 | } 52 | } -------------------------------------------------------------------------------- /09-InheritanceAndInterfaces/Student.java: -------------------------------------------------------------------------------- 1 | /*Implement a superclass Person . Make two classes, Student and Instructor , that inherit 2 | from Person . A person has a name and a year of birth. A student has a major, and 3 | an instructor has a salary. Write the class declarations, the constructors, and the 4 | methods toString for all classes. Supply a test program that tests these classes and 5 | methods.*/ 6 | 7 | public class Student extends Person { 8 | private String major; 9 | 10 | public Student(String name, int yearOfBirth, String major) { 11 | super(name, yearOfBirth); 12 | setMajor(major); 13 | } 14 | 15 | public String getMajor() { 16 | return this.major; 17 | } 18 | 19 | public void setMajor(String major) { 20 | this.major = major; 21 | } 22 | 23 | public String toString() { 24 | return super.toString() + " major: " + this.getMajor(); 25 | } 26 | } -------------------------------------------------------------------------------- /10-GraphicalUserInterfaces/BullsEyeViewer.java: -------------------------------------------------------------------------------- 1 | /*Draw a “bull’s eye”—a set of concentric rings in alternating black and white colors. 2 | Hint: Fill a black circle, then fill a smaller white circle on top, and so on. Your 3 | program should be composed of classes BullsEyeComponent and Bulls­EyeViewer .*/ 4 | 5 | import java.awt.Color; 6 | import java.awt.Graphics; 7 | 8 | import javax.swing.JComponent; 9 | import javax.swing.JFrame; 10 | 11 | @SuppressWarnings("serial") 12 | public class BullsEyeViewer extends JFrame { 13 | private final static int FRAME_WIDTH = 300; 14 | private final static int FRAME_HEIGHT = 200; 15 | private JComponent bullsEyeComponent; 16 | 17 | public BullsEyeViewer() { 18 | this.bullsEyeComponent = new BullsEyeComponent(); 19 | this.add(this.bullsEyeComponent); 20 | this.setSize(FRAME_WIDTH, FRAME_HEIGHT); 21 | this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 22 | this.setVisible(true); 23 | } 24 | 25 | class BullsEyeComponent extends JComponent { 26 | @Override 27 | public void paintComponent(Graphics g) { 28 | g.setColor(Color.BLACK); 29 | g.fillOval(90, 40, 130, 130); 30 | 31 | g.setColor(Color.WHITE); 32 | g.fillOval(105, 55, 100, 100); 33 | 34 | g.setColor(Color.BLACK); 35 | g.fillOval(120, 70, 70, 70); 36 | 37 | g.setColor(Color.WHITE); 38 | g.fillOval(135, 85, 40, 40); 39 | 40 | g.setColor(Color.BLACK); 41 | g.fillOval(150, 100, 10, 10); 42 | } 43 | } 44 | 45 | @SuppressWarnings("unused") 46 | public static void main(String[] args) { 47 | JFrame testFrame = new BullsEyeViewer(); 48 | } 49 | } -------------------------------------------------------------------------------- /10-GraphicalUserInterfaces/ButtonViewer1.java: -------------------------------------------------------------------------------- 1 | /*Enhance the ButtonViewer1 program in Section 10.2.1 so that it prints a message 2 | “I was clicked n times!” whenever the button is clicked. The value n should be 3 | incremented with each click.*/ 4 | 5 | import java.awt.event.ActionEvent; 6 | import java.awt.event.ActionListener; 7 | 8 | import javax.swing.JButton; 9 | import javax.swing.JFrame; 10 | import javax.swing.JPanel; 11 | 12 | @SuppressWarnings("serial") 13 | public class ButtonViewer1 extends JFrame { 14 | private static final int FRAME_HEIGHT = 100; 15 | private static final int FRAME_WIDTH = 100; 16 | 17 | private static int timesClicked; 18 | 19 | private JPanel panel; 20 | private JButton button; 21 | 22 | public ButtonViewer1() { 23 | this.button = new JButton("Click me!"); 24 | ActionListener listener = new ClickListener(); 25 | this.button.addActionListener(listener); 26 | 27 | this.panel = new JPanel(); 28 | this.panel.add(this.button); 29 | this.add(panel); 30 | 31 | this.setSize(FRAME_WIDTH, FRAME_HEIGHT); 32 | this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 33 | this.setVisible(true); 34 | } 35 | 36 | class ClickListener implements ActionListener { 37 | @Override 38 | public void actionPerformed(ActionEvent e) { 39 | timesClicked++; 40 | String message = String.format("I was clicked %d times!", timesClicked); 41 | System.out.println(message); 42 | } 43 | } 44 | 45 | @SuppressWarnings("unused") 46 | public static void main(String[] args) { 47 | JFrame frame = new ButtonViewer1(); 48 | } 49 | } -------------------------------------------------------------------------------- /10-GraphicalUserInterfaces/FaceViewer.java: -------------------------------------------------------------------------------- 1 | /*Write a program to plot the following face. 2 | Provide a class FaceViewer and a class Face­ Component .*/ 3 | 4 | import java.awt.Color; 5 | import java.awt.Graphics; 6 | 7 | import javax.swing.JComponent; 8 | import javax.swing.JFrame; 9 | 10 | @SuppressWarnings("serial") 11 | public class FaceViewer extends JFrame { 12 | private final static int FRAME_WIDTH = 300; 13 | private final static int FRAME_HEIGHT = 200; 14 | private JComponent faceComponent; 15 | 16 | public FaceViewer() { 17 | this.faceComponent = new FaceComponent(); 18 | this.add(this.faceComponent); 19 | this.setSize(FRAME_WIDTH, FRAME_HEIGHT); 20 | this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 21 | this.setVisible(true); 22 | } 23 | 24 | class FaceComponent extends JComponent { 25 | @Override 26 | public void paintComponent(Graphics g) { 27 | Color blueviolet = new Color(138, 43, 226); 28 | g.setColor(blueviolet); 29 | 30 | g.drawLine(100, 140, 180, 140); 31 | g.drawLine(180, 140, 200, 120); 32 | g.drawLine(80, 120, 100, 140); 33 | 34 | g.drawOval(100, 80, 20, 20); 35 | g.drawOval(160, 80, 20, 20); 36 | 37 | g.drawOval(65, 30, 150, 150); 38 | } 39 | } 40 | 41 | @SuppressWarnings("unused") 42 | public static void main(String[] args) { 43 | JFrame testFrame = new FaceViewer(); 44 | } 45 | } -------------------------------------------------------------------------------- /10-GraphicalUserInterfaces/FlagViewer.java: -------------------------------------------------------------------------------- 1 | /*Modify the drawItalianFlag method in How To 10.1 to draw any flag with three horizontal 2 | colored stripes. Write a program that displays the German and Hungarian flags.*/ 3 | 4 | import java.awt.Color; 5 | import java.awt.Graphics; 6 | 7 | import javax.swing.JComponent; 8 | import javax.swing.JFrame; 9 | 10 | @SuppressWarnings("serial") 11 | public class FlagViewer extends JFrame { 12 | private final static int FRAME_WIDTH = 300; 13 | private final static int FRAME_HEIGHT = 200; 14 | 15 | private JComponent flagComponent; 16 | 17 | public FlagViewer() { 18 | this.flagComponent = new FlagComponent(); 19 | this.add(this.flagComponent); 20 | this.setSize(FRAME_WIDTH, FRAME_HEIGHT); 21 | this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 22 | this.setVisible(true); 23 | } 24 | 25 | class FlagComponent extends JComponent { 26 | @Override 27 | public void paintComponent(Graphics g) { 28 | // German Flag 29 | drawFlag(g, Color.BLACK, Color.RED, Color.YELLOW); 30 | 31 | // Hungarian Flag 32 | drawFlag(g, Color.RED, Color.WHITE, Color.GREEN); 33 | } 34 | 35 | public void drawFlag(Graphics g, Color first, Color second, Color third) { 36 | g.setColor(first); 37 | g.fillRect(80, 30, 150, 40); 38 | g.setColor(second); 39 | g.fillRect(80, 70, 150, 40); 40 | g.setColor(third); 41 | g.fillRect(80, 110, 150, 40); 42 | } 43 | } 44 | 45 | @SuppressWarnings("unused") 46 | public static void main(String[] args) { 47 | JFrame testFrame = new FlagViewer(); 48 | } 49 | } -------------------------------------------------------------------------------- /10-GraphicalUserInterfaces/HundredButtons.java: -------------------------------------------------------------------------------- 1 | /*Write a program that shows a square frame filled with 100 buttons labeled 1 to 100. 2 | Nothing needs to happen when you press any of the buttons.*/ 3 | 4 | import javax.swing.JButton; 5 | import javax.swing.JFrame; 6 | import javax.swing.JPanel; 7 | 8 | @SuppressWarnings("serial") 9 | public class HundredButtons extends JFrame { 10 | private static final int FRAME_HEIGHT = 400; 11 | private static final int FRAME_WIDTH = 500; 12 | 13 | private JPanel panel; 14 | 15 | public HundredButtons() { 16 | this.panel = new JPanel(); 17 | this.makeButtons(); 18 | this.add(this.panel); 19 | 20 | this.setSize(FRAME_WIDTH, FRAME_HEIGHT); 21 | this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 22 | this.setVisible(true); 23 | } 24 | 25 | public void makeButtons() { 26 | for (int i = 1; i < 101; i++) { 27 | String buttonLabel = "" + i; 28 | this.panel.add(new JButton(buttonLabel)); 29 | } 30 | } 31 | 32 | @SuppressWarnings("unused") 33 | public static void main(String[] args) { 34 | JFrame frame = new HundredButtons(); 35 | } 36 | } -------------------------------------------------------------------------------- /10-GraphicalUserInterfaces/NameViewer.java: -------------------------------------------------------------------------------- 1 | /*Write a graphics program that draws your name in red, contained inside a blue 2 | rect­angle. Provide a class NameViewer and a class NameComponent.*/ 3 | 4 | import java.awt.Color; 5 | import java.awt.Graphics; 6 | 7 | import javax.swing.JComponent; 8 | import javax.swing.JFrame; 9 | 10 | @SuppressWarnings("serial") 11 | public class NameViewer extends JFrame { 12 | private final static int FRAME_WIDTH = 150; 13 | private final static int FRAME_HEIGHT = 150; 14 | private JComponent nameComponent; 15 | 16 | public NameViewer() { 17 | this.nameComponent = new NameComponent(); 18 | this.add(this.nameComponent); 19 | this.setSize(FRAME_WIDTH, FRAME_HEIGHT); 20 | this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 21 | this.setVisible(true); 22 | } 23 | 24 | class NameComponent extends JComponent { 25 | @Override 26 | public void paintComponent(Graphics g) { 27 | g.setColor(Color.BLUE); 28 | g.fillRect(0, 0, 150, 150); 29 | g.setColor(Color.RED); 30 | g.drawString("Stilyan", 50, 50); 31 | } 32 | } 33 | 34 | @SuppressWarnings("unused") 35 | public static void main(String[] args) { 36 | JFrame testFrame = new NameViewer(); 37 | } 38 | } -------------------------------------------------------------------------------- /10-GraphicalUserInterfaces/TwoSquareViewer.java: -------------------------------------------------------------------------------- 1 | /*Write a program that draws two solid squares: one in pink and one in purple. Use 2 | a standard color for one of them and a custom color for the other. Provide a class 3 | TwoSquareViewer and a class TwoSquareComponent .*/ 4 | 5 | import java.awt.Color; 6 | import java.awt.Graphics; 7 | 8 | import javax.swing.JComponent; 9 | import javax.swing.JFrame; 10 | 11 | @SuppressWarnings("serial") 12 | public class TwoSquareViewer extends JFrame { 13 | private final static int FRAME_WIDTH = 300; 14 | private final static int FRAME_HEIGHT = 300; 15 | private JComponent twoSquareComponent; 16 | 17 | public TwoSquareViewer() { 18 | this.twoSquareComponent = new TwoSquareComponent(); 19 | this.add(this.twoSquareComponent); 20 | this.setSize(FRAME_WIDTH, FRAME_HEIGHT); 21 | this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 22 | this.setVisible(true); 23 | } 24 | 25 | class TwoSquareComponent extends JComponent { 26 | @Override 27 | public void paintComponent(Graphics g) { 28 | g.setColor(Color.PINK); 29 | g.fillRect(20, 20, 100, 100); 30 | 31 | Color purple = new Color(128, 0, 128); 32 | g.setColor(purple); 33 | g.fillRect(150, 150, 100, 100); 34 | } 35 | } 36 | 37 | @SuppressWarnings("unused") 38 | public static void main(String[] args) { 39 | JFrame testFrame = new TwoSquareViewer(); 40 | } 41 | } -------------------------------------------------------------------------------- /12-ObjectOrientedDesign/invoice/Address.java: -------------------------------------------------------------------------------- 1 | package invoice; 2 | 3 | public class Address { 4 | private String name; 5 | private String street; 6 | private String city; 7 | private String state; 8 | private String zip; 9 | 10 | public Address(String name, String street, String city, String state, String zip) { 11 | this.name = name; 12 | this.street = street; 13 | this.city = city; 14 | this.state = state; 15 | this.zip = zip; 16 | } 17 | 18 | public String format() { 19 | String address= String.format("%s\n%s\n%s\n%s\n%s\n", this.name, this.street, this.city, this.state, this.zip); 20 | 21 | return address; 22 | } 23 | } -------------------------------------------------------------------------------- /12-ObjectOrientedDesign/invoice/Invoice.java: -------------------------------------------------------------------------------- 1 | package invoice; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class Invoice { 6 | private Address billingAddress; 7 | private ArrayList items; 8 | 9 | public Invoice(Address anAddress) { 10 | this.items = new ArrayList(); 11 | this.billingAddress = anAddress; 12 | } 13 | 14 | public void add(Product product, int quantity) { 15 | LineItem item = new LineItem(product, quantity); 16 | this.items.add(item); 17 | } 18 | 19 | public String format() { 20 | String invoice = " I N V O I C E\n\n"; 21 | invoice += billingAddress.format(); 22 | invoice += String.format("\n\n%-30s%8s%5s%8s\n", "Description", "Price", "Qty", "Total"); 23 | 24 | for (LineItem item : this.items) { 25 | invoice += item.format() + "\n"; 26 | } 27 | 28 | invoice += String.format("\nAMOUNT DUE: $%8.2f", getAmountDue()); 29 | 30 | return invoice; 31 | } 32 | 33 | private double getAmountDue() { 34 | double amountDue = 0; 35 | 36 | for (LineItem item : this.items) { 37 | amountDue = amountDue + item.getTotalPrice(); 38 | } 39 | 40 | return amountDue; 41 | } 42 | } -------------------------------------------------------------------------------- /12-ObjectOrientedDesign/invoice/InvoicePrinter.java: -------------------------------------------------------------------------------- 1 | package invoice; 2 | 3 | public class InvoicePrinter { 4 | public static void main(String[] args) 5 | { 6 | Address kennyAddress = new Address("Kenny Chapman", "500 Broadway Street", "San Diego", "CA", "98765"); 7 | Invoice kennyInvoice = new Invoice(kennyAddress); 8 | kennyInvoice.add(new Product("Microwave", 29.95), 3); 9 | kennyInvoice.add(new Product("Chair", 24.95), 1); 10 | kennyInvoice.add(new Product("Faith", 19.99), 2); 11 | 12 | System.out.println(kennyInvoice.format()); 13 | } 14 | } -------------------------------------------------------------------------------- /12-ObjectOrientedDesign/invoice/LineItem.java: -------------------------------------------------------------------------------- 1 | package invoice; 2 | 3 | public class LineItem { 4 | private int quantity; 5 | private Product product; 6 | 7 | public LineItem(Product product, int quantity) { 8 | this.product = product; 9 | this.quantity = quantity; 10 | } 11 | 12 | public double getTotalPrice() { 13 | return this.product.getPrice() * quantity; 14 | } 15 | 16 | public String format() { 17 | String productDescription = this.product.getDescription(); 18 | double productPrice = this.product.getPrice(); 19 | double totalPrice = this.getTotalPrice(); 20 | String product = String.format("%-30s%8.2f%5d%8.2f", productDescription, productPrice, this.quantity, totalPrice); 21 | 22 | return product; 23 | } 24 | } -------------------------------------------------------------------------------- /12-ObjectOrientedDesign/invoice/Product.java: -------------------------------------------------------------------------------- 1 | package invoice; 2 | 3 | public class Product { 4 | private String description; 5 | private double price; 6 | 7 | public Product(String aDescription, double aPrice) { 8 | description = aDescription; 9 | price = aPrice; 10 | } 11 | 12 | public String getDescription() { 13 | return description; 14 | } 15 | 16 | public double getPrice() { 17 | return price; 18 | } 19 | } -------------------------------------------------------------------------------- /12-ObjectOrientedDesign/tictactoe/GameViewer.java: -------------------------------------------------------------------------------- 1 | package tictactoe; 2 | 3 | import javax.swing.JFrame; 4 | 5 | public class GameViewer { 6 | @SuppressWarnings("unused") 7 | public static void main(String[] args) { 8 | JFrame frame = new GameFrame(); 9 | } 10 | } -------------------------------------------------------------------------------- /12-ObjectOrientedDesign/tictactoe/tic-tac-toe-o.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yangchenhao/Big-Java-Late-Objects/4813343a677134b4864737a2277bc780a1b51854/12-ObjectOrientedDesign/tictactoe/tic-tac-toe-o.png -------------------------------------------------------------------------------- /12-ObjectOrientedDesign/tictactoe/tic-tac-toe-x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yangchenhao/Big-Java-Late-Objects/4813343a677134b4864737a2277bc780a1b51854/12-ObjectOrientedDesign/tictactoe/tic-tac-toe-x.png -------------------------------------------------------------------------------- /13-Recursion/eightqueens/EightQueens.java: -------------------------------------------------------------------------------- 1 | package eightqueens; 2 | 3 | public class EightQueens { 4 | public static void solve(PartialSolution input) { 5 | int exam = input.examine(); 6 | 7 | if (exam == PartialSolution.ACCEPT) { 8 | System.out.println(input); 9 | } else if (exam != PartialSolution.ABANDON) { 10 | for (PartialSolution p : input.extend()) { 11 | solve(p); 12 | } 13 | } 14 | } 15 | 16 | public static void main(String[] args) { 17 | solve(new PartialSolution(0)); 18 | } 19 | } -------------------------------------------------------------------------------- /13-Recursion/eightqueens/PartialSolution.java: -------------------------------------------------------------------------------- 1 | package eightqueens; 2 | 3 | import java.util.Arrays; 4 | 5 | public class PartialSolution { 6 | private static final int NQUEENS = 8; 7 | public static final int ACCEPT = 1; 8 | public static final int ABANDON = 2; 9 | public static final int CONTINUE = 3; 10 | 11 | private Queen[] queens; 12 | 13 | public PartialSolution(int size) { 14 | this.queens = new Queen[size]; 15 | } 16 | 17 | public int examine() { 18 | for (int i = 0; i < this.queens.length; i++) { 19 | for (int j = i + 1; j < this.queens.length; j++) { 20 | if (this.queens[i].attacks(this.queens[j])) { 21 | return ABANDON; 22 | } 23 | } 24 | } 25 | 26 | if (this.queens.length == NQUEENS) { 27 | return ACCEPT; 28 | } else { 29 | return CONTINUE; 30 | } 31 | } 32 | 33 | public PartialSolution[] extend() { 34 | PartialSolution[] result = new PartialSolution[NQUEENS]; 35 | 36 | for (int i = 0; i < result.length; i++) { 37 | int size = this.queens.length; 38 | result[i] = new PartialSolution(size + 1); 39 | 40 | for (int j = 0; j < size; j++) { 41 | result[i].queens[j] = this.queens[j]; 42 | } 43 | 44 | result[i].queens[size] = new Queen(size, i); 45 | } 46 | 47 | return result; 48 | } 49 | 50 | @Override 51 | public String toString() { 52 | return Arrays.toString(this.queens); 53 | } 54 | } -------------------------------------------------------------------------------- /13-Recursion/eightqueens/Queen.java: -------------------------------------------------------------------------------- 1 | package eightqueens; 2 | 3 | public class Queen { 4 | private int row; 5 | private int column; 6 | 7 | public Queen(int row, int column) { 8 | this.row = row; 9 | this.column = column; 10 | } 11 | 12 | public boolean attacks(Queen other) { 13 | return this.row == other.row || this.column == other.column || 14 | Math.abs(this.row - other.row) == Math.abs(this.column - other.column); 15 | } 16 | 17 | @Override 18 | public String toString() { 19 | return "" + "abcdefgh".charAt(this.column) + (this.row + 1); 20 | } 21 | } -------------------------------------------------------------------------------- /13-Recursion/expressions/ExpressionCalculator.java: -------------------------------------------------------------------------------- 1 | package expressions; 2 | 3 | import java.util.Scanner; 4 | 5 | public class ExpressionCalculator { 6 | public static void main(String[] args) { 7 | Scanner consoleIn = new Scanner(System.in); 8 | System.out.println("Expression: "); 9 | String input = consoleIn.nextLine(); 10 | consoleIn.close(); 11 | 12 | Evaluator evaluator = new Evaluator(input); 13 | int value = evaluator.getExpressionValue(); 14 | System.out.println(input + " = " + value); 15 | } 16 | } -------------------------------------------------------------------------------- /13-Recursion/expressions/ExpressionTokenizer.java: -------------------------------------------------------------------------------- 1 | package expressions; 2 | 3 | public class ExpressionTokenizer { 4 | private String input; 5 | private int start; 6 | private int end; 7 | 8 | public ExpressionTokenizer(String input) { 9 | this.input = input; 10 | this.start = 0; 11 | this.end = 0; 12 | this.nextToken(); 13 | } 14 | 15 | public String peekToken() { 16 | if (this.start >= this.input.length()) { 17 | return null; 18 | } else { 19 | return this.input.substring(this.start, this.end); 20 | } 21 | } 22 | 23 | public String nextToken() { 24 | String r = this.peekToken(); 25 | this.start = this.end; 26 | 27 | if (this.start >= this.input.length()) { 28 | return r; 29 | } 30 | 31 | if (Character.isDigit(this.input.charAt(this.start))) { 32 | this.end = this.start + 1; 33 | 34 | while (this.end < this.input.length() && Character.isDigit(this.input.charAt(this.end))) { 35 | this.end += 1; 36 | } 37 | } else { 38 | this.end = this.start + 1; 39 | } 40 | 41 | return r; 42 | } 43 | } -------------------------------------------------------------------------------- /13-Recursion/tasks/AreaOfPolygon.java: -------------------------------------------------------------------------------- 1 | /*Using recursion, compute the area of a polygon.*/ 2 | package tasks; 3 | 4 | public class AreaOfPolygon { 5 | 6 | public static double calculateArea(int[] x, int[] y) { 7 | return calculateArea(x, y, 1, 0); 8 | } 9 | 10 | public static double calculateArea(int[] x, int[] y, int indexOfTriangle, int area) { 11 | if (indexOfTriangle == x.length - 2 && indexOfTriangle == y.length - 2) { 12 | return area; 13 | } else { 14 | double firstPart = x[indexOfTriangle] * y[indexOfTriangle + 1] - 15 | y[indexOfTriangle] * x[indexOfTriangle + 1]; 16 | double secondPart = x[indexOfTriangle + 1] * y[indexOfTriangle + 2] - 17 | y[indexOfTriangle + 1] * x[indexOfTriangle + 2]; 18 | double thirdPart = x[indexOfTriangle + 2] * y[indexOfTriangle ] - 19 | y[indexOfTriangle + 2] * x[indexOfTriangle]; 20 | 21 | area += Math.abs(firstPart + secondPart + thirdPart) / 2; 22 | 23 | return calculateArea(x, y, indexOfTriangle + 1, area); 24 | } 25 | } 26 | 27 | public static void main(String[] args) { 28 | int[] x = { 2, 7, 3, 6, 4, 9 }; 29 | int[] y = { 3, 4, 5, 1, 7, 3 }; 30 | 31 | double area = calculateArea(x, y); 32 | System.out.printf("Area of polygon is: %.2f", area); 33 | } 34 | } -------------------------------------------------------------------------------- /13-Recursion/tasks/Finder.java: -------------------------------------------------------------------------------- 1 | /*Use recursion to implement a method 2 | public static boolean find(String text, String str) 3 | that tests whether a given text contains a string. For example, 4 | find("Mississippi", "sip") returns true. 5 | Hint: If the text starts with the string you want to match, then you are done. If not, 6 | consider the text that you obtain by removing the first character.*/ 7 | 8 | package tasks; 9 | 10 | public class Finder { 11 | public static boolean find(String text, String str) { 12 | if (text.length() < str.length()) { 13 | return false; 14 | } else if (text.substring(0, str.length()).equals(str)) { 15 | return true; 16 | } else { 17 | return find(text.substring(1), str); 18 | } 19 | } 20 | 21 | public static void main(String[] args) { 22 | boolean isFound = find("Mississippi", "sip"); 23 | System.out.printf("Word is finded? %s", isFound); 24 | } 25 | } -------------------------------------------------------------------------------- /13-Recursion/tasks/IndexOf.java: -------------------------------------------------------------------------------- 1 | /*Use recursion to implement a method 2 | public static int indexOf(String text, String str) 3 | that returns the starting position of the first substring of the text that matches str . 4 | Return –1 if str is not a substring of the text. 5 | For example, s.indexOf("Mississippi", "sip") returns 6. 6 | Hint: This is a bit trickier than Exercise P13.6, because you must keep track of how 7 | far the match is from the beginning of the text. Make that value a parameter variable 8 | of a helper method.*/ 9 | package tasks; 10 | 11 | public class IndexOf { 12 | public static int indexOf(String text, String str) { 13 | return indexOf(text, str, 0); 14 | } 15 | 16 | public static int indexOf(String text, String str, int startIndex) { 17 | if (text.length() < str.length()) { 18 | return -1; 19 | } else if (text.substring(0, str.length()).equals(str)) { 20 | return startIndex; 21 | } else { 22 | return indexOf(text.substring(1), str, startIndex + 1); 23 | } 24 | } 25 | 26 | public static void main(String[] args) { 27 | int index = indexOf("Mississippi", "sip"); 28 | if (index == -1) { 29 | System.out.println("This string is not substring of the text!"); 30 | } else if (index != -1) { 31 | System.out.printf("Starting index of substring is: %d", index); 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /13-Recursion/tasks/LargestElementFinder.java: -------------------------------------------------------------------------------- 1 | /*Using recursion, find the largest element in an array. 2 | Hint: Find the largest element in the subset containing all but the last element. 3 | Then compare that maxi­mum to the value of the last element.*/ 4 | package tasks; 5 | 6 | public class LargestElementFinder { 7 | 8 | public static int findLargestElement(int[] array) { 9 | return findLargestElement(array, array.length - 1, Integer.MIN_VALUE); 10 | } 11 | 12 | public static int findLargestElement(int[] array, int lastIndex, int currentLargest) { 13 | if (lastIndex >= 0) { 14 | int lastElement = array[lastIndex]; 15 | 16 | if (lastElement > currentLargest) { 17 | currentLargest = lastElement; 18 | } 19 | 20 | return findLargestElement(array, lastIndex - 1, currentLargest); 21 | } else { 22 | return currentLargest; 23 | } 24 | } 25 | 26 | public static void main(String[] args) { 27 | int[] array = { 1, 2, 4444, 24, 52, 555, 66 }; 28 | int largestElement = findLargestElement(array); 29 | System.out.printf("Largest element in array is: %d", largestElement); 30 | } 31 | } -------------------------------------------------------------------------------- /13-Recursion/tasks/Rectangle.java: -------------------------------------------------------------------------------- 1 | /*Given a class Rectangle with instance variables width and height, 2 | provide a recursive getArea method. Construct a rectangle whose width is 3 | one less than the original and call its getArea method.*/ 4 | 5 | package tasks; 6 | 7 | public class Rectangle { 8 | private double width; 9 | private double height; 10 | 11 | public Rectangle(double width, double height) { 12 | this.width = width; 13 | this.height = height; 14 | } 15 | 16 | public double getArea() { 17 | if (this.width == 1) { 18 | return height; 19 | } else { 20 | Rectangle rectangle = new Rectangle(this.width - 1, this.height); 21 | return this.height + rectangle.getArea(); 22 | } 23 | } 24 | 25 | public static void main(String[] args) { 26 | Rectangle rectangle = new Rectangle(4, 5); 27 | System.out.printf("Area of rectangle is: %.2f", rectangle.getArea()); 28 | } 29 | } -------------------------------------------------------------------------------- /13-Recursion/tasks/Square.java: -------------------------------------------------------------------------------- 1 | /*Given a class Square with instance variable width , provide a recursive getArea method. 2 | Construct a square whose width is one less than the original and call its getArea 3 | method.*/ 4 | package tasks; 5 | 6 | public class Square { 7 | private double width; 8 | 9 | public Square(double width) { 10 | this.width = width; 11 | } 12 | 13 | public double getArea() { 14 | if (this.width == 1) { 15 | return 1; 16 | } else { 17 | Square square = new Square(this.width - 1); 18 | return square.getArea() + 2 * this.width - 1; 19 | } 20 | } 21 | 22 | public static void main(String[] args) { 23 | Square square = new Square(2); 24 | System.out.printf("Area of square is: %.2f", square.getArea()); 25 | } 26 | } -------------------------------------------------------------------------------- /13-Recursion/tasks/StringReverser.java: -------------------------------------------------------------------------------- 1 | /*Write a recursive method String reverse(String text) that reverses a string. For 2 | example, reverse("Hello!") returns the string "!olleH" . Implement a recursive solution 3 | by removing the first character, reversing the remaining text, and combining the two.*/ 4 | 5 | package tasks; 6 | 7 | public class StringReverser { 8 | public static String reverse(String text) { 9 | if (text.length() == 1) { 10 | return text; 11 | } else { 12 | return reverse(text.substring(1)) + text.substring(0, 1); 13 | } 14 | } 15 | 16 | public static void main(String[] args) { 17 | String newString = StringReverser.reverse("Hello!"); 18 | System.out.printf("Reversed string is: %s", newString); 19 | } 20 | } -------------------------------------------------------------------------------- /13-Recursion/tasks/SubstringGenerator.java: -------------------------------------------------------------------------------- 1 | /*Implement a SubstringGenerator that generates all substrings of a string. For example, 2 | the substrings of the string "rum" are the seven strings 3 | "r", "ru", "rum", "u", "um", "m", "" 4 | Hint: First enumerate all substrings that start with the first character. There are n of 5 | them if the string has length n. Then enumerate the substrings of the string that you 6 | obtain by removing the first character.*/ 7 | 8 | package tasks; 9 | 10 | public class SubstringGenerator { 11 | public static void generate(String text) { 12 | generate(text, 0, 0); 13 | } 14 | 15 | public static void generate(String text, int letterIndex, int wordIndex) { 16 | if (letterIndex < text.length()) { 17 | if (wordIndex < text.length()) { 18 | wordIndex++; 19 | System.out.println(text.substring(letterIndex, wordIndex)); 20 | } else { 21 | letterIndex++; 22 | wordIndex = letterIndex; 23 | } 24 | 25 | generate(text, letterIndex, wordIndex); 26 | } else { 27 | System.out.println("\"\""); 28 | return; 29 | } 30 | } 31 | 32 | public static void main(String[] args) { 33 | SubstringGenerator.generate("rum"); 34 | } 35 | } -------------------------------------------------------------------------------- /13-Recursion/tasks/Sum.java: -------------------------------------------------------------------------------- 1 | /*Using recursion, compute the sum of all values in an array.*/ 2 | package tasks; 3 | 4 | public class Sum { 5 | public static int sum(int[] array) { 6 | return sum(array, 0, 0); 7 | } 8 | 9 | public static int sum(int[] array, int currentIndex, int currentSum) { 10 | if (currentIndex == array.length) { 11 | return currentSum; 12 | } else { 13 | currentSum += array[currentIndex]; 14 | return sum(array, currentIndex + 1, currentSum); 15 | } 16 | } 17 | 18 | public static void main(String[] args) { 19 | int[] array = { 10, 20, 30, 5, 15 }; 20 | int sum = sum(array); 21 | System.out.printf("Sum of elements in array is: %d", sum); 22 | } 23 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Big-Java-Late-Objects 2 | 3 | ## Description 4 | 5 | Big Java: Late Objects is a comprehensive introduction to Java and computer programming, which focuses on the principles of programming, software engineering, and effective learning. It is designed for a two-semester first course in programming for computer science students. 6 | 7 | All solutions from the book written by Cay Horstmann! 8 | 9 | http://eu.wiley.com/WileyCDA/WileyTitle/productCd-EHEP002041.html
10 | http://horstmann.com/bjlo.html 11 | --------------------------------------------------------------------------------