COMPUTER PROGRAMMING 1 (JAVA) INTENSIVE REVISION NOTES Collected and summarize by : Layla Jaffer Bader ITCS 111 / 113 / 101 / 103 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Dear Computer Programming 1 (JAVA) Students, You will find many ideas and example in this note. It's very beneficial for you but still you need to study from the book and your instructor notes as these note alone are not enough. I worked very hard to make it look like this but still if you find any mistake please forgive me. Don't forget me in your duaa .. Layla Jaffer Bader .. 1 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Contents .. Chapter 1 – Introduction to Computers and Java............................................................................ 3 Chapter 2 - Basic Computation .......................................................................................................... 9 Chapter 3 - Flow of Control: Branching .......................................................................................... 25 Chapter 4 - Flow of Control: Loops ................................................................................................. 42 Graphics supplement ......................................................................................................................... 81 Chapter 5 - Defining Classes And Methods ..................................................................................... 94 Output Questions .............................................................................................................................. 119 2 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Chapter 1 – Introduction to Computers and Java Multiple-Choice Questions .. Hardware and Software 1. This part of the computer fetches instructions, carries out the operations commanded by the instructions, and produces some outcome or resultant information. (a) Memory (c) secondary storage (b) CPU (d) input device 2. A byte is made up of eight _____________. (a) CPUs (c) variables (b) addresses (d) bits 3. Each byte in the memory is assigned a unique _____________. (a) address (c) variable (b) CPU (d) bit 4. This type of memory can hold data for long periods of time—even when there is no power to the computer. (a) RAM (c) secondary storage (b) primary storage (d) CPU storage 5. What unit of storage is used to represent 109 bytes? (a) kilobyte (c) Gigabyte (b) Terabyte (d) Megabyte 3 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 6. Memory stores _____________. (a) The operating system (c) Application programs (b) The data processed by the application program (d) All of the above 7. Bit is short for _____________. (a) Binary system (c) Digital byte (b) Binary unit (d) Binary digit Programs, Programming Languages, Compilers, and Interpreters 1. The most basic circuitry-level computer language, which consists of 1 and 0, is ______________. (a) a high-level language (c) Java (b) machine language (d) C++ 2. Languages that let you use a vocabulary of descriptive terms, such as read, write, or add, are known as ______________ languages. (a) high-level (b) machine (c) procedural (d) object-oriented 3. A ______________ translates high-level language statements into machine code. (a) programmer (c) compiler (b) syntax detector (d) class loader 4. The input program to a complier or interpreter is called _____________. (a) Object code (c) source code (b) Byte code (d) Assembly language code 4 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 5. A Java program is portable means it _____________. (a) Can run on any machine (c) Can read from as well as write to any machine (b) Can write on any machine (d) All of the above Java Bytecode, Class Loader, Applications and Applets 1. Computers process data under the control of sets of instructions called ______________ . (a) Hardware (c) Output (b) Input (d) Programs 2. The file produced by the Java compiler contains _____________ that are executed by the Java Virtual Machine. (a) Bits (c) Bytecodes (b) Bytes (d) High-level codes 3. Java programs can be executed in computer after (a) converting them to bytecode (c) can be executed directly (b) converting them into machine code (d) None of the above 4. The process of instructing the computer to solve a problem is called _____________. (a) Compiling (c) Processing (b) Programming (d) Controlling 5. Java is a ________________ programming language. (a) Low-level (c) Neural (b) High-level (d) Natural 5 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 6. The information stored in _____________ typically is volatile (i.e. it disappears when you shut down your computer). (a) Hard disks (c) Main memory (b) Cloud memory (d) Auxiliary memory 7. When a Java program is compiled, the file produced by the compiler ends with the __________ file extension. (a) .java (c) .cpp (b) .class (d) .exe 8. _____________ is a type of program that is designed to be transmitted over the Internet and run in a Web browser (a) Application (c) Machine language (b) Applet (d) Source code 9. JVM stands for _____________. (a) Java Variable Machine (c) Java Virtual Method (b) Java Variable Method (d) Java Virtual Machine Object-Oriented Programming 1. _____________ is not an Object-Oriented design principle (a) Inheritance (c) Ploymorphism (b) Encapsulation (d) Sequence 2. Inheritance means _____________. (a) Many Java methods (c) Information is shared between classes (b) Information is put in one place with methods (d) Write variable names correctly 6 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 3. Encapsulation means _____________. (a) Methods with the same name but different functionality (c) Information is shared between classes (b) Information hiding (d) Writing statements after each other 4. Polymorphism means _____________. (a) Many forms (c) Information defined in one class can be used by another class (b) Part of a class hidden and another is visible (d) Writing a Java program Algorithms, Testing and Debugging and Software Reuse 1. An algorithm is _____________. (a) a set of directions for solving a problem (c) a programming language (b) a source program (d) a type of main memory 2. Pseudocode is (a) used to write an algorithm (c) used to generate a byte code (b) a machine language (d) used to test a program 3. A syntax error _____________. (a) is a grammatical mistake in your program (c) cannot be discovered (b) is the same as a logical error (d) cannot be corrected 7 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 4. Runtime errors are _____________. (a) Grammatical mistakes in a program (c) Errors that are detected when your program is running, but not during compilation (b) Errors that are detected during compilation (d) Errors that do not stop the program from running when they occur. 5. The rules of a programming language constitute its _____________. (a) objects (c) format (b) logic (d) syntax 6. An error in a program is called a _____________. (a) mistake (c) loophole (b) bug (d) virus 7. Reused components _____________. (a) Are likely better tested piece of software, and more reliable than newly created software (c) Should not be used to produce new programs. (b) Does not save time and money (d) Are garbage collection data components 8 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Chapter 2 - Basic Computation 1. Write a program that converts a distance measure from inches to cents. Note that one inch is equal to 2.54 centimeters? import java.util.Scanner; public class InchesToCentimreter { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); double inches , cm ; System.out.println("Enter a velue in inches: "); inches = kbd.nextDouble(); cm = inches * 2.54 ; System.out.println("The value of " + inches + " centimeter"); System.out.println("is equal to " + cm); Output Enter a velue in inches: 5.6 The value of 5.6 centimeter is equal to 14.223999999999998 } } Example 1 (Sum Of Tow Integers) import java.util.Scanner; public class SumOfTwoIntegers { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); // Definition of the program variables int num1 , num2 , result ; // read the two integers // The below message is called "prompt" System.out.println("Enter two integers: "); num1 = kbd.nextInt(); num2 = kbd.nextInt(); result = num1 + num2 ; // print the result System.out.print("\nThe sum of " + num1 + " and " + num2); System.out.println(" is " + result); } } Output Enter two integers: 56 78 The sum of 56 and 78 is 134 9 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 2. The area of a triangle is computed by taking half the product of its base and height Write a program that reads the base and height of a triangle and displays the area. import java.util.Scanner; public class P2answer2 { public static void main (String [] args) { double base , height , area ; Scanner kbd = new Scanner(System.in); //prompt System.out.println("Enter base and height of traingle :"); base = kbd.nextDouble(); height = kbd.nextDouble(); area = 0.5 * base * height; Output Enter base and height of traingle : 67 The area is 21.0 System.out.println("The area is " + area ); } } Example 2 (Average Of Two Integers) import java.util.Scanner; public class AverageOfTwoIntegers { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); int num1 , num2 ; double avg ; System.out.println("Please enter two integers: "); num1 = kbd.nextInt(); num2 = kbd.nextInt(); avg = (double)(num1+num2)/2; System.out.println("The average is: " + avg); } } Output Please enter two integers: 54 The average is: 4.5 10 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Example 3 (Average Of Three Numbers) import java.util.Scanner; public class AverageOfThreeNumbers { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); int num1, num2, num3; double average; //prompt the user for input System.out.print("Enter three integers: "); num1 = kbd.nextInt(); num2 = kbd.nextInt(); num3 = kbd.nextInt(); Output Please enter two integers: 545 The average is: 4.6 average = (double) (num1+num2+num3) / 3; System.out.println("The average is " + average); } } Example 4 (Adding Tow Numbers) import java.util.Scanner; public class AddingTwoNumbers { public static void main(String[] args){ Scanner keyboard = new Scanner(System.in); int first, second, sum; System.out.println("Enter the first number: "); first = keyboard.nextInt(); System.out.println("Enter the second number: "); second = keyboard.nextInt();; sum = first + second; Output Enter the first number: 7 Enter the second number: 10 The sum of 7 and 10 is 17 System.out.println("The sum of " + first + " and " + second + " is " + sum); } } 11 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Example 5 (Type Casting) public class TypeCasting { public static void main(String[] args) Output { double distance ; distance = 9.7 ; int points ; points = (int) distance; System.out.println("Points = " + points); Output Points = 9 } } Example 6 (Circle Area) import java.util.Scanner; public class CircleArea { public static final double PI = 3.14159265; public static void main(String[] args) { Scanner kbd = new Scanner(System.in); double area , radius ; System.out.println("Please enter the radius: "); radius = kbd.nextDouble(); Output Please enter the radius: 3.6 The area is: 40.71504074400001 area = PI * radius * radius ; System.out.println("The area is: " + area); } } 12 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 3.Students are awarded points toward their grades based upon the addition of the average of three quizzes (Q1, Q2, Q3), the midterm exam (MT ), and the final exam (FINAL). Quizzes are marked out of 5, the midterm is out of 30, and the final is out of 70. Compute the total points using a Java program and print the result out of 100 according to the following percentages: Quizzes: 25%, Midterm: 35%, and Final: 40%. import java.util.Scanner; public class BasicProblem_3 { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); Output double Q1 , Q2 , Q3 , Quizzes , MT , Final , total ; System.out.println("Enter Quizzes Marks: " ); Q1 = kbd.nextDouble(); Q2 = kbd.nextDouble(); Q3 = kbd.nextDouble(); Enter Quizzes Marks: Quizzes = Q1 + Q2 + Q3; Quizzes = Quizzes * 25 / 15 ; Enter MT Mark: System.out.println("Enter MT Mark: "); MT = kbd.nextDouble(); 555 30 Enter Final Mark: MT = MT * 35 / 30 ; 70 System.out.println("Enter Final Mark: "); Final = kbd.nextDouble(); The total is: 100.0 Final = Final * 40 / 70 ; total = Quizzes + MT + Final ; System.out.println("The total is: " + total); } } 13 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 4. Write a program that reads a student name followed by his/her id. The program should then display on screen the student’s name followed by his/her academic year. For example, the academic year for the id 20102323 is 2010. import java.util.Scanner; public class AcademicYear { public static void main(String[] args) { //create input object Scanner kbd = new Scanner(System.in); String name; int id, year; System.out.print("Enter your name: "); name = kbd.nextLine(); System.out.print("Enter your id: "); id = kbd.nextInt(); Output Enter your name: layla Enter your id: 20102323 The academic year for layla is 2010 year = id / 10000; System.out.println("The academic year for "); System.out.println(name + " is " + year); } } 14 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 5.Write a program that reads three floating point numbers N1, N2, and N3 from the user. It is required to find and print the value of the following formula: import java.util.Scanner; public class BasicProblem_5 { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); double N1 , N2 , N3 , value ; System.out.println("Enter three floating point numbers: "); N1 = kbd.nextFloat(); N2 = kbd.nextFloat(); N3 = kbd.nextFloat(); value = N1 + (N1 * N2 / 4) - N3 ; Output Enter three floating point numbers: 4.5 2.6 1.1 The value is: 6.3249998688697815 System.out.println("The value is: " + value); } } 15 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 6.One large chemical company pays its salespeople on a commission basis. The salespeople receive BD. 75/600 per week plus 9% of their gross sales for that week. For example, a salesperson who sells BD. 1890/— worth of chemicals in a week receives BD. 75/600 plus 9% of 1890/—, or a total of 75/600 + 170/100 = 245/700. Develop a program that will input each salesperson’s gross sales for last week and will calculate and display that salesperson’s earnings? import java.util.Scanner; public class BasicProblem6 { public static void main(String[] args){ Scanner kbd = new Scanner(System.in); double salesAmount, salary; System.out.print("Enter your sales amount: "); salesAmount = kbd.nextDouble(); Output Enter your sales amount: 25.4 salary = 75.6 + salesAmount * 0.09; System.out.println(); System.out.println("The total earnings is " + salary); The total earnings is 77.886 } } 16 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 7.Write a program that reads two currency codes, exchange rate from first currency to second and the amount of money to be converted. Your program should display the converted amount for each currency using the following equations: First Currency Amount = Currency Amount × Exchange Rate Second Currency Amount = Currenc Amount / Exchange Rate Format the output to 4 decimal places. Sample Input/Output Enter currency codes: USD BD Enter Exchange rate: 0.3774 Enter the amount: 125.0 USD 125.0000 = BD 47.1750 BD 125.0000 = USD 331.2136 import java.util.Scanner; class BasicProblem_7 { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); String FirstCurrencyCode , SecondCurrencyCode; double theAmount , ExchangeRate ; System.out.print("Enter currency codes: "); FirstCurrencyCode = kbd.next(); SecondCurrencyCode = kbd.next(); System.out.print("Enter Exchange rate: "); ExchangeRate = kbd.nextDouble(); System.out.print("Enter the amount: "); theAmount = kbd.nextDouble(); double FirstAmount = theAmount * ExchangeRate ; double SecondAmount = theAmount / ExchangeRate; System.out.println(); System.out.println(FirstCurrencyCode + " " + theAmount + " = " + SecondCurrencyCode + " " + FirstAmount); System.out.println(SecondCurrencyCode + " " + theAmount + " = " + FirstCurrencyCode + " " + SecondAmount); } } 17 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 8.Write a Java program that will perform some calculations regarding a cyclist coasting on a road. The program will ask the user to enter the cyclist’s initial speed Vinitial, the duration (in minutes), and the final speed Vfinal. The program will then calculate the rate of acceleration using the formula: acceleration = (Vfinal − Vinitial) ÷ duration Next, calculate how long it will take for the cyclist to stop (given the initial speed and the calculated acceleration.) The necessary formula is: time = Vinitial ÷ acceleration Display the acceleration and time on screen formatted to the below samples. import java.util.Scanner; public class P8 { public static void main (String []args) { Scanner kbd = new Scanner(System.in); float itiaLS , finaLS , duration ; System.out.println("Enter the intial speed and final speed and duration "); itiaLS = kbd.nextFloat(); finaLS = kbd.nextFloat(); duration = kbd.nextFloat(); double acceleration = ( finaLS - itiaLS ) / duration ; System.out.println(" Accleration = " + acceleration ); double time ; time = itiaLS / acceleration ; System.out.println(time + " minuts to stop "); } } 18 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 9.Write a program that reads from the keyboard the following input: Person Full Name written in a single line. • Person CPR number (9-Digits) written in the next. Your program should find and print on screen the birth year of this person. The birth year can be extracted from the first two digits of the CPR. Assume all persons were born before the year 2000 and after the year 1910. • Sample Input/Output Enter your name: Jassim Ali Ahmed Enter your CPR: 740707573 Jassim Ali Ahmed was born in year 1974 import java.util.Scanner; public class java1 { public static void main(String[] args) { //create input object Scanner kbd = new Scanner(System.in); String name; int cpr, year; System.out.print("Enter your name: "); name = kbd.nextLine(); System.out.print("Enter your CPR : "); cpr = kbd.nextInt(); year = cpr / 10000000; System.out.println(name + " was born in year " + (year+1900)); } } 19 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 11.Write a program that calculates and prints the monthly paycheck for an employee. The net pay is calculated after the following deductions: Medicare/Medicaid Tax: 2.75% • Pension Plan: 6% • Health Insurance: BD. 75 Your program should prompt the user to enter the gross amount and print the net pay. A sample Input/Output is shown below: • Enter gross amount (BD): 650 ---------- Paycheck ----------Gross amount: 650.000 Medicare/Medicaid Tax: 17.875 Pension Plan: 39.000 Health Insurance: 75.000 ------------------------------Net Pay: 518.125 import java.util.Scanner; public class P11 { public static void main(String[] args) { Scanner input = new Scanner(System.in); double grossAmount , medCare , pension , healthInsurance ; System.out.println("Enter gross amount (BD) : "); grossAmount = input.nextDouble(); medCare = grossAmount * 0.0275 ; pension = grossAmount * 0.06 ; healthInsurance = 75.0 ; System.out.println("--------Paycheck------------------"); System.out.printf("%-24s%8.3f%n","Gross Amount:" , grossAmount); System.out.printf("%-24s%8.3f%n","Medicare/Medicaid tax :" , medCare ); System.out.printf("%-24s%8.3f%n","Pension plan :" , pension ); System.out.printf("%-24s%8.3f%n","Health Insurance :" , healthInsurance ); System.out.println("----------------------------------"); System.out.printf("%-24s%8.3f%n","Net Pay :" , (grossAmount-medCare-pension-healthInsurance)); } } 20 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 12.Write a program that reads from the keyboard two integers representing hours and minutes.The program should convert the time (hours and minutes) to seconds. Your program should write the result on screen as shown in the sample I/O below. the sample below: Sample Input/Output Hours? Minutes? 10 15 Time in Seconds = 36900 import java.util.Scanner; public class b11 { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); int hour , minutes , second ; System.out.print("Enter the hour: "); hour = kbd.nextInt(); System.out.print("Enter the minutes: "); minutes = kbd.nextInt(); second = (hour * 60 + minutes ) * 60 ; System.out.println("The seconds is: " + second); } } 21 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Example 7 ( Printf ) import java.util.Scanner; public class PrintfExample { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); // read three numbers double first, second, third; System.out.print("Please enter three numbers: "); first = kbd.nextDouble(); second = kbd.nextDouble(); third = kbd.nextDouble(); Output Please enter three numbers: 2.5 7.6 4.2 The average of 2.500, 7.600, and 4.200 is 4.77 // print the average System.out.printf("The average of %.3f, %.3f, and %.3f is %.2f\n", first, second, third, (first+second+third)/3.0); Number = Number = 71 71 x int num = 71; System.out.printf("Number = %10d\n", num); System.out.printf("Number = %-10dx\n", num); } } Example 8 ( Escape Sequences ) public class EscapeSequences { public static void main(String[] args) { System.out.print("Hello\n\"Every one\"\n" + "The directory is\nc:\\class\\HW1"); } } Output Hello "Every one" The directory is c:\class\HW1 22 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Example 9 (String Processing) public class EX { public static void main(String[] args) { String s = "Hello every one"; System.out.println("The lenght of string is " + s.length()); System.out.println("The char at index 10 is " + s.charAt(10)); System.out.println("The index of \"one\" is " + s.indexOf("every")); //combine tow string -- Concatenation String s1 = s + " in this class"; System.out.println("s1 = " + s1); String s2 = s.concat("in this class "); System.out.println("s2 = " + s2); System.out.println("The index of first e is " + s.indexOf("e")); System.out.println("The index of last e is " + s.indexOf('e')); System.out.println("The string in lower case is " + s.toLowerCase()); System.out.println("The string in upper case is " + s.toUpperCase()); System.out.println("Replace e by o = " + s.replace('e','o')); String s3 = s.substring(6); System.out.println("Substring at 5 is " + s3); String s4 = s.substring(6,11); System.out.println("Substring between 6 and 11 is " + s4); } } Output The lenght of string is 15 The char at index 10 is y The index of "one" is 6 s1 = Hello every one in this class s2 = Hello every onein this class The index of first e is 1 The index of last e is 1 The string in lower case is hello every one The string in upper case is HELLO EVERY ONE Replace e by o = Hollo ovory ono Substring at 5 is every one Example 10 ( Reading Single Character ) Substring between 6 and 11 is every import java.util.Scanner; public class ReadingSingleCharacter { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); System.out.println("Enter A or B: "); char letter = kbd.next().toUpperCase().charAt(0); Output Enter A or B: a System.out.println("You typed " + letter); } } You typed A 23 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Example 11 (String Processing) public class StringProcessing { public static void main(String[] args) { String msg = "Hello"; System.out.println("The message is '" + msg + "'"); System.out.println("char at 1 is " + msg.charAt(1)); System.out.println("char at 4 is " + msg.charAt(4)); // The below statement is commented because the index // is out of bound and it produces a run-time error // System.out.println("char at 15 is " + msg.charAt(15)) System.out.println("The letter 'l' is at index " + msg.indexOf('l')); System.out.println("'He' is at index " + msg.indexOf("He")); System.out.println("'lo' is at index " + msg.indexOf("lo")); System.out.println("'HE' is at index " + msg.indexOf("HE")); System.out.println("'SHE' is at index " + msg.indexOf("SHE")); System.out.println("last index of 'l' is " + msg.lastIndexOf('l')); System.out.println(msg.concat(" everyone")); System.out.println("msg = " + msg); System.out.println("All in uppercase is " + msg.toUpperCase()); System.out.println("msg = " + msg); System.out.println(msg.replace('l', 'L')); Output The message is 'Hello' char at 1 is e char at 4 is o The letter 'l' is at index 2 'He' is at index 0 'lo' is at index 3 'HE' is at index -1 'SHE' is at index -1 last index of 'l' is 3 Hello everyone String uob = "University of Bahrain"; System.out.println(uob.substring(14).toLowerCase()); System.out.println(uob.substring(11,13).toUpperCase()); } } msg = Hello All in uppercase is HELLO msg = Hello HeLLo bahrain OF 24 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Chapter 3 - Flow of Control: Branching Flow Charts Note : The Flow Charts only include in Test 1 not include Test 2 or Final Exam ! This answer is incomplete please draw the flowchart on your own .. import java.util.Scanner; public class PlayGamesFlowchart { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); double age , height ; System.out.println("Please enter age and height: "); age = kbd.nextDouble(); height = kbd.nextDouble(); // age > 5 and height > 120 if (age > 5 && height > 120 ) { System.out.println("Yes , you can play. "); } else { System.out.println("No , you cannot play. "); } Output Please enter age and height: 10 130 Yes , you can play. Output Please enter age and height: 5 100 No , you cannot play. } } 25 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader This answer is incomplete please draw the flowchart on your own .. import java.util.Scanner; public class P2EquilateralTriangle { public static void main (String [] args) { Scanner input = new Scanner(System.in ); double side1 , side2 , side3 ; System.out.println("Please enter three sides of a traingle: "); side1= input.nextDouble(); side2= input.nextDouble(); side3= input.nextDouble(); if (side1 == side2 && side2 == side3) System.out.println("The traingle is Equilateral. "); else System.out.println("The traingle is not Equilateral."); double circumfenence = side1 + side2 + side3 ; System.out.println("The circumfenence is " + circumfenence); } } Output Please enter three sides of a traingle: 344 The triangle is not Equilateral. The circumfenence Outputis 11.0 Please enter three sides of a traingle: 444 The triangle is Equilateral. The circumfenence is 12.0 26 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 4.Write a java program that: (a) (b) Prompts the user to enter from the keyboard the employees Salary in BD. Calculates the Tax as shown in the table below: Salary Range in BD Tax Between 0 and 500 0.05 × Salary More than 500 and less than 1000 0.08 × Salary 1000 or Above 0.09 × Salary Displays the value of Tax. (d) Displays the value of Net Salary = Salary - Tax. Example: If Salary is 600, then Tax is 0.08 × 600 = 48 and Net Salary is 60048 = 552. (c) import java.util.Scanner; public class SalaryProgram { public static void main(String[] args) { Scanner input = new Scanner(System.in); double salary, tax, netSalary; System.out.print("Enter your salary: "); salary = input.nextDouble(); if (salary >=0 && salary <=500) tax = 0.05 * salary; else if (salary > 500 && salary < 1000) tax = 0.08 * salary; else tax = 0.09 * salary; System.out.println("The tax is " + tax); netSalary = salary - tax; System.out.println("Net salary is " + netSalary); Output Enter your salary: 250 The tax is 12.5 Net salary is 237.5 } } 27 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 3.The selling price of an apartment depends on the area of the apartment and the floor number where the apartment is located. Write a Java program that: (a) Prompts the user to enter from the keyboard: • The area by square meter of the apartment. • The floor number where the apartment is located. (b) Calculates the total price of the apartment based on the apartment area and the floor number as shown below: Area (square meter) Price for square meter Up to 150 BD. 500 for each square meter From 151 to 200 BD. 450 for each square meter Over 200 Display apartment not available (c) Display the total price if applicable. Apartment 1: Area 120 in Floor 0, the total price = 120 × 500 = 60,000. Apartment 2: Area 160 in Floor 5, the total price = 160 × 450 = 72,000. import java.util.Scanner; public class QUIZ1 { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); double totalPrice ; int areaSquare , fNumber ; System.out.println("Enter the area square:"); areaSquare = kbd.nextInt(); System.out.println("Enter the floor number:"); fNumber = kbd.nextInt(); if (areaSquare <= 150) { totalPrice = areaSquare * 500; System.out.println("Area " + areaSquare + " in floor " + fNumber + " , total price } else if (areaSquare >= 151 && areaSquare <= 200) { totalPrice = areaSquare * 450; System.out.println("Area " + areaSquare + " in floor " + fNumber + " , total price } else { System.out.println("Display apartment not available"); } } } = " + totalPrice); = " + totalPrice); 28 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Example 1 (Boolean) public class BooleanExamples { public static void main(String[] args) { boolean stop = true; boolean answer; int number = 7; Output Answer is true answer = number == 7; System.out.println("Answer is " + answer); } } public class BooleanExample { public static void main(String[] args) { int number = 7; boolean status = true; System.out.println("The value in condition is " + status); The value in condition is true status = number > 20; System.out.println("The value in condition is " + status); The value in condition is false if (status) System.out.println("Hi"); else System.out.println("Good bye"); Output Good bye } } 29 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader ACE balloon shop sells balloons to customers at 10 fils each. If the customer buys 500 1000 balloons, the price is 8 fils − each. If the customer buys over 1000 balloons, the price is 6 fils each. Write a program that reads the number of balloons to purchase and prints the amount of the bill? 2. import java.util.Scanner; public class sel2 { public static void main(String[] args) { Scanner input = new Scanner(System.in); int balloons ; System.out.println(" How many balloons you would like " + "to purchase ? "); balloons = input.nextInt(); //input validation if (balloons <= 0) { System.out.println(" Invailed input. Buy buy."); //exit the program System.exit(0); } if (balloons > 0 && balloons < 500) System.out.print(" The amount is " + balloons * 10 + " fils." ); else if (balloons >= 500 && balloons <= 1000 ) System.out.println("The amount is " + balloons * 8 + " fils."); else System.out.println("The amount is " + balloons * 6 + " fils."); Output How many balloons you would like to purchase ? 35 The amount is 350 fils. } } 30 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 4.Write a java program that asks the user to input the weight of a canary bird in grams. The program should determine and display a message the category of the bird’s weight according to the following table: Weight Between 50 Grams and 100 Grams (inclusive) Under 50 but above 20 OR above 100 but under 130 All other ranges Category Healthy Critical Endangere d import java.util.Scanner; public class sel4 { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); double weight ; System.out.println("Please enter the bird's weight: "); weight = kbd.nextDouble(); //test for validity of input if (weight <= 0) { System.out.println("Invailed input. Buy buy."); //exit the program System.exit(0); } Output Please enter the bird's weight: 60 Healthy. if (weight >= 50 && weight <= 100) System.out.println("Healthy."); else if ( (weight < 50 && weight > 20 ) || (weight < 130 && weight > 100 ) ) System.out.println("Critical."); else System.out.println("Endengared."); } } 31 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Example 2 and 3 (Comparing String) import java.util.Scanner; public class SortingThreeString { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); import java.util.Scanner; public class CompareToMethod { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); String word1, word2, word3; System.out.println("Enter three words: "); word1 = kbd.next(); word2 = kbd.next(); word3 = kbd.next(); // test for the first and second words if (word1.compareTo(word2) > 0) { // swapping word1 and word2 String tWord = word1; word1 = word2; word2 = tWord; } if (word2.compareTo(word3) > 0) { // swapping word2 and word3 String tWord = word2; word2 = word3; word3 = tWord; } if (word1.compareTo(word2) > 0) { // swapping word1 and word2 String tWord = word1; word1 = word2; word2 = tWord; } System.out.println("Word1= " + word1 + "\nWord2 = " + word2 + "\nWord3 = " + word3); } String word1, word2; System.out.print("Enter two words: "); word1 = kbd.next(); word2 = kbd.next(); if (word1.compareTo(word2) < 0) System.out.printf("%s comes before %s\n", word1, word2); else if (word1.compareTo(word2) > 0) System.out.printf("%s comes after %s\n", word1, word2); else System.out.println("Both are the same words."); } } Output Output Enter three words: Layla Jaffer Bader Enter two words: layla bader layla comes after bader After Sorting: First = Bader Second = Jaffer Third = Layla } 32 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 6.Write a java program that accepts a number followed by one space and then a letter. If the letter following the number is ‘f’ or ‘F’, the program is to treat the number entered as a temperature in degrees Fahrenheit, convert the number to the equivalent degrees Celsius, and print the result. If the letter following the number is ‘c’ or ‘C’, the program is to treat the number entered as a temperature in degrees Celsius, convert the number to the equivalent degrees Fahrenheit, and print the result. If the letter is neither ‘f’, ‘F’, ‘c’, nor ‘C’, the program is to print a message that the input is invalid and terminate. Note that .. import java.util.Scanner; public class TempratureVersion1 { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); double number , degree ; char code ; System.out.println("Enter a number followed by a code: "); number = kbd.nextDouble(); // take the firstChar from the read string code = kbd.next().charAt(0); if (code == 'f' || code == 'F') { degree = (5.0/9) * (number-32); System.out.print("The temprature in Celisus is " + degree); } else { if (code == 'c' || code == 'C') { degree = (9.0/5) * number + 32 ; System.out.println("The temprature in Pahernheite is " + degree); } else { System.out.println("Invalid code."); } } Output Enter a number followed by a code: 23 C The temprature in Pahernheite is 73.4 Output Enter a number followed by a code: 66 F The temprature in Celisus is 18.88888888888889 } } 33 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 8.Write a program to calculate and display the net price of a pasta based on two user inputs: type (C for chicken, M for Meat, or V for Vegetable) and the number of appetizers. the net price of the pasta is the sum of the following: (a) Base price of the pasta is BD. 2.5 for chicken, BD. 2.5 for Meat, and BD. 2.1 for vegetables. (b) Each appetizer is an additional BD. 1.2 Sample Input/Output Enter pasta type: C for chicken, M for Meat, V for Vegetables: C Enter number of appetizers: 2 Net price is BD. 4.9 import java.util.Scanner; public class SelectionProblem8 { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); char type; int appetizers; double price=0.0; System.out.println("Enter pasta type: C for chicken, M for Meat, V for Vegetables:"); type = kbd.next().charAt(0); System.out.println("Enter number of appetizers: "); appetizers = kbd.nextInt(); if (type == 'c' || type == 'C' || type == 'm' || type == 'M') price = 2.5; else if (type == 'v' || type == 'V') price = 2.1; else { System.out.println("Invaid code. Sorry we have to end" + " the program."); System.exit(-1); } double netPrice = price + appetizers * 1.2; System.out.println("Net price is BD. " + netPrice); } } 34 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Example 4 and 5 (Switch) import java.util.Scanner; public class SwitchExample { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); import java.util.Scanner; public class SwitchEx2 { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); int msgNo ; System.out.println("Enter an integer: "); msgNo = kbd.nextInt(); switch (msgNo) { case 1: System.out.println("One"); break; case 2: System.out.println("Tow"); //break; case 3: System.out.println("Three"); //break; case 4: System.out.println("Four"); break; default: System.out.println("Invalid input."); } System.out.print("Enter a word: "); String word = kbd.next(); switch (word.charAt(0)) { case 'a' : case 'A' : System.out.println("The user typed letter 'a' "); break; case 'b' : case 'B' : System.out.println("The user typed letter 'b' "); break; default: System.out.println("Invalid input. "); } } } output } } Enter a word: b Output Enter an integer: The user typed letter 'b' 2 Tow Three Four 35 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Example 6 (Switch) import java.util.Scanner; public class SwitchExample { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); int watt, life; System.out.print("What is the bulb wattage: "); watt = kbd.nextInt(); switch(watt) { case 25: life = break; case 40: case 60: life = break; case 75: case 100: life = break; default: life = } Output 2500; What is the bulb wattage: 40 1000; The life expectancy is 1000 hours. 750; 0; System.out.println("The life expectancy is " + life + " hours."); } } 36 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 2.A Florist needs a program to manage his flower shop. The florist sells three types of flowers Viola, Rose and Camellia. The available flowers in the shop are 25, 33, and 40 respectively. The program should ask the customer to enter the type of flower (1 for Viola, 2 for Rose, 3 for Camellia) and the number of flowers to be bought. If the number of flowers to be bought is larger than the available flowers then display the message “Sorry, we do not have this amount of flowers”. Otherwise display the following message “Thank you come again”. Note: Use Switch or if statement Sample Input / Output: Enter the type of the flowers: Viola(1),Rose(2),Camellia(3): 1 Enter the number of flowres: 12 Answer Thank you come again. OR Enter the type of the flowers: Viola(1),Rose(2),Camellia(3): 2 Enter the number of flowres: 45 Sorry, we do not have this amount of flowers. 37 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Using if Statement .. import java.util.Scanner; public class Assi { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); int msg, msgN ; System.out.print("Enter the type of the flowers Viola(1),Rose(2),Camellia(3): msg = kbd.nextInt(); "); if (msg == 1) { System.out.print("Enter the number of flowers: "); msgN = kbd.nextInt(); if (msgN <= 25) System.out.println("Thank you come again"); else System.out.println("Sorry, we do not have this amount of flowers."); } else if ( msg == 2 ) { System.out.print("Enter the number of flowers: "); msgN = kbd.nextInt(); if (msgN <= 33) System.out.print("Thank you come again"); else System.out.println("Sorry, we do not have this amount of flowers."); } else if (msg == 3 ) { System.out.print("Enter the number of flowers: "); msgN = kbd.nextInt(); if (msgN <= 40) System.out.print("Thank you come again"); else System.out.println("Sorry, we do not have this amount of flowers."); } else System.out.println("Sorry"); } } 38 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 10.Write a java program that asks the user to enter two float numbers and a character which represents a code for an arithmetic operation. The program performs arithmetic operations (addition, subtraction, multiplication, and division) on those two numbers depending on the value of code as follows: import java.util.Scanner; public class SelectionProblem10 { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); double first, second; char code; System.out.println("Enter two numbers followed by a code."); System.out.println("For the code, use A or a for addition, " + " S or s for subtraction."); System.out.println("Use m or M for multiplcation, and d or D for division."); System.out.print("? "); first = kbd.nextDouble(); second = kbd.nextDouble(); code = kbd.next().charAt(0); switch(code) { case 'a': case 'A': System.out.printf("The answer is %.3f\n", (first+second)); break; case 's': case 'S': System.out.printf("The answer is %.3f\n", (first-second)); break; case 'm': case 'M': System.out.printf("The answer is %.3f\n", (first*second)); break; case 'd': case 'D': if (second == 0.0) System.out.println("Sorry we cannot divide by zero."); else System.out.printf("The answer is %.3f\n", (first/second)); break; default: System.out.println("Invalid code."); } } } 39 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 3.Write a program that asks the user to enter: (1) a string representing a car type, (2) an integer representing the number of cylinders and (3) a float representing the price of the car. The program will calculate and display the insurance amount to be paid as follows: Insurance Amount = Initial + Cylinder*Ratio + Price * Percentage Where Initial, Ratio and Percentage values are selected from the following table according to the car type: Note: all variations of capitalizations should be equally accepted in your program; i.e. Toyota, Toyota, TOYOTA and even ToYotA should be equally treated in your program Answer 40 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader import java.util.Scanner; public class toyota { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); char carType ; int nuOfCylinders ; float price ; System.out.println("Enter Car Type: T for Toyota , N for Nissan , B for BMW , M for Mercedes "); carType = kbd.next().charAt(0); System.out.println("Enter number of cylinders : "); nuOfCylinders = kbd.nextInt(); System.out.println("Enter price: "); price = kbd.nextFloat(); int initial , ratio ; double percentage ; switch (carType) { case 'T': case 'N': { initial = 50 ; ratio = 10 ; percentage = 5/100.0; break; } case 'B': case 'M': { initial = 70; ratio = 20; percentage = 7/100.0; break; } default: { initial = 80; ratio = 30; percentage = 9/100.0; } } double insuranceAmount = initial + (nuOfCylinders * ratio) + (price * percentage); System.out.println("\nInsurance Amount : " + insuranceAmount); } } 41 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Chapter 4 - Flow of Control: Loops Example 1 (For Loop) public class forloop3 { public static void main(String[] args) { for (int i = 1 ; i <= 5 ; i++) { for (int j = 1 ; j <= 3 ; j++) System.out.print(j + "\t"); System.out.println(); } } Output 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 } public class forloop4 { public static void main(String[] args) { for (int i = 1 ; i <= 5 ; i++) { for (int j = 1 ; j <= 3 ; j++) System.out.print(j + "\t"); Output 123123123123123 } } } 1 public class forloop5 { public static void main(String[] args) { for (int i = 1 ; i <= 5 ; i++) { for (int j = 1 ; j <= 3 ; j++) System.out.println(j + "\t"); } } 2 3 1 2 3 … } 2 42 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Example 2 and 3 (For Loop) Output public class ForLoop { public static void main(String[] args) { for (int i = 1; i <= 5; i++) System.out.println("i = " + I +"\ti^2 = " + i * i); } } i=1 i^2 = 1 i=2 i^2 = 4 i=3 i^2 = 9 i=4 i^2 = 16 i=5 i^2 = 25 Output public class ForLoop { public static void main(String[] args) { for (int i = 1; i <= 5; i++) System.out.println("i = " + i + "\ti^2 = " + i * i); for (int i = 1, j = 10 ; i <= 10 ; i++ , j--) System.out.println("i = " + i + "\tj= " + j); } } i=1 i^2 = 1 i=2 i^2 = 4 i=3 i^2 = 9 i=4 i^2 = 16 i=5 i^2 = 25 i=1 j= 10 i=2 j= 9 i=3 j= 8 i=4 j= 7 i=5 j= 6 i=6 j= 5 i=7 j= 4 i=8 j= 3 i=9 j= 2 i = 10 j= 1 43 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Example 4 (While Loop) Output public class LoopExample { public static void main(String[] args) { int i = 1; while (i <= 3) { System.out.println("i = " + i); i++; } System.out.println("Done. i = " + i); i=1 i=2 i=3 Done. i = 4 } } Output public class LoopExample { public static void main(String[] args) { System.out.println("\nPrinting the numbers from 1 to 10"); int j = 1; while (j<=10) { System.out.println("j = " + j); j++; } } } Printing the numbers from 1 to 10 j=1 j=2 j=3 j=4 j=5 j=6 j=7 j=8 j=9 j = 10 44 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Output public class LoopExample { public static void main(String[] args) { j = 20; while (j>=11) { System.out.println("j = " + j); j--; } } j = 20 j = 19 j = 18 j = 17 j = 16 } j = 15 j = 14 j = 13 j = 12 j = 11 Output public class LoopExample { public static void main(String[] args) { j = 100; while (j<=104) { System.out.println("Iteration " + j); j++; } } Iteration 100 Iteration 101 Iteration 102 Iteration 103 Iteration 104 } 45 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Example 5 (While Loop) public class WhileLoopExample { public static void main(String[] args) { System.out.println("counting up from 1 to 5:\n"); int count = 1; while (count <= 5) { System.out.println("count = " + count); count++; } System.out.println("Done. Count = " + count); System.out.println("counting down from 5 to 1:\n"); count = 5; while (count >= 1) { System.out.println("count = " + count); count--; } System.out.println("Done. Count = " + count); System.out.println("counting upward but printing downward.\n"); count = 1; while (count <= 5) { System.out.println("count = " + (6-count)); count++; } System.out.println("Done. Count = " + count); } } Output counting up from 1 to 5: count = 1 count = 2 count = 3 count = 4 count = 5 Done. Count = 6 counting down from 5 to 1: count = 5 count = 4 count = 3 count = 2 count = 1 Done. Count = 0 counting upward but printing downward. count = 5 count = 4 count = 3 count = 2 count = 1 Done. Count = 6 46 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Example 6 (While Loop) import java.util.Scanner; public class ReadingASetOfIntegers { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); int number; System.out.println("Enter a set of number zero to stop."); number = kbd.nextInt(); int count = 0; while (number != 0) { count++; //System.out.println("You entered " + number); //System.out.print("Enter a number or zero to stop: "); number = kbd.nextInt(); } System.out.println("You have entered " + count + " numbers."); Output Enter a set of number zero to stop. 1240 You have entered 3 numbers. } } 47 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Example 7 (Do While Loop) import java.util.Scanner; public class DoWhileExample { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); Output Enter two numbers: 2 5 double first, second; String tryAgain; The sum is 7.00 do { System.out.print("Enter two numbers: "); first = keyboard.nextDouble(); second = keyboard.nextDouble(); System.out.printf("The sum is %.2f\n", first + second); Do you want to try again? 'yes' or 'no' System.out.println("\nDo you want to try again? 'yes' or 'no'"); System.out.print("? "); tryAgain = keyboard.next(); } while (tryAgain.equalsIgnoreCase("yes")); ? no } } public class DoWhileLoop { public static void main(String[] args) { int count = 1; do { System.out.println("count = " + count); count++; } while (count <= 5); } } Output count = 1 count = 2 count = 3 count = 4 count = 5 48 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 1.Write a program that reads a set of positive integers and displays their sum (total). Stop reading whenever the user types a negative or zero integers. import java.util.Scanner; public class Q2 { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); int number , sum = 0; System.out.println("Please enter a set of positive integers. "); System.out.println("Enter negative or zero to stop. "); number = kbd.nextInt(); while (number > 0) { // add to sum sum += number ; number = kbd.nextInt(); Output Please enter a set of positive integers. Enter negative or zero to stop. 6 3 2 1 -7 The sum is 12 } System.out.println("\nThe sum is " + sum); } } 49 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 2.write a program that prompts the user for a positive integer..If the user typed a none positive integer , then display an invalid message and try again. import java.util.Scanner; public class O1 { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); System.out.print("Enter a positive integer: "); int num = kbd.nextInt(); // initialize while (num <= 0 ) // LCV = num { System.out.println("Invalid input. Please try again !"); num = kbd.nextInt(); // update } while Output Enter a positive integer: -1 Invalid input. Please try again ! 10 You are done. System.out.println("You are done."); } } import java.util.Scanner; public class O1 { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); int num; do { if (num <= 0) System.out.println("Invalid input. Try again !"); } while (num <= 0); System.out.println("We are done"); } Output Enter a positive integer: 0 System.out.print("Enter a positive integer: "); num = kbd.nextInt(); } do - while Invalid input. Try again ! Enter a positive integer: 4 We are done 50 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Example 8 and 9 (Sent Line Loop and General Loop Tasks) import java.util.Scanner; public class sentlineloop { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); int num , count = 0 , sum = 0 , max , min ; double average ; Output // (1) read a set of integers ended by any negative number System.out.println("Please enter a set of integers\n" + "ended by a negative integer: "); num = kbd.nextInt(); max = num; min = num; while (num >= 0) { // (2) count how many integers count++; // (3) find the sum of the integers sum += num ; // (5) find the maximum if (num > max) max = num ; // (5) find the minimum if (num < min) min = num; num = kbd.nextInt(); } if (count == 0) { System.out.println("You did not enter any integers. "); // quit the program System.exit(0); } System.out.println("You have entered " + count + " integer(s) ."); System.out.println("The sum of the integer(s) is " + sum); // (4) The average of the integers average = (double) sum / count ; System.out.println("The average is " + average); System.out.println("The maximum is " + max ); } } Output Please enter a set of integers ended by a negative integer: 4 3 2 6 -1 You have entered 4 integer(s) . The sum of the integer(s) is 15 The average is 3.75 The maximum is 6 51 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader import java.util.Scanner; public class GeneralLoopTasks { public static final int SENTINEL = 0; public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); int number, count=0, evenCount=0, oddCount=0, posCount=0, negCount=0, sum=0, multipleThree=0 , maximum, minimum; System.out.println("Enter a number or zero to stop : " ); number = keyboard.nextInt(); maximum = number; minimum = number; while(number != SENTINEL) { Output // count how many numbers entered by the user count++; // count even and odd numbers Enter a number or zero to stop : if (number % 2 == 0) // even evenCount++; 1 8 2 6 7 -1 0 else oddCount++; You have eneterd 6 integers. // check if the number is divisible by three if (number % 3 == 0) multipleThree++; Even integers = 3 and odd integers = 3 // count positives and negative numbers if (number >0) There are 1 integers divisible by 3. posCount++; else Positive(s) = 5 and Negative(s) = 1 negCount++; // find the sum of the entered numbers The sum is 23 sum += number; // finding the maximum and minimum The aveage is 3.83 if (number > maximum) maximum = number; if (number < minimum) The maximum is 8 minimum = number; number = keyboard.nextInt(); The minimum is -1 } if (count == 0) { System.out.println("There is no data in your input."); System.exit(0); } System.out.println("\nYou have eneterd " + count + " integers."); System.out.println("Even integers = " + evenCount + " and odd integers = " + oddCount); System.out.println("There are " + multipleThree + " integers divisible by 3."); System.out.println("Positive(s) = " + posCount +" and Negative(s) = " + negCount); System.out.println("The sum is " + sum); System.out.printf("The aveage is %.2f\n", (double)sum/count); 52 System.out.println("The maximum is " + maximum); System.out.println("The minimum is " + minimum); } } UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 1.Blood sugar is considered normal if its rate is less than 140 and greater than 70, it is considered high if its rate is greater than or equal to 140, and it is considered low if its rate is less than or equal to 70. Write a Java program that asks the user to input the rate of blood sugar of each patient in a hospital (-1 to indicate the end of the data.) The program should calculate and print the number of patients with normal blood sugar, number of patients with high blood sugar, number of patients with low blood sugar, and the total number of patients entered by the user. import java.util.Scanner; public class LoopsProblem1 { public static final int SENTINEL = -1; public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); int rate, normal=0, low=0, high=0; System.out.println("Enter patients' blood sugar (-1 to stop)"); rate = keyboard.nextInt(); while (rate != SENTINEL) { if (rate <= 0) System.out.println(rate + " is invalid."); else if (rate > 70 && rate < 140) normal++; else if (rate <= 70) low++; else if (rate >= 140) high++; rate = keyboard.nextInt(); } System.out.println("Normal = " + normal); System.out.println("High = " + high); System.out.println("Low = " + low); System.out.println("Total = " + (normal+ high + low)); } Output Enter patients' blood sugar (-1 to stop) 120 10 400 -1 Normal = 1 High = 1 Low = 1 Total = 3 } 53 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 4.A factory manufactures electricity cables, all of which are tested to find their Cable Factor. Cables are classified as either Accepted or Rejected as follows: Cable Factor Cable Quality Greater than or equal to 4.5 Otherwise Accepted Rejected Write a program that asks the user to enter the Cable Factor of several cables until the user enters a negative number to quit. The program should find and display: (a) The average cable factor for Accepted cables. (b) The number of cable factors entered by the user. import java.util.Scanner; public class PL4{ public static void main(String[] args) { Scanner input = new Scanner(System.in); double cableFactor , acceptedSum = 0.0 , acceptedAvarage ; int acceptedCount = 0 , cableCount = 0 ; Output System.out.println("Please enter cable factors for"); System.out.println("all electrical cables (negative to stop) . "); cableFactor = input.nextDouble(); while (cableFactor >= 0) { cableCount++; if (cableFactor >= 4.5 ) { acceptedCount++; acceptedSum += cableFactor ; } cableFactor = input.nextDouble(); } System.out.println("sum = " + acceptedSum); if (acceptedCount == 0) System.out.println("Noaccepted cable is found."); else { acceptedAvarage = acceptedSum / acceptedCount ; System.out.printf("The avarge of accpted cables is: %8.3f\n",acceptedAvarage ); } System.out.println("You have is total " + cableCount + " cables."); } } Output Please enter cable factors for all electrical cables (negative to stop) . 6.4 4.7 9.8 2.1 -1 sum = 20.900000000000002 The avarge of accpted cables is: 6.967 You have is total 4 cables. 54 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 2.Write a Java program that asks the user to input unknown number of characters terminated by ‘#’ character. Your program should count the number of alphabets (a–z, A–Z) and the number of non-alphabets (i.e digits, special characters, spaces, tabs, etc.) in the given input. Sample Input/Output Enter characters terminated by #: CSC 103# Alphabets are 3 Non-alphabets are 4 import java.util.Scanner; public class PL2 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter a line of text : "); String line = input.nextLine(); line = line.toUpperCase(); int alphaCount = 0 ; for ( int i = 0 ; i < line.length(); i++) { char letter = line.charAt(i); if (letter >= 'A' && letter <= 'z') alphaCount++; } System.out.println("Alphabets are = " + alphaCount ); System.out.println("Non-alphabets are = " + (line.length()-alphaCount) ); Output Enter a line of text : Hello ITCS 113 Alphabets are = 9 Non-alphabets are = 5 } } 55 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 1. Write a program that reads a positive integer number of any digit size and do the following: (a) Print the sum of its digits. (b) Print the average of its digits. (c) Print the leftmost digit. (d) Print the maximum digit. If the input number is negative, convert it to positive. Here is a sample Input/Output of your program: Enter a positive integer: 1246 The Sum is 13 The average is 3.25 The leftmost digit is 1 The maximum is 6 import java.util.Scanner; public class PL5 { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); System.out.println("Enter a positive integer: "); int num = kbd.nextInt(); if (num < 0) num = -num; int digitsSum = 0 , digitsCount = 0 , digitMax = 0 , digit = 0 ; while (num !=0) { //get the unary digit digit = num % 10 ; digitsCount++; digitsSum += digit ; if (digit > digitMax) digitMax = digit ; num /= 10 ; } if (digitsCount == 0) System.out.println("The number you entered is zero. "); else { System.out.println("The sum is " + digitsSum ); System.out.println("The avarege is " + ( (double) digitsSum/digitsCount) ); System.out.println("The leftmost digit is " + digit ); System.out.println("The maximum digit is " + digitMax ); } } } 56 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 7.You received a data file named “students.txt” from the admission office of the university. Each line in the file is a record of a student consisting of the student first name (string) followed by his/her GPA (double) followed by a letter code, either F or M (char). The letter code F is used for female students and M for male students. Assume the number of lines in the file is unknown. Write a program that reads the first name, the GPA and the letter code for every student in the file and display on screen the following: (a) The number of students named AHMED. (b) The number of students whom GPAs are above 3.0. (c) The name that has the maximum GPA. (d) The average GPA for female and male students separately. Answer 57 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader import java.util.Scanner; public class LoopsProblem7 { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); String firstName, maximumName =""; double gpa, maximumGpa = -1.0, maleSum=0.0, femaleSum=0.0; char gender; int ahmedCount=0, gpaCounter = 0, maleCount=0, femaleCount=0; System.out.println("Enter first name followed by gpa\n" + " followed by gebder (F for female and M for male."); firstName = kbd.next(); while (!firstName.equalsIgnoreCase("stop")) { gpa = kbd.nextDouble(); gender = kbd.next().charAt(0); // part (a) if (firstName.equalsIgnoreCase("ahmed")) ahmedCount++; // part (b) if (gpa > 3.0) gpaCounter++; // part (c) if (gpa > maximumGpa) { maximumGpa = gpa; maximumName = firstName; } // part (d) switch(gender) { case 'm': case 'M': maleCount++; maleSum += gpa; break; case 'f': case 'F': femaleCount++; femaleSum += gpa; default: System.out.println(gender + " is an invalid gender code"); } firstName = kbd.next(); } System.out.println("(a) Number of students with name Ahmed is " + ahmedCount); System.out.println("(b) Number of students with GPA above 3 is " + gpaCounter); System.out.println("(c) The name with maximum GPA is " + maximumName); System.out.printf("(d) Male average is %.2f and " + " female average is %.2f\n", maleSum/maleCount, femaleSum/femaleCount); } } 58 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 9.Consider a file named transaction.txt which contains unknown number of lines. Each line contains data of one transaction as follows: username (string), amount (float), and membership number (int). Write a Java program that reads the data from the file, then displays on screen the number of users, the total amount and the highest amount. Readding from the file should stop when one or more of the conditions given below becomes true: transaction.txt (a) (b) The end of file has been reached. The username “user999” is reached. user001 user002 user003 ... ... 12.5 5.2 33.1 12345 87542 93568 Sample Screen Output Number of users: 54 Transactions total amount: 26587 The highest amount: 280 import java.util.Scanner; public class LoopsProblem9 { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); System.out.println("Enter user name, amount, and membership."); System.out.println("To stop reading enter user999 as the user name."); String name; double amount, sum = 0.0, maxAmount=-1.0; int membership, users = 0; name = kbd.next(); while (!name.equalsIgnoreCase("user999")) { amount = kbd.nextDouble(); membership = kbd.nextInt(); users++; sum += amount; if (amount > maxAmount) maxAmount = amount; name = kbd.next(); } if (users == 0) { System.out.println("You enterd no data."); System.exit(0); } System.out.printf("%-30s%d\n", "Number of users:", users); System.out.printf("%-30s%.1f\n", "Transactions total amount:",sum); System.out.printf("%-30s%.1f", "The highest amount", maxAmount); } } 59 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 10.An input file empSalary contains records of unknown number of employees (maximum number of employees in the file is 150.) Each line in the file is a record that contains the employee’s first name (string), number of hours worked (int) and hourly rate in Bahraini Dinar BD. (float). Write a program that reads the data from the file and displays the following on screen: the salary for each employee in the file (Salary = Hours Worked × Hourly rate.) (b) the number of employees in the file. (c) the highest salary with employee name. Format the salary to 3 decimal places. Sample I/O of the program is shown in the example below. (a) Answer 60 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader public class LoopsProblem10 { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); String firstName, maximumName = ""; int hoursWorked, employees=0; double hourlyRate, salary, maxSalary=-1.0; System.out.println("Enter first name followed by hours worked\n" + " followed by hourly rate"); firstName = kbd.next(); System.out.printf("%-10s%-10s\n", "Name", "Salary"); while (!firstName.equalsIgnoreCase("stop")) { hoursWorked = kbd.nextInt(); hourlyRate = kbd.nextDouble(); // (b) employees++; salary = hoursWorked*hourlyRate; System.out.printf("%-10s%10.2f\n", firstName, salary); // (c) if (salary > maxSalary){ maxSalary = salary; maximumName = firstName; } firstName = kbd.next(); } System.out.println("\n\nThere are " + employees + " employees."); System.out.printf("%s has the highest salary of BD. %.3f\n", maximumName, maxSalary); } } 61 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 3.An IT student at UOB is expected to graduate if his/her GPA is greater than or equal to 2.0 and he/she is in the fourth year in the B.Sc program. Write a JAVA program that ask the user to input a student id (long), year number (either 1 or 2 or 3 or 4) and gpa (float) for 5 students (use loop). The program should output the number of expected to graduate students. You Input/Output should be as follows: Enter a student id :111 Enter the year number and gpa: 4 2.5 import java.util.Scanner; public class Assi3 { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); float gpa ; long id ; int year , count = 0; Enter a student id : 222 Enter the year number and gpa: 3 3.1 for (int x = 1 ; x <= 5 ; x++) { System.out.print("Enter a student id :"); id = kbd.nextLong(); Enter a student id : 333 Enter the year number and gpa: 4 1.9 System.out.print("Enter the year number and gpa: "); year = kbd.nextInt(); gpa = kbd.nextFloat(); Enter a student id : 444 if (year == 4 && gpa >= 2.0) { count++; } Enter the year number and gpa: 4 3.6 Enter a student id : 555 } Enter the year number and gpa: 1 3.9 System.out.println("The number of expected to graduate students is: " + count); } The number of expected to graduate students is: 2 } 62 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 4.Write a program to read a list of exam scores given as integer percentages in the range 0 to 100. Display the total number of grades, the number of grades in each letter-grade category and the average of grades in each category’s as follows : 90-100 is an A, 80 to 89 is an B, 70 to 79 is an C, 60 to 69 is an D, and 59 is an F. Use a negative score as a sentinel value to indicate the end of the input. (The negative value is used only to end the loop, so do not use it in the calculations.) For example, if the input is: 98 87 86 85 85 78 73 72 72 72 70 66 63 50 -1 The output would be Total number of grades = 14 Number of A's = 1 Average = 98 Number of B's = 4 Average = 85.75 Number of C's = 6 Average= 72.83 Number of D's = 2 Average= 61.5 Number of F's = 1 Output Enter the marks: 98 87 86 85 85 78 73 72 72 72 70 66 63 50 -1 Total number of grades = 14 The Answer Number of 'A's = 1 Average = 98.0 Number of 'B's = 4 Average = 85.75 Number of 'C's = 6 Average = 72.83 Number of 'D's = 2 Average = 64.5 Number of 'F's = 1 Average = 50.0 63 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader import java.util.Scanner; public class Assi3 { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); int CA = 0 , CB = 0 , CC = 0 , CD = 0 , CF = 0 ; int sumA = 0 , sumB = 0 , sumC = 0 ,sumD = 0 , sumF = 0 ; System.out.println("Enter the marks: "); int mark = kbd.nextInt(); while (mark > 0) { if (mark <= 100 && mark >= 90) { CA++; sumA += mark; } if (mark <= 89 && mark >= 80) { CB++; sumB += mark; } if (mark <= 79 && mark >= 70) { CC++; sumC += mark; } if (mark <= 69 && mark >= 60) { CD++; sumD += mark; } if (mark <= 59) { CF++; sumF += mark; } mark = kbd.nextInt(); } System.out.println("Total number of grades = " + (CA + CB System.out.println("Number of 'A's = " + CA + " Average = System.out.println("Number of 'B's = " + CB + " Average = System.out.println("Number of 'C's = " + CC + " Average = System.out.println("Number of 'D's = " + CD + " Average = System.out.println("Number of 'F's = " + CF + " Average = } } + " " " " " CC + CD + CF)); + (double) sumA/CA + (double) sumB/CB + (double) sumC/CC + (double) sumD/CD + (double) sumF/CF ); ); ); ); ); 64 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Output Example 10 (For Loop) First loop public class ForLoopExamples { public static void main(String[] args) { System.out.println("\nFirst loop"); for(int i=1, j=10; i<=10; i++, j--) System.out.println(i + "\t" + j); System.out.println("\nSecond loop"); for(int i=2; i<=20; i+=2) System.out.println(i); } } 1 10 2 9 3 8 4 7 5 6 6 5 7 4 8 3 9 2 10 1 Second loop 2 4 6 8 10 12 14 16 18 20 65 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Example 11 (For Loop) public class ForLoopExamples { public static void main(String[] args) { // nested loops System.out.println("\nNested loops"); for(int i=1; i<=7; i++) { for(int j=i; j<=7; j++) System.out.print(j + "\t"); System.out.println(); } } } Output Nested loops 1 2 3 4 5 6 2 3 4 5 6 7 3 4 5 6 7 4 5 6 7 5 6 7 6 7 7 7 Output public class ForLoopExamples { public static void main(String[] args) { for(int i=5; i>=1; i--) { for(int j=i; j<=5; j++) System.out.print(j + "\t"); System.out.println(); } } } 5 4 5 3 4 5 2 3 4 5 1 2 3 4 5 66 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 6.Write a Java program that asks the user to input the age and gender (M for male, F for female) of 10 rabbits. Your program should count the number of female and male rabbits and print the results on the screen. import java.util.Scanner; public class PL6 { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); System.out.println("Enter the age and gender of 10 rabbits: "); char gander ; int age , countm = 0 , countf = 0 ; for (int i = 1 ; i <= 10 ; i++) { age = kbd.nextInt(); gander = kbd.next().charAt(0); if (gander == 'M') { countm++; } if { (gander == 'F') countf++; } } Output Enter the age and gender of 10 rabbits: 1M 2M 3M 4M 5F } 6F System.out.println("Male Rabbits = " + countm); System.out.println("Female Rabbits = " + countf); 7F 8F } 9F 1F Male Rabbits = 4 Female Rabbits = 6 67 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 15.Write a program that reads from the keyboard a positive integer M and generates a triangle of numbers (as shown below). You must make sure the number is entered is positive before making the triangle. For example, if the input for M is 6, the output triangle should be 6 5 4 3 2 1 5 4 3 2 1 4 3 21 3 21 2 1 1 import java.util.Scanner; public class PL15 { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); Output System.out.println("Please enter a positive integer: "); int M = kbd.nextInt(); if (M < 0) { System.out.println("You did not enter a positive integer. "); System.out.println("You input will be cinverted to positive. "); M = -M ; //Convert M into pisitive. } for (int line = M ; line >= 1 ; line--) { for (int col = line ; col >= 1 ; col--) System.out.print(col + "\t"); System.out.println(); // new line } } Output Please enter a positive integer: 6 6 5 4 3 2 5 4 3 2 1 4 3 2 1 3 2 1 2 1 1 1 } 68 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 16.Write a program that reads two integers num1 and num2. If any of these integers is negative convert it to positive and if num1 > num2, swap num1 and num2. The output of your program is as shown below: Enter first number: 3 Enter second number: 7 3 6 9 ... 4 8 12 ... 5 10 15 ... 6 12 18 ... 7 14 21 ... 30 40 50 60 70 import java.util.Scanner; public class PL16 { public static void main(String[] args) { Scanner input = new Scanner(System.in); int num1 , num2 ; System.out.println("Enter first numbers: "); num1 = input.nextInt(); System.out.println("Enter second number: "); num2 = input.nextInt(); //if negative, convet to positive if (num1 < 0) num1 = -num1; if (num2 < 0) num2 = -num2; // swap if num1>num2 if (num1 > num2) { int temp = num1 ; num1 = num2 ; num2 = temp ; } Output Enter first numbers: 3 Enter second number: 7 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50 6 12 18 24 30 36 42 48 54 60 7 14 21 28 35 42 49 56 63 70 for (int line = num1 ; line <= num2 ; line++) { for (int col = line ; col <= line * 10 ; col += line) System.out.print(col + "\t"); System.out.println();//new line } } } 69 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Example 12 (Break And Countinue) Output break inside a loop. public class BreakAndCountinue { public static void main(String[] args) { System.out.println("break inside a loop. "); int num = 1 ; } 3 5 6 7 8 // continue inside a loop num = 0 ; while (num <= 10) { num++; if (num % 3==0) continue; System.out.println(" num = " + num); } } 2 4 while (1 == 1) { if (num % 5==0 && num % 6==0) break; System.out.println(num); num++; } // use continue with for loop for (int n = 1 ; n <= 10 ; n++) { if (num % 3==0) continue; System.out.println(" n = " + } 1 9 10 ….. to 29 num = 1 num = 2 num = 4 num = 5 num = 7 n); num = 8 num = 10 num = 11 n=1 n=2 n=3 n=4 n = 5 .. to n = 10 70 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Break inside a loop. i=1 Example 13 (Break And Countinue) public class BreakAndContinueExamples { public static void main(String[] args) { System.out.println("Break inside a loop."); for(int i=1; i<=20; i++) { System.out.println("i = " + i); if (i > 10) break; } System.out.println("Continue inside a for loop."); for(int i=1; i<=20; i++) { if (i % 2 == 0) continue; System.out.println("i = " + i); } System.out.println("Continue inside a while loop."); int i =1; while(i<=20) { if (i++ % 2 == 0) continue; System.out.println("i = " + (i-1)); //i++; } i=2 i=3 i=4 i=5 i=6 i=7 i = 8 to i = 11 Continue inside a for loop. i=1 i=3 i=5 i=7 i=9 i = 11 i = 13 i = 15 } } i = 17 i = 19 Continue inside a while loop. i=1 i=3 i=5 i=7 i=9 i = 11 i = 13 i = 15 i = 17 71 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 1- Write a program called SumAndAverage to produce the sum of 1, 2, 3, ..., UpperBound. Upperbound is a positive integer entered by the user. Also compute and display the average. a. By using for loop b. By using While-do loop c. By using do-while loop import java.util.Scanner; public class Q1 { public static void main (String[] args) { int sum = 0; // Store the accumulated sum, init to 0 double average; // average in double int lowerbound = 1; // The lowerbound to sum int upperbound ; // The upperbound to sum int count=1; Scanner input=new Scanner(System.in); System.out.println("Enter an upperbound :"); upperbound=input.nextInt(); // Use a for-loop to sum from lowerbound to upperbound Output Enter an upperbound : 5 Sum=15 Average = 3.0 /*for (int number = lowerbound; number <= upperbound; ++number) { sum += number; // same as "sum = sum + number" Output }*/ /*while(count<=upperbound) Enter an upperbound : sum+=count; count++; 3 { }*/ Sum=6 Average = 2.0 do { sum+=count; count++; }while(count<=upperbound); // Compute average in double. Beware that int/int produces int. average=(double)sum/upperbound; // Print sum and average. System.out.println("Sum="+sum + " Average = "+average); } } 72 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 2- A Prime Number, is a number that can be divided evenly only by 1, or itself. Write a Java program, that prompts the user to enter a number, and determines if it is a prime or not. Use while-do loop. import java.util.Scanner; public class Q2 { public static void main (String[] args) { int n; Scanner input=new Scanner(System.in); System.out.println("Enter Number :"); n=input.nextInt(); Output Enter Number : 12 Not prime boolean ok=true; int count=2; while(ok && count <n) { if(n%count==0) ok=false; else count++; } if (ok==true) System.out.println("Prime"); else System.out.println("Not prime"); Output Enter Number : 7 prime } } 73 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 3- Write a program called HarmonicSum to compute the sum of a harmonic series, as shown below, where n is a number entered by the user. import java.util.Scanner; public class Q3 { // Save as "SumAndAverage.java" public static void main (String[] args) { int n; Scanner input=new Scanner(System.in); int maxDenominator; // Use a more meaningful name instead of n System.out.println("Enter maxDenominator :"); maxDenominator=input.nextInt(); double sum = 0.0; // for-loop for summing from left-to-right for (int denominator = 1; denominator <= maxDenominator; ++denominator) { sum+=(double)1/denominator; // Beware that int/int gives int, e.g., 1/2 gives 0. } System.out.println("The sum is: " + sum); Output Enter maxDenominator : 3 The sum is: 1.8333333333333333 } } 74 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader import java.lang.Math; public class TL1 { public static void main(String[] args) { System.out.println("n\tn^2\tn^3\tn^4"); System.out.println("----------------"); for (int i = 1 ; i <= 5 ; i++ ) { for (int j = 1 ; j <= 4 ; j++) { System.out.print((int)Math.pow(i,j)+"\t"); } Output n n^2 n^3 n^4 -------------------------------------------1 1 1 1 2 4 8 16 3 9 27 81 4 16 64 256 5 25 125 625 System.out.println(); } } } 75 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 17.Write a Java program that prompts the user to input an integer greater than 0 which represents the size/height of the triangle shape. The program should print the following triangle shape according to the user input by alternating ’ !’ and ’+’ characters. Invalid error message must be displayed if the size is less than 1. Example: if the size of the shape = 4, then the program should output: ! ! +! ! + ! +! ! + ! + ! +! import java.util.Scanner; public class PL17 { public static void main(String[] args) { int number, r = 1 ,num; Scanner input = new Scanner(System.in); System.out.print("Please enter the height: "); number = input.nextInt(); num = number; for(int i = 0; i < number ; i++) { for(int j = num ; j > 0; j--) { System.out.print(" "); } num--; for(int x = 0; x < r ;x++) { if(x%2 == 0) System.out.print("!"); else System.out.print("+"); } r+=2; System.out.println(" "); } } } 76 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 18.Write a program that reads an integer number N . If the number is negative convert it to positive. The program ir required to produce a shape consisting of * and # characters of N lines. Below is shown examples on sample output for some values of N . N =1 *# N= **# *## 2 N =3 ***# **## *### N =4 ****# ***## **### *#### import java.util.Scanner; public class PL18 { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); System.out.print("Enter an integer: "); int N = kbd.nextInt(); if (N < 0) N = -N ; for (int lines = 1 ; lines <= N ; lines++) { // print *'s for (int st = 1 ; st <= N-lines+1 ; st++ ) System.out.print("*"); // print #'s for (int hash = 1 ; hash <= lines ; hash++) System.out.print("#"); System.out.println(); Output Enter an integer: 4 ****# ***## **### *#### } } } 77 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 19.Write a Java program that asks the user to enter a positive integer N 15. The program should check that N is valid and repeatedly asks the user to enter N if N is not valid. The program then should print the following shape according to the value of N by alternating * and + characters. import java.util.Scanner; public class LoopsProblems19 { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); double N = 0; do { System.out.print("Enter a positive integer >= 15: "); N = kbd.nextInt(); if (N <= 0) System.out.println("Invalid input. Try again."); } while (N <= 0); for(int line=1; line<=N; line++) { System.out.print("*"); for(int group=1; group <= N-line; group++) System.out.print("+*"); System.out.println(); } } } 78 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader import java.util.Scanner; public class LoopsProblem20 { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); System.out.print("Enter odd number of lines: "); int N = kbd.nextInt(); while(N%2 == 0 || N < 3) { System.out.println(N + " is invalid. It should be odd greater than 3."); System.out.print("Try again ? "); N = kbd.nextInt(); } for(int i=1; i<= N; i++) { // check if i is the middle line if (i == N/2+1) { // display N +'s for(int col=1; col<=N; col++) System.out.print("+"); } else { // display N #'s for(int col=1; col<=N; col++) { if (col == N/2+1) System.out.print("+"); else System.out.print("#"); } } // newline System.out.println(); } } } 79 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader import java.util.Scanner; public class LoopsProblem21 { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); System.out.print("Enter an odd number greter than 2: "); int N = kbd.nextInt(); if (N %2 == 0 || N <= 2) { System.out.println(N + " is not odd. Good bye."); System.exit(0); } for(int line =1; line <= N; line++) { // first line if (line==1) for(int star=1; star <= N; star++) System.out.print("*"); else { // print spaces for(int space=1; space <= line-1; space++) System.out.print(" "); System.out.print("*"); } System.out.println(); } } } 80 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Graphics supplement JApplet JFrame import javax.swing.JApplet; import java.awt.Graphics; import javax.swing.*; import java.awt.*; public class HappyFace extends JApplet { public void paint(Graphics canvas) { super.paint(canvas); . . . } } public class HappyFaceJFrame extends JFrame{ public HappyFaceJFrame(){ setSize(600,400); setDefaultCloseOperation(EXIT_ON_CLOSE); } public void paint(Graphics canvas) { super.paint(canvas); . . . } public static void main(String[] args) { HappyFaceJFrame guiWIndow = new HappyFaceJFrame(); guiWIndow.setVisible(true); } } 81 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Commonly used methods of Graphics class: drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) Draws the outline of a circular or elliptical arc covering the specified rectangle. drawLine(int x1, int y1, int x2, int y2) Draws a line, using the current color, between the points (x1, y1) and (x2, y2) in this graphics context's coordinate system. drawOval(int x, int y, int width, int height) Draws the outline of an oval. drawPolygon(int[] xPoints, int[] yPoints, int nPoints) Draws a closed polygon defined by arrays of x and y coordinates. drawPolyline(int[] xPoints, int[] yPoints, int nPoints) Draws a sequence of connected lines defined by arrays of x and y coordinates. drawRect(int x, int y, int width, int height) Draws the outline of the specified rectangle. fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) Fills a circular or elliptical arc covering the specified rectangle. fillOval(int x, int y, int width, int height) Fills an oval bounded by the specified rectangle with the current color. 82 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader fillPolygon(int[] xPoints, int[] yPoints, int nPoints) Fills a closed polygon defined by arrays of x and y coordinates. fillRect(int x, int y, int width, int height) Fills the specified rectangle. drawString(String str, int x, int y) Draws the text given by the specified string, using this graphics context's current font and color. drawImage(Image img, int x, int y, ImageObserver observer) Draws as much of the specified image as is currently available. setColor(Color c) Sets this graphics context's current color to the specified color. setFont(Font font) Sets this graphics context's font to the specified font. 83 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Example 1 (Happy Face Using JApplet) import javax.swing.*; import java.awt.*; public class HappFaceJApplet extends JApplet{ public void paint(Graphics canvas) { super.paint(canvas); canvas.drawOval(80,80,150,150); canvas.fillOval(120,130,10,20); canvas.fillOval(180,130,10,20); canvas.drawArc(120,150,70,50,180,180); } } Example 2 (Happy Face Using JFrame) import javax.swing.*; import java.awt.*; public class HappyFaceJFrame extends JFrame{ public HappyFaceJFrame() { setSize(600,400); setDefaultCloseOperation(EXIT_ON_CLOSE); } public void paint(Graphics canvas) { super.paint(canvas); canvas.drawOval(80,80,150,150); canvas.fillOval(120,130,10,20); canvas.fillOval(180,130,10,20); canvas.drawArc(120,150,70,50,180,180); } public static void main(String[] args) { HappyFaceJFrame guiWindow = new HappyFaceJFrame(); guiWindow.setVisible(true); } } 84 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Example 3 (Graphic Demo) import java.applet.Applet; import java.awt.*; public class demo extends Applet{ public void paint(Graphics g){ g.setColor(Color.red); g.drawString("Welcome",50, 50); g.drawLine(20,30,20,300); g.drawRect(70,100,30,30); g.fillRect(170,100,30,30); g.drawOval(70,200,30,30); g.setColor(Color.pink); g.fillOval(170,200,30,30); g.drawArc(90,150,30,30,30,270); g.fillArc(270,150,30,30,0,180); } } 85 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Example 4 (Bouncing Circle) import javax.swing.*; import java.awt.*; public class BouncingCircle extends JFrame{ public static final int FRAME_WIDTH = 600; public static final int FRAME_HEIGHT = 400; public static final int CYCLE_DIAMETER = 120; public BouncingCircle() { setSize(FRAME_WIDTH,FRAME_HEIGHT); setDefaultCloseOperation(EXIT_ON_CLOSE); } public void paint(Graphics canvas) { super.paint(canvas); int offset =10, xPos = 10, repeat = 1; while (repeat <= 3) { canvas.clearRect(xPos-offset ,80, CYCLE_DIAMETER+1, CYCLE_DIAMETER+1); canvas.drawOval(xPos, 80, CYCLE_DIAMETER, CYCLE_DIAMETER); // add a delay try { Thread.sleep(20); } catch (InterruptedException ex) {} xPos += offset; if (xPos >= FRAME_WIDTH-CYCLE_DIAMETER-5 || xPos <= 0) { offset = -offset; repeat++; } canvas.clearRect(10, 240, 100, 10); canvas.drawString("x = " + xPos, 10, 250); } } Note.. Write this program in your compiler to see the output public static void main(String[] args) { BouncingCircle gui = new BouncingCircle(); gui.setVisible(true); } } 86 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Example 5 (Moving Cycle) import javax.swing.*; import java.awt.*; public class MovingCycle extends JFrame{ public MovingCycle(){ // resize window frame setSize(600,400); // close window wehn X is clicked setDefaultCloseOperation(EXIT_ON_CLOSE); } public void paint(Graphics canvas){ super.paint(canvas); canvas.setColor(Color.BLUE); int xDispl = 0; while (xDispl <= 350) { canvas.drawOval(100 + xDispl, 100, 150, 150); // add a delay try { Thread.sleep(60); // in miliseconds } catch (InterruptedException ex) { System.out.println("Error happended."); } canvas.clearRect(100 + xDispl, 100, 151, 151); xDispl += 10; } canvas.drawOval(100 + xDispl-10, 100, 150, 150); xDispl = 0; while (450-xDispl >= 0) { canvas.drawOval(450 - xDispl, 100, 150, 150); // add a delay try { Thread.sleep(60); // in miliseconds } catch (InterruptedException ex){ System.out.println("Error happended."); } canvas.clearRect(450 - xDispl, 100, 151, 151); xDispl += 10; } canvas.drawOval(450 - xDispl+10, 100, 150, 150); } public static void main(String[] args){ MovingCycle guiWindow = new MovingCycle(); guiWindow.setVisible(true); } } Note.. Write this program in your compiler to see the output 87 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 1. Write a Java applet to draw the five inter- locking rings that are the symbol of the Olympics. (Don’t worry about the color.) import javax.swing.*; import java.awt.*; public class Ex1 extends JApplet { public void paint (Graphics canvac) { super.paint(canvac); canvac.setColor(Color.blue); canvac.drawOval(30,60,50,50); canvac.setColor(Color.BLACK); canvac.drawOval(85,60,50,50); canvac.setColor(Color.red); canvac.drawOval(140,60,50,50); canvac.setColor(Color.yellow); canvac.drawOval(55,90,50,50); canvac.setColor(Color.green); canvac.drawOval(110,90,50,50); } } 88 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 2. Write an applet program that displays a picture of a snowman. (Hint: Draw three circles, one above the other. Make the circles progressively smaller from bottom to top. Make the top circle a happy face.) import javax.swing.*; import java.awt.*; public class Ex2 extends JApplet { public void paint (Graphics canvac) { super.paint(canvac); canvac.drawOval(130,60,65,60); canvac.fillOval(145,80,10,10); canvac.fillOval(169,80,10,10); canvac.drawArc(147,88,30,20,180,180); canvac.drawOval(120,120,85,80); canvac.drawOval(115,199,100,100); } } 89 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 3.Write a Java applet that displays the following pattern: import javax.swing.*; import java.awt.*; public class Ex3 extends JApplet { public void paint (Graphics canvac) { super.paint(canvac); canvac.setColor(Color.blue); canvac.drawOval(120,80,60,60); canvac.setColor(Color.cyan); canvac.fillOval(138,97,25,25); canvac.setColor(Color.black); canvac.drawArc(127,30,50,50,180,180); canvac.drawArc(179,85,50,50,90,180); canvac.drawArc(71,85,50,50,90,-180); canvac.drawArc(125,140,50,50,0,180); } } 90 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Example 6 (Car) import javax.swing.*; import java.awt.*; public class Assi4 extends JApplet { public void paint(Graphics canvac) { super.paint(canvac); canvac.drawRect(100,50,130,67); canvac.drawRect(70,118,190,75); canvac.drawRect(100,65,55,53); canvac.drawRect(175,65,55,53); canvac.drawOval(80,165,70,70); canvac.fillOval(99,183,33,33); canvac.drawOval(179,165,70,70); canvac.fillOval(197,183,33,33); } } Example 7 (Face) import javax.swing.*; import java.awt.*; public class Ex6 extends JApplet{ public void paint (Graphics canvas) { super.paint(canvas); //Draw face interior and outline canvas.setColor(Color.yellow); canvas.fillOval(100,50,200,200); //Draw eyes canvas.setColor(Color.black); canvas.fillOval(145,100,40,40); canvas.fillOval(220,100,40,40); //Draw ears canvas.setColor(Color.yellow); canvas.fillOval(40,50,100,100); canvas.fillOval(260,50,100,100); //Draw mouth canvas.setColor(Color.black); canvas.fillOval(150,180,100,22); } } 91 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Example 8 (Polygon ) import javax.swing.*; import java.awt.*; public class Ex7 extends JApplet { public void paint(Graphics canvas) { int xPoints[] = {50 , 100 , 140 , 140 , 100 , 50 , 10 , 10 }; int yPoints[] = {60 , 60 , 100 , 150 , 190 , 190 , 150 , 100 }; int n = 8 ; canvas.setColor(Color.pink); canvas.fillPolygon(xPoints , yPoints , n); } public static void main(String [] args) { Ex7 guiWidow = new Ex7(); guiWidow.setVisible(true); } } Example 9 (Three Circle Shap) import javax.swing.*; import java.awt.*; public class ThreeCircleShap extends JFrame{ public ThreeCircleShap(){ // resize window frame setSize(600,400); // close window wehn X is clicked setDefaultCloseOperation(EXIT_ON_CLOSE); } public void paint(Graphics canvas){ super.paint(canvas); canvas.setColor(Color.GREEN); canvas.drawOval(100,100,150,150); canvas.setColor(Color.RED); canvas.drawOval(175,100,150,150); canvas.setColor(Color.BLUE); canvas.drawOval(135,175,150,150); } public static void main(String[] args){ ThreeCircleShap guiWindow = new ThreeCircleShap(); guiWindow.setVisible(true); } } 92 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 4.Write a JApplet or JFrame program to draw four circles besides each other in a form of a square as shown below. Two circles are filled and the other two are not. The color of each circle is: • Top-Left circle is grey and not filled. • Top-Right circle is blue and filled. • Bottom-Left circle is green filled. • Bottom-Right circle is red and not filled. Below the four circles write “I LOVE COLORS” in using black color. import javax.swing.*; import java.awt.*; import java.lang.String; public class Q2 extends JApplet { public void paint (Graphics canvas) { super.paint(canvas); canvas.setColor(Color.gray); canvas.drawOval(50, 50, 80, 80); canvas.setColor(Color.BLUE); canvas.fillOval(129, 50, 80, 80); canvas.setColor(Color.green); canvas.fillOval(50,129,80,80); canvas.setColor(Color.red); canvas.drawOval(129,129,80,80); canvas.setColor(Color.BLACK); canvas.drawString("I LOVE COLORS" , 79 ,245); } } 93 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Chapter 5 - Defining Classes And Methods Example 1 (Circle And Circle Class) public class Circle { /** class data */ double radius = 1.0 ; /** class contructor */ Circle (double r) { radius = r ; } /** class methods */ double getArea() { return radius * radius * 3.14159; } } Output Area = 314.159 public class CirlceClassExample { public static void main(String[] args) { Circle object = new Circle (10); System.out.println("Area = " + object.getArea()); } } 94 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader import java.util.Scanner; public class MethodsProblem1 { // main method public static void main(String[] args) { Scanner kbd = new Scanner(System.in); double firstSide , secondSide , thirdSide ; System.out.print("Enter 3 side: "); firstSide = kbd.nextDouble(); secondSide = kbd.nextDouble(); thirdSide = kbd.nextDouble(); boolean answer = isRightTriangle(firstSide , secondSide , thirdSide ); if (answer == true) System.out.println("Yes , it is right triangle. "); else System.out.println("No , it is not a right triangle. "); Output Enter 3 side: 3.0 4.0 5.0 Yes , it is right triangle. } // isRightTriangle method public static boolean isRightTriangle (double side1 , double side2 , double side3 ) { boolean result = false ; // you may use the pow method in math class //if (Math.pow(side1,2) + Math.pow(side2,2) // == Math.pow(side3,2)); if (side1*side1 + side2*side2 == side3*side3) result = true; return result; } } 95 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Output import java.util.Scanner; public class MethodProblem3 { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); 55555 666666 System.out.print("Enter start and end integers: "); startNum = kbd.nextInt(); endNum = kbd.nextInt(); 7777777 trapezoid(startNum , endNum); Enter start and end integers: -5 80 1 public { if if if { static void trapezoid(int start , int end) (start < 0 || start > 9 ) start = 0 ; (end < 0 || end > 9 ) end = 9 ; (start > end) int temp = start ; start = end ; end = temp ; } for (int line = start ; line <= end ; line++) { for (int col = 1 ; col <= line ; col++) System.out.print(line); System.out.println(); } } 4444 int startNum , endNum ; } } Enter start and end integers: 4 7 22 333 4444 55555 666666 7777777 88888888 999999999 96 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader import java.util.Scanner; public class MethodsProblem4 { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); char code; String str; System.out.println("Enter 10 train codes:"); for(int i=1; i<=10; i++) { code = kbd.next().charAt(0); str = trainType(code); System.out.println("This code represents " + str + " Type"); } } public static String trainType(char code) { String result; switch(code) { case 'S':case 's': result = "Steam"; break; case 'D':case 'd': result = "Diesel"; break; case 'E':case 'e': result = "Electric"; break; default: result = "Invalid"; } return result; } } 97 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader import java.util.Scanner; public class MethodsProblem6 { public static final double PI = 3.141592654; public static void main(String[] args) { Scanner kbd = new Scanner(System.in); System.out.println("Enter radius and height: "); double r = kbd.nextDouble(); double h = kbd.nextDouble(); System.out.println("The surface area is " + surfaceArea(r,h)); } Output Enter radius and height: 1.5 2.2 The surface area is 34.8716784594 public static double surfaceArea(double radius, double height) { return 2 * PI * radius * (radius+height); } } 98 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader import java.util.Scanner; public class MethodProblem12 { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); String material ; float length , tempChange ; System.out.print("Enter a material: "); material = kbd.next(); System.out.print("Enter a length: "); length = kbd.nextFloat(); System.out.print("Enter a temperature change: "); tempChange = kbd.nextFloat(); float answer = Expansion(material , length , tempChange); System.out.printf("The length change is %10.3f" , answer); } public static float Expansion(String material , float length , float temp_Change) { int coefficient ; switch (material.toUpperCase()) { case "ALUMINIOM" : coefficient = 24 ; break; case "SILVER" : coefficient = 18 ; break; default: coefficient = 12 ; } return coefficient * length * temp_Change; } } Output Enter a material: silver Enter a length: 3.5 Enter a temperature change: 2.6 The length change is 163.800 99 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader public class InvoiceTest { public static void main(String[] args) Invoice inv1 = new Invoice("C123", Invoice inv2 = new Invoice("C124", Invoice inv3 = new Invoice("C125", { "COMPUTER", 15, 129.000); "CAMERA", 5, 60.500); "FLASH", 30, 1.500); Answer Continued System.out.println("Invoice 3 quantity is " + inv3.getQuantity()); inv3.setQuantity(-40); inv3.setQuantity(40); System.out.println("Invoice 3 quantity is " + inv3.getQuantity()); System.out.println("Invoice 1 Total is BD. " + inv1.getInvoiceAmount()); System.out.println("Invoice 2 Total is BD. " + inv2.getInvoiceAmount()); System.out.println("Invoice 3 Total is BD. " + inv3.getInvoiceAmount()); } } 100 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader public class Invoice { String partNo, description; private int quantity; double pricePerItem; // Constructor public Invoice(String partNo, String description, int quantity, double price){ this.partNo = partNo; this.description = description; if (quantity < 0) this.quantity = 0; else this.quantity = quantity; if (price < 0.0) this.pricePerItem = 0.0; else this.pricePerItem = price; } public String getPartNo() { return partNo; } public void setPartNo(String partNo) { this.partNo = partNo; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { if (quantity < 0) System.out.println(quantity + " is an invalid quantity. " + "The current quantity is unchanged, which is " + this.quantity); else this.quantity = quantity; } public double getPricePerItem() { return pricePerItem; } public void setPricePerItem(double pricePerItem) { this.pricePerItem = pricePerItem; } public double getInvoiceAmount() { return this.quantity * this.pricePerItem; } } Run The Main Output Invoice 3 quantity is 30 -40 is an invalid quantity. The current quantity is unchanged, which is 30 Invoice 3 quantity is 40 Invoice 1 Total is BD. 1935.0 Invoice 2 Total is BD. 302.5 Invoice 3 Total is BD. 60.0 101 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader public class ClassProblem2P { public static void main(String[] args) { Employee emp1 = new Employee ("Ahmed" , "Ali" , 500.0); Employee emp2 = new Employee ("Mona" , "jamal" , 750.0); System.out.printf("The yearly salary for %s %s is %.3f%n", emp1.getFirstName() ,emp1.getlastName() , emp1.getSalary() * 12.0 ); Answer Continued System.out.printf("The yearly salary for %s %s is %.3f%n", emp2.getFirstName() ,emp2.getlastName() , emp2.getSalary() * 12.0 ); emp1.setSalary(emp1.getSalary() * 1.1); emp2.setSalary(emp2.getSalary() * 1.1); System.out.println("Yearly salaries after 10% increase: "); System.out.printf("The yearly salary for %s %s is %.3f%n", emp1.getFirstName() ,emp1.getlastName() , emp1.getSalary() * 12.0 ); System.out.printf("The yearly salary for %s %s is %.3f%n", emp2.getFirstName(),emp2.getlastName() , emp2.getSalary() * 12.0 ); } } 102 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader public class Employee { // Instance variables private String firstName , lastName ; private double salary = 0.0 ; // by defult is puplic // methods Employee (String first , String last , double sal) { firstName = first ; lastName = last ; if (salary < 0) salary = 0.0 ; else salary = sal; } // get and set methods for the first name data public String getFirstName() { return firstName; } public void setFirstName(String first) { firstName = first; } // get and set methods for the last name data public String getlastName() { return lastName; } public void setLastName(String last) { lastName = last; } // get and set methods for the salary data public double getSalary () { return salary; } public void setSalary (double salary) { this.salary = salary; } Run The Main Output The yearly salary for Ahmed Ali is 6000.000 The yearly salary for Mona jamal is 9000.000 Yearly salaries after 10% increase: The yearly salary for Ahmed Ali is 6600.000 The yearly salary for Mona jamal is 9900.000 } 103 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader public class StockTesting { public static void main(String[] args) { Stock myStock = new Stock("ORCL", "Oracle Corporation"); Stock urStock = new Stock("ORCL", "Oracle Corporation"); myStock.previousClosingPrice = 34.5; myStock.currentPrice = 34.35; urStock.previousClosingPrice = 60.56; urStock.currentPrice = 102.35; Answer Continued System.out.printf("My stock price change is %.3f%%\n", myStock.getChangePercent()); System.out.printf("Your stock price change is %.3f%%\n", urStock.getChangePercent()); if (myStock.equals(urStock)) System.out.println("The two stocks are the same."); else System.out.println("The two stocks are different."); } } 104 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader public class Stock { String symbol, name; double previousClosingPrice, currentPrice; // Constructor public Stock(String symbol, String name) { this.symbol = symbol; this.name = name; } public double getChangePercent() { return (this.previousClosingPrice-this.currentPrice)/ this.previousClosingPrice * 100; } public boolean equals(Stock otherStock) { boolean result; if ((this.symbol == otherStock.symbol) && (this.name == otherStock.name)) result = true; else result = false; return result; } Run The Main Output My stock price change is 0.435% Your stock price change is -69.006% The two stocks are the same. } 105 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader public class ClassesProblem7 { public static void main(String[] args) { Car car1 = new Car(2016 , "Toyota"); Answer Continued // call accelerate method five times System.out.println("Accelerate five times: "); for (int i = 1 ; i <= 5 ; i++) { car1.accelerate(); System.out.println("The speed is: " + car1.getSpeed()); } // call brake method five times System.out.println("Brake five times: "); for (int i = 1 ; i <= 5 ; i++) { car1.Brake(); System.out.println("The speed is: " + car1.getSpeed()); } } } 106 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader public class Car { private int yearMake ; private String Make ; private int Speed ; public Car(int year, String make) { this.yearMake = year; this.Make = make; this.Speed = 0; } public int getYearMake() { return this.yearMake; } public String getMake() { return Make; } public int getSpeed() { return Speed; } public void accelerate () { this.Speed += 5 ; } public void Brake () { this.Speed -= 5 ; } } Run The Main Output Accelerate five times: The speed is: 5 The speed is: 10 The speed is: 15 The speed is: 20 The speed is: 25 Brake five times: The speed is: 20 The speed is: 15 The speed is: 10 The speed is: 5 The speed is: 0 107 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Example 2 (Point And Classes Parameters) public class ClassesParameters { public static void main(String[] args) { double x = 4.5, y = 7.2; changDataPrimitive(x, y); System.out.printf("Pass by value: x = %3f , y = %f\n", x, y); public class Point { private double x , y ; public Point(double x, double y) { this.x = x; this.y = y; } public double getX() { return x; } public double getY() { return y; } public void setX(double x) { this.x = x; } public void setY(double y) { this.y = y; } Point point = new Point(2.0, 3.0); changeClassValues(point); System.out.printf("Pass by class reference: x = %3f , y = %f\n", point.getX(), point.getY()); } public static void changDataPrimitive (double a , double b) { a *= 2 ; b += 6 ; } public static void changeClassValues (Point pt) { pt.setX(4.0); pt.setY(6.0); } } } Output Run The Main Pass by value: x = 4.500000 , y = 7.200000 Pass by class reference: x = 4.000000 , y = 6.000000 108 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader import java.util.Scanner; public class ClassesProblem8 { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); Answer Continued System.out.print("Enter a temperature in Fahrenheit: "); double temp = kbd.nextDouble(); Temperature t = new Temperature(temp); System.out.printf("The temperature in Fahrenheit: %.3f\n" , t.getFahrenheit ()); System.out.printf("The temperature in Celsius: %.3f\n" , t.getCelsius()); System.out.printf("The temperature in Kelvin: %.3f\n" , t.getKelvin()); } } 109 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader public class Temperature { private double ftemp; // constructor public Temperature (double temp) { this.ftemp = temp; } public void setFahrenheit (double temp) { this.ftemp = temp; } public double getFahrenheit () { return this.ftemp; } public double getCelsius() { return (5.0/9)*(this.ftemp-32); } Run The Main Output Enter a temperature in Fahrenheit: 34.7 The temperature in Fahrenheit: 34.700 The temperature in Celsius: 1.500 The temperature in Kelvin: 274.500 public double getKelvin() { //return getCelsius()+273; return (5.0/9)*(this.ftemp-32)+273; } public boolean equals(Temperature t) { return (this.ftemp == t.ftemp); } } 110 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader import java.util.Scanner; public class ClassesProblem11 { public static void main(String[] args) { double area,height,base; Scanner kbd = new Scanner(System.in); Answer Continued System.out.print("Please enter the three test scores: "); double test1 = kbd.nextDouble(), test2 = kbd.nextDouble(), test3 = kbd.nextDouble(); TestScores scoreRef = new TestScores(test1,test2,test3); System.out.printf("The average is %.3f\n", scoreRef.getAverage()); System.out.printf("Test1 before change: %.3f\n", scoreRef.getTest1()); replaceTest1(scoreRef, -35.6); System.out.printf("Test1 after change: %.3f\n", scoreRef.getTest1()); } public static void replaceTest1(TestScores tsRef, double score) { tsRef.setTest1(score); } } 111 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader public class TestScores { private double test1 = 0.0, test2 = 0.0, test3 = 0.0; // The constrcutor public TestScores(double t1, double t2, double t3) { if (t1 > 0) this.test1 = t1; else System.out.println("Invalid test1 marks."); if (t2 > 0) this.test2 = t2; else System.out.println("Invalid test2 marks."); if (t3 > 0) this.test3 = t3; else System.out.println("Invalid test3 marks."); } public double getAverage() { return (test1+test2+test3)/3.0; } // getter and setter for test1 public double getTest1() { return this.test1;} public double getTest2() { return test2; } public double getTest3() { return test3; } public void setTest1(double newTest) { if (newTest < 0) System.out.printf("%.3f is an invalid score.\n", newTest); else this.test1 = newTest; } public void setTest2(double newTest) { if (newTest < 0) System.out.printf("%.3f is an invalid score.\n", newTest); else this.test2 = newTest; } public void setTest3(double newTest) { if (newTest < 0) System.out.printf("%.3f is an invalid score.\n", newTest); else this.test3 = newTest; } } Run The Main Output Please enter the three test scores: 20.0 15.5 30.2 The average is 21.900 Test1 before change: 20.000 -35.600 is an invalid score. Test1 after change: 20.000 112 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 3. Create a class called Holiday to represent a holiday. An object of class Holiday represents a holiday during the year. This class has three instance variables: • name, which is a String representing the name of the holiday. • day, which is an int representing the day of the month of the holiday. • month, which is a String representing the month the holiday is in. a. Write a constructor for the class Holiday, which takes a String representing the name, an int representing the day, and a String representing the month as its arguments, and sets the class variables to these values. b. Provide a mutator method (set) and accessor method (get) for each instance variable. c. Write a method inSameMonth, which compares two instances of the class Holiday, and returns the Boolean value true if they have the same month, and false if they do not. d. Write a method toString that prints the message: The holiday is “name” and it is on month, day. Where name, month and day are the name, month and day of the holiday. e. Write a piece of code that creates a Holiday instance with the name “National Day”, with the day “16”, and with the month “December”, then call the method toString() to print the holiday information. public class NationalDay { public static void main(String[] args) { holiday2 H1 = new holiday2("National day ", 16 ," december"); Answer Continued H1.setName1(" National day "); H1.setDay1(16); H1.setMonth1(" December "); H1.String(); } } 113 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader public class holiday { private String name, month; int day; // write a constructor public holiday(String name, String month, int day) { this.name = name; this.day = day; this.month = month; } Run The Main Output // set and get public void setName(String name) { this.name = name; } public void setDay(int day) { this.day = day; } public void setMonth(String month) { this.month = month; } The holiday National day on 16 December public String getName() { return name; } public int getDay() { return day; } public String getmonth() { return month; } public boolean inSameMonth(holiday h1) { boolean result = false; if (h1.month == month) result = true; return result; } public void String(){ System.out.print(" The holiday is " + name + " and its on " + day + month } } 114 ); UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 4.Consider a class Person that represents an entry in an address book. Its attributes are : • The first name of the person (String type). • The last name of the person (String type). • The Telephone number of the person (integer type). 1. Write a constructor that takes three parameters—two string and one integer. Use these parameters to initialize the instance variables declared earlier. 2. Write a get and a set method for each of the instance variables in the class.. 3. Write a separate program that creates three Person objects to hold the following data. First Name Last Name Telephone Number Ahmed Shams 36251478 Kareema Zaidan 33247825 Jassim Naeem 334786541 Output the first name, last name and the telephone number for each of the above persons. public class PersonT { public static void main(String[] args) { ClassPerson Pe1 = new ClassPerson("Ahmed" , "Shams" , 36251478); ClassPerson Pe2 = new ClassPerson("Kareema" , "Zaidan" , 33247825); ClassPerson Pe3 = new ClassPerson("Jassim" , "Naeem" , 334786541); System.out.println("The First name is " + Pe1.getFirstName() Pe1.getLastName() + " ,thelephone number: System.out.println("The First name is " + Pe2.getFirstName() Pe2.getLastName() + " ,thelephone number: System.out.println("The First name is " + Pe3.getFirstName() Pe3.getLastName() + " ,thelephone number: + " + " + " " + " + " + Answer Continued and last name is " + Pe1.getTelephoneNumber()); and last name is " + Pe2.getTelephoneNumber()); and last name is " + Pe3.getTelephoneNumber()); } } 115 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader public class ClassPerson { private String FirstName; private String LastName; private int TelephoneNumber; public ClassPerson(String firstName, String lastName, int telephoneNumber) { FirstName = firstName; LastName = lastName; TelephoneNumber = telephoneNumber; } public String getFirstName() { return FirstName; } public String getLastName() { return LastName; } public int getTelephoneNumber() { return TelephoneNumber; } Run The Main Output The First name is Ahmed and last name is Shams ,thelephone number: 36251478 The First name is Kareema and last name is Zaidan ,thelephone number: 33247825 The First name is Jassim and last name is Naeem ,thelephone number: 334786541 public void setFirstName(String firstName) { FirstName = firstName; } public void setLastName(String lastName) { LastName = lastName; } public void setTelephoneNumber(int telephoneNumber) { TelephoneNumber = telephoneNumber; } } 116 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 5.A parking garage charges a BD 0.500 minimum fee to park for up to three hours. The garage charges an additional BD 0.200 per hour for each hour or part thereof in excess of three hours. The maximum charge for any given 24-hour period is BD4.00. Assume that no car parks for longer than 24 hours at a time. Write an application that calculates and displays the parking charges for each customer who parked in the garage yesterday. You should enter the hours parked for each customer. The program should display the charge for the current customer and should calculate and display the running total of yesterday’s receipts. The program should use the method calculateCharges to determine the charge for each customer. import java.util.Scanner; public class charge { public static void main(String args[]) { int time; double charge; Scanner input=new Scanner(System.in); System.out.println("Enter the time of the first client: "); time=input.nextInt(); person P1=new person(time); P1.CalculateCharge(); charge=P1.GetCharge(); System.out.println("The Total charge of the first client is: " +charge); Answer Continued System.out.println("Enter the time of the second client : "); time=input.nextInt(); P1.SetPerson(time); P1.CalculateCharge(); charge=P1.GetCharge(); System.out.println("The Total charge of the second client is: " +charge); } } 117 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader public class person { private int time; // time expressed with hours private double charge; public person(int Ntime) Run The Main { time=Ntime; } // Constructor public void SetPerson(int Ntime) {time = Ntime;} //Mutator Output public double GetCharge() { return charge;} //Accessor public void CalculateCharge() // Method Calculate Charge { int Addtime = time-3; if(Addtime <0) charge=0.5; else { double chargeAddTime = Addtime*0.2; double TotalCharge = chargeAddTime+0.5; if(TotalCharge<4) Enter the time of the first client: 2 The Total charge of the first client is: 0.5 Enter the time of the second client : 120 The Total charge of the second client is: 4.0 charge = TotalCharge; else charge=4; } } } 118 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Output Questions Chapter 2 Output .. int a = 4; a=15 int b = 10; b=9 int c; c=11 a += 2 + --b; c = b+ a * 2 % 4; System.out.println("a="+a+"\nb="+b+"\nc="+c); int AB=1, GM=9, CE=5; double fm=2.5; System.out.println("Year 2016"); double yr = 2016-fm*3-GM/2.0; System.out.println("Before "+yr); double avg = (AB+GM+CE)/3.0; System.out.println("After "+ 2016+(int) avg); AB++; --GM; int N2=AB+GM; System.out.println(N2); System.out.println("Example2:"); int a = 4, b=7, c=2; System.out.println(b-c/a+c%b); System.out.println(--a*2); System.out.println(a+b++); System.out.println(b); Year 2016 Before 2004.0 After 20165 10 String msg = "Today the weather is hot."; System.out.println("The length is "+msg.length()); char ch = msg.charAt(1); System.out.println(msg.replace(ch,'u')); int indx = msg.indexOf("hot"); System.out.println(msg.substring(0,indx)+"cold."); System.out.println(msg.substring(0,indx).concat("humid.")); Example2: 9 6 10 8 String line="You have 75 minutes."; System.out.println(line.length()); int n = line.indexOf("7"); System.out.println("n = " + n); String msg = line.substring(4,n); System.out.println(msg.toUpperCase()); msg = msg.concat("fun."); System.out.println(msg); System.out.println("\nHello\n\"ITCS111\"\nToday."); System.out.println("Hello 'ITCS113'"); 20 n=9 HAVE have fun. Hello "ITCS111" Today. Hello 'ITCS113' The length is 25 Tuday the weather is hut. Today the weather is cold. Today the weather is humid 119 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader int x=4, y=3, k=10; System.out.println (x + k/y - y/k*10); System.out.println ( ++x * 3 ); System.out.println (y-- ); System.out.println( x + "\t" + y ); 7 15 3 5 2 String command=("Java is funny language"); int count = command.length(); System.out.println("Length is " + command.length( )); count = command.length( ) + 3; System.out.println( count ); Length is 22 25 String sentence = "Text processing is hard!"; int position = sentence.indexOf("hard"); System.out.println(sentence); System.out.println("012345678901234567890123"); System.out.println("The word \"hard\" starts at index "+ position); sentence = sentence.substring(0, position) + "easy!"; sentence = sentence.toUpperCase(); System.out.println("The changed string is:"); System.out.println(sentence); String test = "abcdefg"; System.out.println(test.length()); System.out.println(test.charAt(1)); String test1 = "abcdefg"; System.out.println(test1.substring(3)); System.out.println("abc\ndef"); System.out.println("abc\\ndef"); String test2 = "Hello John"; test2 = test2.toUpperCase(); System.out.println(test2); 7 b defg abc def abc\ndef HELLO JOHN Text processing is hard! 012345678901234567890123 The word "hard" starts at index 19 The changed string is: TEXT PROCESSING IS EASY! 120 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader int a=2, b=3, c=4; double z = 1.5; System.out.println (a+" " + b); System.out.println (a + b); a = b+2 * c-a ; System.out.println (a); b =(int)(z) + 3; System.out.println (b); c = (b+c) % a ; System.out.println (c); 23 5 9 4 8 int x = 11; long y = 28; double w = 3.64; System.out.println( x + " "+ y + " " + w); w += 2; double result = y++ * --x ; System.out.println(x + " " + y +" " + w + " " + result); int result = 3 * 7 % 3 - 4 - 6; System.out.println("result is " + result); int result1 = 11 ; result1 /= 2 ; System.out.println("result is " + result1); result is -10 result is 5 int n=4; int m=6; System.out.println(++n*2+n + 20-m++*m + "n"); -7n 11 28 3.64 10 29 5.640000000000001 280.0 121 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader char a , b ; a = 'b'; System.out.println(a); b = 'c'; System.out.println(b); a=b; System.out.println(a); b c c int n = 2; n++; System.out.println("n is " + n); n--; System.out.println("n is " + n); int quotient = 7 / 3 ; int remainder = 7 % 3 ; System.out.println("quotient = " + quotient); System.out.println("remainder = " + remainder); double result = (1 / 2) * 2 ; System.out.println("(1 / 2) * 2 equals " + result); quotient = 2 remainder = 1 (1 / 2) * 2 equals 0.0 n is 3 n is 2 122 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Chapter 3 Output .. int x = 11, y ; if (x%2 == 0 && x/5 == 2) y = x++; else y = ++ x; System.out.println("x = " + x); System.out.println("y = " + y); x = 12 y = 12 int a =1 , b=2 , c= 1; int s = b*b-4*a*c ; if ( (s == 0) && (a==1) ) System.out.println ("Factored"); else System.out.println ("Imaginary"); System.out.println ("Coefficient= " + s); int time = 2, tide = 3; if (time + tide > 6) System.out.println("Time and tide wait for no one."); else System.out.println("Time and tide wait for me."); int time = 2, tide = 3; if (time + tide > 6) System.out.println("Time and tide wait for no one."); else if (time + tide > 5) System.out.println("Time and tide wait for someone."); else if (time + tide > 4) System.out.println("Time and tide wait for everyone."); else System.out.println("Time and tide wait for me."); Factored Coefficient= 0 Time and tide wait for me. Time and tide wait for everyone. int x = 10, y ; if (x%2 == 0 && x/5 == 2) y = x++; else y = ++ x; System.out.println("x = " + x); System.out.println("y = " + y); x = 11 y = 10 123 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader int number = 7; boolean isPositive = (number > 0); if (number > 0); number = -100; if (isPositive) System.out.println("Positive."); else System.out.println("Not positive."); System.out.println(number); System.out.println(false); System.out.println(7 < 0); System.out.println(7 > 0); int n = 7; System.out.println(n > 0); Positive. -100 false false true true System.out.println(true &&false); System.out.println(true || false); System.out.println(false && (x > 0)); System.out.println(true || (x > 0)); false true false true int key = 1; switch (key + 1){ case 1: System.out.println("Cake"); break; case 2: System.out.println("Pie"); break; case 3: System.out.println("Ice cream"); case 4: System.out.println("Cookies"); break; default:System.out.println("Diet time"); } Pie int code = 2; switch (code) { case 1: System.out.println("Hello."); case 3: System.out.println("Good-bye."); break; default: System.out.println("Till we meet again."); break; } Till we meet again. char letter = 'A'; switch (letter) { case'A': case'a': System.out.println("Some kind of A."); case'B': case'b': System.out.println("Some kind of B."); break; default: System.out.println("Something else."); break; } Some kind of A. Some kind of B. 124 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader int a, b; a = 0; b = 1; switch ( a + b ) { case 1: case 2: System.out.println ("Option 2");break; case 3: System.out.println ("Option 3");break; default: System.out.println ("Option 4 \n"); } System.out.println ("Option 5"); int y = 5, x = 8; switch (x % 7) { case 0: case 1: y++; case 2: case 3: y = y + 2; break; case 5: case 6: y = y - 3; } System.out.println (y); 8 Option 2 Option 5 int x, y; x = 3; y = x + 5; if ( ( x == y ) || ( y < x ) ) { System.out.println ("Expression is true\n"); } else { System.out.println ("Expression is false\n") ; } int angle=10; if (angle > 5) angle = angle + 5; else if (angle > 2) angle = angle + 10; System.out.println (angle); 15 Expression is false String s1 = "hello" ; String s2 = "hel" + "lo" ; String s3 = " mum" ; if (s1 == s2) { System.out.println("1. same"); } else { System.out.println("1. different"); }if (s1 + s3 == "hello mum" ){ System.out.println("2. same"); } else { System.out.println("2. different"); } double price = 19.5; int quantity = 2; String item = "Widgets"; System.out.printf("%10s sold:%4d at $%5.2f. Total = $%1.2f", item, quantity, price, quantity * price); 1. same 2. different Widgets sold: 2 at $19.50. Total = $39.00 125 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 12 126 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Chapter 4 Output .. int c = 0 , t = 1 ; while (c < 4) { c++; t += c; System.out.println("=>"+ t); } =>2 =>4 =>7 =>11 int sum = 11 ; for ( int i = 1 ; i <= 4 ; i++) { sum -= i; System.out.println("sum = " + sum); } int c = 0 , t = 0 ; while (c < 4) { c++; t += c; System.out.println("=>"+ t); } sum = 10 sum = 8 sum = 5 sum = 1 for (double test = 0; test < 3; test = test + 0.5) System.out.println(test); for (int count = 0; count <= 3; count++) for (int count2 = 0; count2 < count; count2++) System.out.println(count2); =>1 =>3 =>6 =>10 int sum = 10 ; for ( int i = 1 ; i <= 4 ; i++) { sum -= i; System.out.println("sum = " + sum); } 0.0 0.5 1.0 1.5 2.0 2.5 0 0 1 0 1 2 sum = 9 sum = 7 sum = 4 sum = 0 for (int n = 1; n <= 3; n++){ switch (n){ case 1: System.out.println("One"); break; case 2: System.out.println("Two"); break; case 3: System.out.println("Three"); break; default: System.out.println("Default case"); break; } } System.out.println("After the loop") One Two Three After the loop 127 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader for (int n = 1; n <= 5; n++) { if (n == 3) break; System.out.println("Hello"); } System.out.println("After the loop"); int i ,j ,k; for(i=1 ; i <= 5 ; i++) { for(j=4 ; j>=I ; j--) { System.out.print(" "); } for(k=1 ; k <= ( 2 * i -1); k++) { System.out.print("*"); } System.out.println(""); } int i, j, k; for(i=5 ; i >= 1; i--){ for(j=5 ; j > i ; j--){ System.out.print(" "); } for(k=1; k < (i *2) ; k++) { System.out.print("*"); } System.out.println(); } Hello Hello After the loop * *** ***** ******* ********* ********* ******* ***** *** * int i ,j; for(i=1; i <= 6; i++) { for(j=1; j < i; j++) { System.out.print("*"); } System.out.println(); } int i , j; for(i=5 ; i >= 1;i--) { for(j=1 ; j <= i; j++) { System.out.print("*"); } System.out.println(); } int i , j, k; for(i=5 ; i >= 1 ;i--){ for(j=1 ; j< i ;j++) { System.out.print(" "); } for(k=5 ; k>=i ;k--){ System.out.print("*"); } System.out.println(); } * ** *** **** ***** ***** **** *** ** * * ** *** **** ***** 128 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader int i, j, k; for(i=5 ; i >= 1 ;i--) { for(j=5 ; j > i ;j--) { System.out.print(" "); } for(k=1 ; k <= i ;k++) { System.out.print("*"); } System.out.println(); } ***** **** *** ** * for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) { System.out.print(j+" "); } System.out.println(); } 1 12 123 1234 12345 for (int i = 1; i <= 5; i++){ for (int j = 1; j <= i; j++){ if(j%2 == 0){ System.out.print(0); }else{ System.out.print(1); } }System.out.println(); } 1 10 101 1010 10101 int i, j, k; for(i=1 ; i <= 5 ;i++) { for(j=i ; j < 5 ;j++) { System.out.print(" "); } for(k=1 ; k < (i*2) ;k++) { System.out.print("*"); } System.out.println(); } for(i=4 ; i >= 1 ;i--) { for(j=5 ; j > i ;j--) { System.out.print(" "); } for(k=1 ; k < (i*2) ;k++) { System.out.print("*"); } System.out.println(); } * *** ***** ******* ********* ******* ***** *** * for (int i = 1; i <= 6; i++) { for (int j = i; j >= 1; j--) { System.out.print(j+" "); } System.out.println(); } 1 21 321 4321 54321 654321 129 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader for (int i = 1; i <= 6; i++) { for (int j = 1; j <= i; j++) { System.out.print(j+" "); } for (int j = i-1; j >= 1; j--) { System.out.print(j+" "); } System.out.println(); } 1 121 12321 1234321 123454321 12345654321 for(int i=1 ; i < 5 ;i++) { int alphabet = 65; //ASCII value of A for(int j=1; j <= i ;j++) { System.out.print((char)alphabet); alphabet++; } System.out.println(); } A AB ABC ABCD for (int i = 1; i <= 6; i++) { for (int j = 1; j <= i; j++) { System.out.print(i+" "); } System.out.println(); } 1 22 333 4444 55555 666666 int alphabet = 65; //ASCII value of A for(int i=1 ; i < 5 ;i++) { for(int j=1 ; j <= i ;j++) { A BC DEF GHIJ System.out.print((char)alphabet); alphabet++; } System.out.println(); } int alphabet = 65; for(int i=1 ; i < 5;i++){ for(int j=1 ; j <= i;j++){ System.out.print((char)alphabet); } System.out.println(); alphabet++; } A BB CCC DDDD 130 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader 131 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader Chapter 5 Output .. 132 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader public class rectangle { private int width; private int length; private int Area; public class AppRectangle { public static void main(String [] args) { rectangle R1=new rectangle(10,5); R1.SetArea(); R1.WriteOutput(); public rectangle(int w,int l){width=w;length=l;} public void SetArea(){this.Area=this.width*this.length;} public void WriteOutput() { System.out.println( width + " " + length); } public boolean Equal(rectangle R) { return((this.width==R.width) && (this.length==R.length)); } public void TryChange(rectangle R) { R.width=this.width; R.length=this.length; } public void Swap(int a, int b) { int temp; temp=a; a=b; b=temp; } 10 5 10 5 10 5 a=5 b=8 a=5 b=8 Are equal rectangle R2=new rectangle(25,5); R1.TryChange(R2); R1.WriteOutput(); R2.WriteOutput(); int a=5; int b=8; System.out.println("a=" + a + " b=" + b); R1.Swap(a,b); System.out.println("a=" + a + " b=" + b); if(R1.Equal(R2)) System.out.println("Are equal"); else System.out.println("Not equal"); } } } 133 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader public class Numbers { private int num1; private int num2; public Numbers(int n, int m) { if (n >= m) { num1 = m; num2 = n; } else { num1 = n; num2 = m; } } public Numbers(int m) { if (m > 0) { num1 = 0; num2 = m; } else { num1 = 0; num2 = 100; } } public Numbers() { num1 = 0 ; num2 = 5; } public int Thing() { int a = 0; for (int i = num1; i < num2; i++) a = a + i; return a; } public boolean Check() { return (num1 % num2 == 0); } public void Display() { for (int i = num1; i < num2; i++) if (i % 3 == 0) System.out.println(i); } public class AppNumbers { public static void main(String []args) { Numbers N1 = new Numbers(2, 5); Numbers N2 = new Numbers(20, 10); Numbers N3 = new Numbers(10); Numbers N4 = new Numbers(); N1.Display(); System.out.println(N1.Thing()); System.out.println(N1.Check()); System.out.println(N1.compare(N3)); N1.WriteOutput(); N2.WriteOutput(); N3.WriteOutput(); N4.WriteOutput(); N1.Swap(N2); N1.WriteOutput(); N2.WriteOutput(); 3 9 false false Num1=2 Num2= 5 Num1=10 Num2= 20 Num1=0 Num2= 10 Num1=0 Num2= 5 Num1=10 Num2= 20 Num1=2 Num2= 5 } } 134 UOB – IT – ITCS 111/113/101/103 (JAVA) – Collected and summarize by : Layla Jaffer Bader public boolean compare(Numbers Num) { return ((this.num1 == Num.num1) && (this.num2 == Num.num2)); } public void Swap(Numbers OtherNumber) { int temp1, temp2; temp1 = this.num1; this.num1 = OtherNumber.num1; OtherNumber.num1 = temp1; temp2 = this.num2; this.num2 = OtherNumber.num2; OtherNumber.num2 = temp2; } public void WriteOutput() { System.out.println("Num1=" + num1 + " Num2= " + num2); } } 135