Individual Readiness Assessment Test (irat) 11 questions ~ 11 minutes. Group Readiness Assessment Test (grat)
|
|
- Randolf Whitehead
- 5 years ago
- Views:
Transcription
1 INTRODUCTION
2 Today Questions & Answers Chapters 1 and 2 Individual Readiness Assessment Test (irat) 11 questions ~ 11 minutes Group Readiness Assessment Test (grat) 20 ~ 30 minutes Appeal (as needed) Mini-lecture Assignment for next lecture
3 Individual Test Question 1: def reserved word Question 2: syntax vs. semantic Question 3: white spaces Question 4: comments Question 5: escape sequence Question 0: Are you ready? Question 6: print vs println Question 7: order of precedence Question 8: variable Question 9: result =? Question 10: casting Question 11: string concatenation
4 Reserved Words class system static Scanner print public import main this variable results while
5 Syntax vs. Semantic Syntax grammar Semantic sentence meaning
6 White Spaces Are ignored when it is used to separate words (e.g. quotations) Used to improve the program readability (e.g. indentation) Includes blanks, tabs, and newlines (use them wisely)
7 Comments in Java 3 ways in Java // for one line /* for several lines */ /** for Java doc */ api/java/io/printstream.html
8 Escape Sequence The \ is used to indicate that the following character is special. \n = next line \r = return carriage \\ = to be able to put \ in string \( = not needed as brackets can be used in strings directly See page 63 on textbook
9 print vs. println System.out.println( My name is: ); System.out.print( Patricia ); Solution 1: My name is: Patricia Solution 2: My name is: Patricia
10 Order of Precedence Precedence among some of the Java operators (page 78) Precedence level Operator Operation Associates 1 + Unary plus R to L - Unary minus 2 * Multiplication L to R / Division % Remainder 3 + Addition L to R - Subtraction + String concatenation 4 = Assignment R to L
11 Order of Precedence / 5 * 4
12 Variables in Java Must be declared with a specific type Can only hold one value for the entire duration of the program It is a name for a memory location where a value is stored grades students average
13 Casting in Java int total = 100; int count = 8; result = (float) total / count; Vs. result = total / count;
14 Readings / Assignments Prepare exercise PP. 1.9 page 55 Is an individual work will be picked up at the beginning of class. Note: Lab 1 starts on Tuesday. Attendance mandatory for the first lab.
15 CHAPTERS 1 & 2 PRACTICE
16 Today Return of Assignment Correction of PP 1.9 (page 55) on the board Exercise 2.5 (page 106) Variable assignments Coverage of Scanner class Assignment for next lecture
17 Exercise PP 1.9, page 55 * *** ***** ******* ********* ******* ***** *** *
18 EX 2.5 (page 106) What is the output produced by the following statement? Explain. System.out.println ( He thrusts his fists\n\tagainst + the post\nand still insists\n\the sees the \ ghost\ ); He thrusts his fists against the post and still insists he sees the ghost 2 gifts
19 Today Exercise 2.5 (page 106) Correction of PP 1.9 (page 55) on the board Variable assignments Coverage of Scanner class Assignment for next lecture
20 EX 2.10 (page 107) Given the following declarations, what result is stored in each of the listed assignment statements? (a) int iresult, num1 = 25, num4 = 5; iresult = num1 / num4; (d) int num3 = 17, num4 = 5; double fresult = num3 / num4; (e) int num4 = 5; double fresult, val1 = 17.0; fresult = val1 / num4; Team gift
21 Chapter 2 EX 2.10 (Continued) (g) int iresult, num1 = 25, num2 = 40; iresult = num1 / num2; (h) int num1 = 25, num2 = 40; double fresult = (double) num1 / num2; (j) int num1 = 25, num2 = 40; double fresult = (double) (num1 / num2); Team gift
22 Variable assignment EX 2.6 (page 106) What value is contained in the integer variable size after the following statements are executed? size = 18; size = size + 12; size = size * 2; size = size / 4; size += 12; size *= 2; size /= 4; size = 30; size = 60; size = 15; 3 gifts
23 Chapter 2 EX 2.8 What value is contained in the integer variable length after the following statements are executed? length = 5; length *= 2; length *= length; length /= 100; 1 gift
24 EX 2.11 (page 107) For each of the following expressions, indicate the order in which the operators will be evaluated by writing a number beneath each operator. (b) a b + c d (c) a + b / c / d (i) (a (b c)) d (l) a + (b c) * d e (n) (a + b) * (c / d) % 4 Team gift
25 Anatomy of a class public class ANewClass { public static void main (String[] args) { } } //some work is done here
26 Section 2.6 Scanner class Used to get input from user (from keyboard, from a file ). Can get Strings and numbers import java.util.scanner; public class Input { public static void main (String args) { Scanner scan = new Scanner (System.in); String message = scan.nextline(); int number = scan.nextint(); } }
27 Assignment PP 2.11 page 109 Only think at the steps that must be taken to make it happen No java code Only algorithm (English like sentences of step bystep instructions)
28 END OF MODULE
29 Today Algorithms vs. Program Exercise on Scanner object Exercise PP 2.11 Pick up of individual work Team work Submission Coverage of Applets Exercise on Applets Assignment for next lecture
30 Algorithm vs. Program Peanut butter sandwich Algorithm: English like step by step instructions Independent from the programming language Is the first step to program Program: Instructions written in the specific programming language Should follow algorithm instructions, but adapt it to the specificity of the chosen programming language
31 Practice (PP 2.3 page 109) Write an application that prompts for and reads a person s name, university name, and the year. Then print the following paragraph inserting the appropriate data. Dear name, Congratulations on being accepted to university. The semester begins in year.
32 Chapter 2 PP 2.11 Write an application that prompts for and read a double value representing a monetary amount. Then determine the fewest number of each bill and coin needed to represent that amount, starting with the highest (assume that the $10 bill is the maximum size needed). Assume Canadian monies
33 Graphics & Applets Image => Pixels Color => RGB Grayscale => I
34 Coordinate Systems Each pixel can be identified using a two dimensional coordinate system When referring to a pixel in a Java program, we use a coordinate system with the origin in the top left corner (0, 0) 112 X 40 (112, 40) Y Copyright 2009 Pearson Education, Inc Publishing as Pearson-Addison Wesley
35 The Color Class A color in a Java program is represented as an object created from the Color class The Color class also contains several predefined colors, including the following: Object Color.black Color.blue Color.cyan Color.orange Color.white Color.yellow RGB Value 0, 0, 0 0, 0, 255 0, 255, , 200, 0 255, 255, , 255, 0 Copyright 2009 Pearson Education, Inc Publishing as Pearson-Addison Wesley
36 Applets A Java application is a stand alone program with a main method (like the ones we've seen so far) A Java applet is a program that is intended to transported over the Web and executed using a web browser An applet also can be executed using the appletviewer tool of the Java Software Development Kit An applet doesn't have a main method Instead, there are several special methods that serve specific purposes Copyright 2009 Pearson Education, Inc Publishing as Pearson-Addison Wesley
37 Applets The class that defines an applet extends the Applet class This makes use of inheritance, which is explored in more detail in Chapter 8 See Einstein.java An applet is embedded into an HTML file using a tag that references the bytecode file of the applet The bytecode version of the program is transported across the web and executed by a Java interpreter that is part of the browser Copyright 2009 Pearson Education, Inc Publishing as Pearson-Addison Wesley
38 The HTML applet Tag <html> <head> <title>the Einstein Applet</title> </head> <body> <applet code="einstein.class" width=350 height=175> </applet> </body> </html> Copyright 2009 Pearson Education, Inc Publishing as Pearson-Addison Wesley
39 Drawing Shapes Let's explore some of the methods of the Graphics class that draw shapes in more detail A shape can be filled or unfilled, depending on which method is invoked The method parameters specify coordinates and sizes Shapes with curves, like an oval, are usually drawn by specifying the shape s bounding rectangle An arc can be thought of as a section of an oval Copyright 2009 Pearson Education, Inc Publishing as Pearson-Addison Wesley
40 Drawing a Line X Y page.drawline (10, 20, 150, 45); or page.drawline (150, 45, 10, 20); Copyright 2009 Pearson Education, Inc Publishing as Pearson-Addison Wesley
41 Drawing a Rectangle 50 X Y page.drawrect (50, 20, 100, 40); Copyright 2009 Pearson Education, Inc Publishing as Pearson-Addison Wesley
42 Drawing an Oval 175 X 20 bounding rectangle 80 Y 50 page.drawoval (175, 20, 50, 80); Copyright 2009 Pearson Education, Inc Publishing as Pearson-Addison Wesley
43 Set colors of background and graphics setbackground(color.cyan); page.setcolor(color.blue); page.fillrect(0,175,300,50); page.setcolor(color.yellow); page.filloval( 40, 40,80,80);
44 Chapter 2 PP 2.12 Create a revised version of the Snowman applet with the following modifications: Add to red buttons to the upper torso Make the snowman frown instead of smile Move the sun to the upper right corner of the picture GIVEN AS A LAB ASSIGNMENT (LAB 3)
45 Reading assignment Chapter 3 Check on webct for reading guidelines RAT on Tuesday: BRING YOUR CLICKERS Make sure your clicker is registered in WebCT
46 READING 2 TEST
47 Today Reading 2 Test Questions & Answers Individual test Team test Mini Lecture Correction of Exercise done last lecture (if time permits)
48 Reading 2 individual test Question 0 Are you ready? Question 1 Question 2 Question 3 Question 4 Question 5 Question 6 Question 7 Question 8 Question 9 Question 10 Question 11
49 Reading 2 Team test
50 Declaration/Initialization/Instantiation Declaration: int num; String name; Initialization: first time a variable is assigned a value num = 10; name = patricia ; Instantiation: creation of an object scan = new Scanner(System.in);
51 Method Invocation Two ways: Method static ClassName.MethodName() Method non static ObjectName.MethodName()
52 Method invocation: String class (page 119) non static public int length() Returns the number of characters in this string public charcharat (int index) Returns the character at the specified index public int compareto (String str) Returns an integer indicating if this string is lexically before (negative return value), equal to (..), or after the string str.
53 Method invocation: String class (page 119) public int length() Returns the number of characters in this string String name= patricia ; int strlenght = name.length(); strlenght = 8
54 Method invocation: String class (page 119) public char charat (int index) Returns the character at the specified index String name= patricia ; char letter = name.charat(3); Letter =
55 Method invocation: String class (page 119) String name= patricia ; char letter = name.charat(3); name index value p a t r i c i a
56 Method invocation: String class (page 119) public int compareto (String str) Returns an integer indicating if this string is lexically before (negative return value), equal to (..), or after the string str. String name1 = patricia ; String name2 = fred ; int diff = name1.compareto(name2); diff =
57 Method invocation: String class (page 119) int diff = name1.compareto(name2); patricia after Diff > 0 fred fred Diff < 0 patricia patricia Diff = 0 patricia
58 Method invocation static A method is static if the keyword static is in front of return type (e.g. Math class) public static double sqrt (double num) Returns the square root of num, which must be positive. double nb = 100; double value = Math.sqrt (nb);
59 RAT review What is the content of s1 after the following code fragment? String s1 = Lasserre ; s1 = s1.tolowercase(); s1 = Hel + s1.charat(0) + o ;
60 Correction PP 2.9 Algorithm: Ask user to input cash amount Wait for cash amount Separate dollars from cents Compute tens = dollars / 10 Compute fives = (dollars%10) / 5 Compute twonies, loonies (same idea) Compute quarters = cents / 25 Compute dimes = cents % 25)/10 Computer five & pennies (same idea) Print results
61 FUNDAMENTALS OF PROGRAMMING
62 Today Correction of PP 2.9 Coverage of end of Chapter 2 Applets Exercises on Chapter 3 Coverage of Chapter 3 Wrapper classes Frames & Panels Introduction of fundamental programming concepts Reading for next lecture
63 Correction PP 2.9 Algorithm: Ask user to input cash amount Wait for cash amount Separate dollars from cents Compute tens = dollars / 10 Compute fives = (dollars%10) / 5 Compute twonies, loonies (same idea) Compute quarters = cents / 25 Compute dimes = cents % 25)/10 Computer five & pennies (same idea) Print results
64 Today Correction of PP 2.9 Coverage of end of Chapter 2 Applets Exercises on Chapter 3 Coverage of Chapter 3 Wrapper classes Frames & Panels Introduction of fundamental programming concepts Reading for next lecture
65 Chapter 2 Graphics & Applets Image => Pixels Color => RGB Grayscale => I
66 Coordinate Systems Each pixel can be identified using a two dimensional coordinate system When referring to a pixel in a Java program, we use a coordinate system with the origin in the top left corner (0, 0) 112 X 40 (112, 40) Y Copyright 2009 Pearson Education, Inc Publishing as Pearson-Addison Wesley
67 The Color Class A color in a Java program is represented as an object created from the Color class The Color class also contains several predefined colors, including the following: Object Color.black Color.blue Color.cyan Color.orange Color.white Color.yellow RGB Value 0, 0, 0 0, 0, 255 0, 255, , 200, 0 255, 255, , 255, 0 Copyright 2009 Pearson Education, Inc Publishing as Pearson-Addison Wesley
68 Applets A Java application is a stand alone program with a main method (like the ones we've seen so far) A Java applet is a program that is intended to transported over the Web and executed using a web browser An applet also can be executed using the appletviewer tool of the Java Software Development Kit An applet doesn't have a main method Instead, there are several special methods that serve specific purposes Copyright 2009 Pearson Education, Inc Publishing as Pearson-Addison Wesley
69 Applets The class that defines an applet extends the Applet class This makes use of inheritance, which is explored in more detail in Chapter 8 See Einstein.java An applet is embedded into an HTML file using a tag that references the bytecode file of the applet The bytecode version of the program is transported across the web and executed by a Java interpreter that is part of the browser Copyright 2009 Pearson Education, Inc Publishing as Pearson-Addison Wesley
70 The HTML applet Tag <html> <head> <title>the Einstein Applet</title> </head> <body> <applet code="einstein.class" width=350 height=175> </applet> </body> </html> Copyright 2009 Pearson Education, Inc Publishing as Pearson-Addison Wesley
71 Drawing Shapes Let's explore some of the methods of the Graphics class that draw shapes in more detail A shape can be filled or unfilled, depending on which method is invoked The method parameters specify coordinates and sizes Shapes with curves, like an oval, are usually drawn by specifying the shape s bounding rectangle An arc can be thought of as a section of an oval Copyright 2009 Pearson Education, Inc Publishing as Pearson-Addison Wesley
72 Drawing a Line X Y page.drawline (10, 20, 150, 45); or page.drawline (150, 45, 10, 20); Copyright 2009 Pearson Education, Inc Publishing as Pearson-Addison Wesley
73 Drawing a Rectangle 50 X Y page.drawrect (50, 20, 100, 40); Copyright 2009 Pearson Education, Inc Publishing as Pearson-Addison Wesley
74 Drawing an Oval 175 X 20 bounding rectangle 80 Y 50 page.drawoval (175, 20, 50, 80); Copyright 2009 Pearson Education, Inc Publishing as Pearson-Addison Wesley
75 Set colors of background and graphics setbackground(color.cyan); page.setcolor(color.blue); page.fillrect(0,175,300,50); page.setcolor(color.yellow); page.filloval( 40, 40,80,80);
76 Chapter 2 PP 2.14 Create a revised version of the Snowman applet with the following modifications: Add to red buttons to the upper torso Make the snowman frown instead of smile Move the sun to the upper right corner of the picture GIVEN AS A LAB ASSIGNMENT (LAB 3)
77 Today Correction of PP 2.9 Coverage of end of Chapter 2 Applets Exercises on Chapter 3 Coverage of Chapter 3 Wrapper classes Frames & Panels Introduction of fundamental programming concepts Reading for next lecture
78 Exercise EX 3.3 page 156 Write a declaration of a String variable called change and initialize it to the characters stored in another String object called original with all the e changed to j ;
79 Exercise EX 3.8 page 156 Write an assignment statement that computes the square root of the sum of num1 and num2 and assign the result to num3.
80 Exercise EX 3.4 page 156 What output is produced by the following code fragment? String m1, m2, m3; m1 = Quest for the Holy Grail ; m2 = m1.tolowercase(); m3 = m1 + + m2; System.out.println(m3.replace( h, z ));
81 Exercise EX 3.6 page 156 Assuming that a Random object has been created called generator, what is the range of the result of each of the following expressions? a. generator.nextint(20); b. generator.nextint(8) + 1; c. generator.nextint(45) + 10; d. generator.nextint(100) 50;
82 Exercise EX 3.7 page 156 Write code to declare and instantiate an object of the Random class. Then write a list of expressions using the nextint method that generates random numbers in the following specified ranges, including the endpoints. Use the version of the nextint() method that accepts a single integer parameter a. 0 to 10 b. 0 to 500 c. 1 to 10 d. 1 to 500 e. 25 to 50 f. 10 to 15
83 Today Correction of PP 2.9 Coverage of end of Chapter 2 Applets Exercises on Chapter 3 Coverage of Chapter 3 Wrapper classes Frames & Panels Introduction of fundamental programming concepts Reading for next lecture
84 Chapter 3 Wrapper classes Can I transform String value into a number? Wrapper class: Primitive data hidden in a class: one for each primitive data Provides basic casting functions from one type to another, and various format. Integer class (page 141): static int parseint (String str) String n = 10 ; int nb=integer.parseint(n);
85 Autoboxing Automatic conversion between primitive value and corresponding wrapper object Double nb; double val = 23.4; nb = val; //autoboxing or Double nb = new Double (44.1); double val; val = nb; //autoboxing
86 Frames and Panels Frames Java container Used to display GUI based applications Displayed as a separate window Defined by the Jframe class Panels Java container Cannot be displayed on its own Must be added to another container to be displayed Helps organize components in a GUI Defined by the JPanel class
87 Examples JFrame > Window JPanel for content JLabel for text 2 labels added to Panel, and then included in Frame before being displayed.
88 Nested Panels JPanel to create subpanels Text in subpanels done with JLabel JLabel could have both text and image. Subpanels combined in another panel Panel added to Jframe
89 Today Correction of PP 2.9 Coverage of end of Chapter 2 Applets Exercises on Chapter 3 Coverage of Chapter 3 Wrapper classes Frames & Panels Introduction of fundamental programming concepts Reading for next lecture
90 Next Reading Nice to give instruction but pretty limited Only able to give instruction one after the other: Do A Do B Do C What if I want to say: Do C only if a condition is satisfied?
91 Conditional statements Option 1: Do something only if a condition is true Option 2: there is an exclusive choice between two actions based on a condition being true or false Option 3: condition might have more than 2 solutions and one must do something different depending on each of them.
92 Introduction for next reading Flow of program Sequential Block statement Conditional (or selection) statement If else statements Switch statements
93 Reading assignment Chapter 2, 5 & 6 Check on webct for reading guidelines RAT on Tuesday: BRING YOUR CLICKERS
94 Peer review Access through webct. Check forum for link & deadline Comments: Give constructive feedback to team members I will release results once I ve checked that comments are appropriate. No mark given on this one, only for feedback.
95 EXERCISES
96 Today Conditional statements Review of competition Team programming exercises Switch statement Introduction to next reading
97 Competition results Teams average before bonuses: 87% Didn t have time to look at all teams errors found but Lots of errors were correctly found on the ones I ve seen
98 Exercise Write code describe the following conditions: a) Is the integer variable num an even number if (num % 2 == 0)
99 Exercise Write code describe the following conditions: b) Is the integer variable temp between 20 and 25 (degree celsius) if (temp >= 20 && temp <= 25)
100 Exercise Write code describe the following conditions: c) Is the double variable value is within 10% of the variable limit if (Math.abs (value limit)<= 0.1*limit) (value / limit) > 0.9 && (value/ limit) < 1.1)
101 Exercise Write code describe the following conditions: d) Is the integer variable num outside of the range [10, 100] if (num < 10 num > 100)
102 Exercise Write code describe the following conditions: e) Is the character variable letter a letter of the alphabet if ((letter >= A && letter <= Z ) (letter >= a && letter <= z ))
103 Exercise PP 5.1 page 263 What is the condition for being a leap year? Year is divisible by 4 AND Option 1: Year is not divisible by 100 Option 2: Year is divisible by 100 AND Year is divisible by 400
104 Algorithm Prompt user to give a year Get year from keyboard If year in Gregorian calendar If year is leap year Print message is a leap year Else Print message not a leap year Else Print message date not in Gregorian calendar
105 Switch statement System.out.println("Enter a number"); Scanner scan = new Scanner (System.in); int number = scan.nextint(); switch (number/10){ case 0: System.out.println("pear"); break; case 1: System.out.println("apple"); case 2: case 3: case 4: System.out.println("orange"); break; case 5: System.out.println("grape"); break; default: System.out.println("other"); } What output is produced when number = 9? 1. pear 2. apple 3. orange 4. Grape What output is produced when number = 14? 1. pear, apple and orange 2. apple and orange 3. apple 4. Pear What output is produced when number = 33? 1. pear 2. orange 3. grape 4. apple and orange
106 Programming exercise Exercise PP 5.3 page 263 Design and implement an application that determines and prints the number of odd, even and zero digits in an integer value read from the keyboard. We will assume that the number has 4 digits
107 Algorithm Initialize all counters to zero Ask user for a number Read number from keyboard Get the four digits. divide digit by two and take remainder If remainder equals: Zero: increment even counter if digit equal zero, increment zero counter One: increment odd counter Print values of all counters
108
109
110 Introduction to next reading Sequential order of action Conditional statements Repetition statements Also called loops Used to repeat several times the same action(s) Three variations of the loop: While loop Do while loop For loop
111 While loop Init condition; While (condition) { } Action1; Action 2; Change condition; Change condition Init condition Condition evaluated loop Condition false Action 1 Action 2
112 Do While loop Init condition; Do { Init condition Action1; Action 2; Action 1 Change condition; } while (condition); Condition false Condition evaluated loop Action 2 Change condition
113 For loop While loop Init condition; While (condition) { } Action1; Action 2; Change condition; For loop For (init condition; condition; change condition) { Action1; Action2; }
114 Next Lecture Reading assignment on webct BRING YOUR CLICKERS
115 READING 4 TEST
116 Today Reading 4 Test Questions & Answers Individual test Team test Mini Lecture Assignment for next lecture
117 Reading 4 individual test ARE YOU READY? Question 1 Question 2 Question 3 Question 4 Question 5 Question 6 Question 7 Question 8 Question 9 Question 10
118 Reading 2 Team test
119 Questions 1, 4, 6 While loop Do While loop Init condition; Init condition; while (condition) { do{ Action1; Action1; Action 2; Action 2; Change condition; Change condition; } } while (condition) ; For loop for (init condition; condition; change condition) { Action1; Action2; }
120 Question 8 Which of the following is false about this code fragment? for (int count = 0; count < 5; count++){ System.out.println(count); } a) The variable count only exists for the duration of for loop statement. b) The incrementation is done after the body has been executed c) It prints the values 0 to 5 d) It prints the values 0 to 4
121 For loop, the 3 S s for (init condition; condition; change condition) { Action1; Action2; } for (int count = 0; count < 5; count++){ System.out.println(count); } for (start; stop; step) { Action1; Other way: Action2; }
122 Question 9 Which one of these sentences is false about this code fragment? int count = 0; do { count++; System.out.println(count); } while (count < 5); a) The body of the loop is between the curly brackets b) The semi column after the condition will generate a compilation error c) It prints the values 1 to 5 d) If the two statements in the loop are reversed, it would print the values 0 to 4.
123 Question 10 What output is produced by the following code fragment? int num = 0; while (num < 20) { System.out.println(num); num += 4; }
124 EX 6.6 page 295 Write a for loop to print the odd numbers from 1 to 99 for (int count = 1; count < 100; count += 2) System.out.println(count);
125 Exercise 6.5 page 295 Write a do loop that verifies that the user enters an even integer value. Scanner scan = new Scanner (System.in); int number; do { System.out.print ( Give an even number ); number = scan.nextint(); } while (number % 2!= 0);
126 Next assignment Homework for next lecture: Check on webct
127 LOOP EXERCISES
128 Today Pick up of home assignment Loop statements Class exercises Team programming exercises Introduction to next class Marked exercise
129 Exercise: Trace the code import java.util.scanner; public class Trace { public static void main(string[] args) { Scanner scan = new Scanner(System.in); System.out.println("Give a integer number:"); int n = scan.nextint(); System.out.println("Give another integer number:"); int d = scan.nextint(); int q = 0; while (n >= d){ n = d; q++; } int r = n; } } Steps/. variables n d na 3 q na na r na na System.out.println ("q = " + q + \nr = " + r);
130 EX 6.8 page 295 Write a code fragment that reads 10 integer values from the user and prints the highest value entered. Need a Scanner object Read 10 numbers => loop to get user s numbers Highest value entered => test each number to see if it is bigger
131 Solution Scanner scan = new Scanner (System.in); int count = 1, val, highest; System.out.print("Give a number:"); highest = scan.nextint(); while (count < 10){ System.out.print("Give a number:"); val = scan.nextint(); if (val > highest) highest = val; count++; } System.out.println("The highest value is " + highest);
132 Team work Competition: First team to complete the exercise stops the competition My correction is done immediately after 3 exercises to complete > reward to the winning team(s)
133 Exercise EX 6.9 page 295 Write a code fragment that determines and prints the number of times the character a appears in a String object called name. String name = "I want to see if it happens to work"; int count = 0; for (int position = 0; position < name.length(); position++) if (name.charat(position) == 'a') count++; System.out.println("\ a\ is present " + count +" times");
134 Exercise EX 6.10 page 295 Write a code fragment that prints the characters stored in a String object called str backward. String str = "I want to see if it works"; for (int position = str.length()-1; position >= 0; position--) System.out.print(str.charAt(position));
135 Exercise EX 6.11 page 295 Write a code fragment that prints every other character in a String object called word starting with the first character. String word = "I want to see if it works"; for (int position = 0; position < word.length(); position+=2) System.out.print(word.charAt(position));
136 EXERCISES CORRECTION
137 Today Pick up of individual assignments Correction of star exercises Correction of PP 5.8 and 5.16 Introduction of breaking problem into methods
138 Correction of PP 5.13 Algorithm for (a) For 10 lines Display right number of * Go to the next line Display * s Opposite to the line number For star = 10 to line number On the screen ********** ********* ******** ******* ****** ***** **** *** ** *
139 Program for (a) for (int line = 1; line <= 10; line++){ for (int stars = 10; stars >= line; stars--) System.out.print('*'); System.out.println(); }
140 Correction of PP 5.13 Algorithm for (b) For 10 rows Display right number of start at right position Go to the next line Display stars As many stars as line number But 10-line spaces before On the screen * ** *** **** ***** ****** ******* ******** ********* **********
141 Program for (b) for (int line = 1; line <= 10; line++){ for (int space = 10 - line; space >= 0; space--) System.out.print(" "); for (int stars = 1; stars <= line; stars++) System.out.print("*"); System.out.println(); }
142 Correction of PP 5.13 Algorithm for (c) For 10 lines Display right number of stars at right position Go to next line Display stars One less space than line number (for 1 to line-1) Opposite number of stars than lines (For star = 10 to line number) On the screen ********** ********* ******** ******* ****** ***** **** *** ** *
143 Program for (c) for (int line = 1; line <= 10; line++){ for (int spaces = 1; spaces <= line-1; spaces++) System.out.print(" "); for (int stars = 10; stars >= line; stars--) System.out.print("*"); System.out.println(); }
144 Correction of PP 5.13 Algorithm for (d) For 10 lines Display right number of stars at correct position Go to next line Display stars Number of spaces is equal to half number of stars line. Still holds true in negative values for second half of diamond spaces = 5 line Number of stars is dependant on number of spaces. But always odd number: stars = 10 2*spaces -1 On the screen * *** ***** ******* ********* ********* ******* ***** *** *
145 Program for (d) int nbspaces; for (int line = 1; line <= 10; line++){ } nbspaces = Math.abs(5 - line); for (int spaces = 1; spaces <= nbspaces; spaces++) System.out.print(" "); for (int stars = 1; stars <= 10-2*nbSpaces-1 ; stars++) System.out.print("*"); System.out.println();
146 PP 5.16 Rock, Paper, Scissor Algorithm Loop Play Rock Paper Scissor Ask user if wants to quit If yes, display statistics Stop loop when user wants to quit Rock Paper Scissor: Generate random number (rock = 0, paper = 1, scissor = 2) Ask for user choice Difference user - computer If difference = 0 => tie If difference = 1 or -1 => largest value wins If difference = 2 or -2 => smallest value wins Keep stats
147 Program Scanner scan = new Scanner (System.in); int ties = 0, userwin = 0, computerwin = 0, computerchoice, userchoice; Random gen = new Random (); String answer; boolean exit = false; while (!exit) { computerchoice = gen.nextint(3); System.out.print("Give your choice: Rock(0), Paper(1), Scissor(2)"); userchoice = scan.nextint(); System.out.println("Computer = " + computerchoice + ", User = " + userchoice);
148 switch (Math.abs(userChoice - computerchoice)){ case 0: //both are equals ties++; System.out.println("It's a tie"); break; case 1: //the largest value wins if (userchoice > computerchoice){ System.out.println("you win"); userwin++; } else { System.out.println("computer wins"); computerwin++;} break; case 2: //the smallest value wins if (userchoice < computerchoice){ System.out.println("you win"); userwin++; } else { System.out.println("computer wins"); computerwin++; } break; } System.out.print("Continue? Y/N"); answer = scan.next(); if (answer.equalsignorecase("n")) exit = true; } //display statistics }
149 PP 5.8 Hi-Lo guess Algorithm: Loop: Play Hi-Lo Ask user if wants to quit Stop loop when user wants to quit Algorithm Play Hi-Lo Pick a random number between 1 and 100 Loop Ask user for a guess or quit (zero to quit) Compare guess to random number If guess = number, display statistics on number of guesses Else If guess > number, display High Else (necessarily guess < number) display Low increase number of guesses Stop loop if guess = number or number = 0 Display statistics
150 Breakdown of program Two algorithms => Two pieces of code One in the main method. The other??? Can be done in the same file using strategy of method decomposition Method is invoked in main program Method code is separated in another location in the same file
151 Program import java.util.*; public class HiLo { public static void main (String[] args){ Random gen = new Random(); boolean exit = false; while (!exit){ //play one game playhilo(gen); } } } //test if user wants to play again exit = teststop("continue playing? Y/N");
152 Invocation vs. Declaration Use of index to find book in shelf Code as reference for book Use of table of content to find material to read in book Page number as reference for material Method Use of method invocation for method location Use of method header as reference
153 Invocation vs. declaration Declaration in class with main method public static return-type methodname (parameter list) Invocation in main program: With void as return-type methodname (parameter list values);
154 Invocation vs. declaration Invocation (main): playhilo(gen); Declaration (new method in class): public void playhilo (Random g) { //code for play Hi Lo }
155 Code for Hi-Lo public static void playhilo(random g){ Scanner scan = new Scanner (System.in); int randnum = g.nextint(100)+1; //Computer picks a number between 1 and 100 //initialize counter for statistics and game to begin int count = 0, guess; boolean quit = false; do { System.out.print("Guess the number (0 to quit): "); guess = scan.nextint(); if (guess!= 0) { //if does not want to quit count++; //increment the guess counter if (guess == randnum){ // if found System.out.println("You found it in " + count + " guesses"); quit = true; } else if (guess < randnum) //not found high or low System.out.println("The guess is low"); else System.out.println("The guess is high"); } } } while (!quit && guess!= 0); //leave either because found or because user wants to quit
156 Invocation vs. declaration Declaration in class with main method public static return-type methodname (parameter list) Invocation in main program: With something as return-type TypeOfSomething var = methodname (parameter list values); exit = teststop("continue playing? Y/N"); Method declaration?
157 Invocation vs. declaration Invocation: exit = teststop("continue playing? Y/N"); Declaration: public boolean teststop (String str) { //code for test Stop return boolean-value; }
158 Code for TestStop public static boolean teststop(string message) { Scanner scan = new Scanner (System.in); System.out.println(message); String yesno = scan.next(); if (yesno.equalsignorecase("n")) return true; else return false; } Notice: The boolean instead of void means a boolean will be returned, up to the programmer to place it into a variable (or it will be lost) The keyword return is used to return true or false After the keyword return a boolean must be returned (as indicated in the declaration) The String message indicates that this information must be provided for the method to run correctly the message variable is used to print the right message It simplifies both the main method, and the playhilo method as presented on the next slides
159 Recap. public class HiLo { public static void main (String[] args) { Random gen = new Random(); boolean exit = false; while (!exit){ //play one game playhilo(gen); } } //test if user wants to play again exit = teststop("continue playing? Y/N"); public static void playhilo (Random g) { //code for playing one game //invokes also teststop (shown on next slide) } public static boolean teststop (String message) { //code for printing message and getting answer } } //end of class
160 PP 5.16 Rock, Paper, Scissors Algorithm: Loop: Play Rock Paper Scissor Ask user if wants to quit Stop loop when user wants to quit Display win/loss/ties statistics Algorithm Play Rock Paper Scissor Randomly choose Rock (value 0) Paper (value 1) Scissor (value 2) Ask user for its choice Compare computer and user choice Difference = user - computer => value between -2 and 2 If diff = 0 => tie If diff = 1 or -1 => the largest value wins (either computer or user) If diff = 2 or -2 => the smallest value wins (either computer or user)
161 Exercise Write code for House applet such that: Everything is calculated based on the center of the house (x, y) Size of house, door, window may vary Windows are equally spaced Door is centered Roof and bushes codes is provided
162 //house position (center) int x = 100, y = 100; //house dimensions and features int househeight = 60, housewidth = 140; int roofheight = 40; int doorwidth = 20, doorheight = househeight/2; final int MAX_WINDOWS = 4; int nbwindows = MAX_WINDOWS; int windowwidth = 20, windowheight = 20;
163 Bushes code page.setcolor(color.green); //color for bushes int bushwidth, bushheight = doorheight; int spacing = housewidth/2 - doorwidth/2; bushwidth = spacing/3; //left side page.filloval(x - 3*bushWidth - doorwidth/2, y + househeight/2 - bushheight/2, bushwidth, bushheight/2); page.filloval(x - 2*bushWidth - doorwidth/2, y, bushwidth, bushheight); page.filloval(x - 1*bushWidth - doorwidth/2, y + househeight/2 - bushheight/2, bushwidth, bushheight/2);
164 Assignment for next class Will work again with the House applet example Good idea to make it work on your own machine Reading already available Good idea to start before lecture intro on Thursday Reading and RAT on Tuesday
165 DECOMPOSITION IN METHODS
166 Today Last lecture exercises Team discussion [10 min] House applet example Continuation of breaking problem into methods Introduction to object oriented design Introduction of next reading
167 Exercise Code provided 10 minutes to review Transform to have 5 methods that draw: the house outline, the door, the roof, the windows, and the bushes.
168 Invocation vs. declaration Invocation (main): methodname(parameters); Declaration (new method in class): public void methodname (ParameterList) { //code for method }
169 Exercise Create method which draw the following: the house outline, Paint method invokes this method to draw the house.
170 Draw House Idea public void paint(graphics page) {... // draw the house page.setcolor(color.lightgray); page.fillrect(x - housewidth/2, y - househeight/2, housewidth, househeight);... } public void paint(graphics page) {... // draw the house drawhouseoutline(page, x, y, housewidth, househeight);... } //method drawhouseoutline just below //TO DO.
171 Draw House Method Using method decomposition, replace the Java code in the paint method which draws the outline of the house. Method will be named drawhouseoutline. Method will be public and return a void data type. Method will take 5 parameters: Graphics object named page This is the page which the house will be drawn on Integer data named x Specifies the x coordinate for the centre of the house Integer data named y Specifies the y coordinate for the centre of the house Integer data named housewidth Specifies the width of the house Integer data named househeight Specifies the height of the house
172 Draw House Solution public void paint(graphics page) {... // draw the house drawhouseoutline(page, x, y, housewidth, househeight);... } public void drawhouseoutline(graphics page, int x, int y, } int housewidth, int househeight) { // draw the house page.setcolor(color.lightgray); page.fillrect(x - housewidth/2, y - househeight/2, housewidth, househeight);
173 Exercise Create method which draw the following: the house outline, the roof, Paint method invokes each of these methods to draw the house.
174 Draw Roof Method Using method decomposition, replace the Java code which draws the roof. Method will be named drawroof. Method will be public and return a void data type. Method takes 6 parameters: Graphics object named page Integer data named x Integer data named y Integer data named housewidth Integer data named househeight Integer data named roofheight
175 Draw Roof Solution public void paint(graphic page) {... // draw the roof drawroof(page, x, y, housewidth, househeight, roofheight);... } public void drawroof(graphics page, int x, int y, int housewidth, int househeight, int roofheight) { // draw the roof int[] xroof = {x - housewidth/2, x, x + housewidth/2}; int[] yroof = {y - househeight/2, y - househeight/2 roofheight, y - househeight/2}; page.setcolor(color.red); page.fillpolygon(xroof, yroof, xroof.length); }
176 Exercise Create method which draw the following: the house outline, the roof, the door
177 Draw Door Method Using method decomposition, replace the Java code which draws the door. Method will be named drawdoor. Method will take 5 parameters: A Graphics object to draw on, X and Y coordinates of the house, Width and Height of the door.
178 Draw Door Solution public void paint(graphics page) {... // draw the door drawdoor(page, x, y, doorwidth, doorheight);... } public void drawdoor(graphics page, int x, int y, int doorwidth, int doorheight) { // draw the door page.setcolor(color.blue); page.fillrect(x - doorwidth/2, y, doorwidth, doorheight); }
179 Exercise Create method which draw the following: the house outline, the roof, the door, the windows.
180 Draw Windows Method Using method decomposition, replace the Java code which draws the windows. Method will be named drawwindows. Method will take some parameters: The object to draw on, Location of the house, Number of windows to draw, Dimensions of the window and house.
181 Draw Windows Solution public void paint(graphics page) { }... // draw windows drawwindows(page, x, y, nbwindows, windowwidth, windowheight, housewidth, househeight); public void drawwindows(graphics page, int x, int y, int nbwindows, int windowwidth, int windowheight, int housewidth, int househeight) { } //draw windows page.setcolor(color.white); int spacing = housewidth - (nbwindows*windowwidth); for (int i = 0; i < nbwindows; i++){ page.fillrect(x - housewidth/2 + i*windowwidth + spacing*(i+1)/(nbwindows+1), y - househeight/2 + 5, windowwidth, windowheight);
182 Exercise Create method which draw the following: the house outline, the roof, the door, the windows, the bushes.
183 Draw Bushes Method Using method decomposition, replace the Java code which draws the bushes. Method will be named drawbushes. Insert parameters as required.
184 Draw Bushes Solution public void paint(graphics page) {... // bushes (3 per side) drawbushes(page, x, y, housewidth, househeight, doorwidth, doorheight); } public void drawbushes(graphics page, int x, int y, int housewidth, int househeight, int doorwidth, int doorheight) { // bushes (3 per side) page.setcolor(color.green); int bushwidth, bushheight = doorheight; int spacing = housewidth/2 doorwidth/2; bushwidth = spacing/3; page.filloval(x 3*bushWidth doorwidth/2, y + househeight/2 bushheight/2, bushwidth, bushheight/2); page.filloval(x 2*bushWidth doorwidth/2, y, bushwidth, bushheight); page.filloval(x 1*bushWidth doorwidth/2, y + househeight/2 bushheight/2, bushwidth, bushheight/2); page.filloval(x + 2*bushWidth + doorwidth/2, y + househeight/2 bushheight/2, bushwidth, bushheight/2); page.filloval(x + 1*bushWidth + doorwidth/2, y, bushwidth, bushheight); page.filloval(x + 0*bushWidth + doorwidth/2, y + househeight/2 bushheight/2, bushwidth, bushheight/2); }
185 Discussion Easier to read BUT Not much easier to program: Lots of repetition of parameters relative to the graphic page the house measurements Not much readable code as soon as more than one house must be done Not that easy to change color of roof, house, sizes, etc.
186 House Applet example
187 Better approach Object oriented Allows to separate actual application requirements from the various elements needed to complete the work For example in the house applet: Have a class House which stores all information relative to the house Draw the different elements of the house Has a method draw house that calls the drawing methods House applet only draw the house based on characteristics of object created
188 House applet example House Applet paint() method House create house objects: house 1: red roof, bushes, 4 windows house 2: orange roof, 2 windows, cyan door, no bushes house 3: gray roof, 3 windows, pink door, bushes Stores house features such as width, height, position (x,y), Graphics page draw houses house1.draw(); house2.draw(); house3.draw(); methods to: draw roof, house outline, windows, bushes, and entire drawing of the house (draw)
189 House Applet example Imports public class HouseApplet extends Applet{ public void paint(graphics page){ this.setsize(600,400); page.drawstring("my Village", 10, 10); House house1 = new House(page, 150, 150, Color.lightGray, Color.red, Color.blue, 4, true); House house2 = new House(page, 300, 150, Color.darkGray, Color.orange, Color.cyan, 2, false); House house3 = new House(page, 450, 150, Color.blue, Color.gray, Color.magenta, 3, true); House house4 = new House(page, 450, 300, Color.lightGray, Color.green, Color.darkGray, 1, true); House house5 = new House(page, 300, 300, Color.pink, Color.magenta, Color.lightGray, 3, false); house1.draw (); house2.draw (); house3.draw (); house4.draw (); house5.draw (); } }
190 House Applet example BUT where is the code for the House??? In another file called House.java Linked with HouseApplet file made by invocation: House house1 = new House(page, 150, 150, ); house1.draw ();
191 House Applet example Invocation (HouseApplet.java) Header declaration (House.java) House house1 = new House(page, );... house1.draw (); public House (Graphics page, ) { //initialization of variables } public void draw() { //code for drawing house }
192 Important keywords & words Difference Class vs. Objects Public vs. private Method headers Parameters formal/actual Accessors/mutators methods
193 Assignment for next class Chapter 4 reading Reading and RAT on Tuesday
194 OBJECTS AND CLASSES
195 Today Practice writing classes Midterm review Introduction to readings
196 tostring() method Which is easier? System.out.println( Die 1: + die1.getfacevalue()); OR System.out.println( Die 1: + die1 ); System.out.println( Die 1: + die1.tostring())
197 Exercise PP 4.6 page 202 Design and implement a class called Flight that represents an airline flight. It should contain instance data that represent the airline, flight number, and the flight s origin and destination cities Define the Flight constructor to accept and initialize all instance data Include getter and setter methods for all instance data Include a tostring method that returns a one line description of the flight Create a driver class called FlightTest, whose main method instantiates and updates several Flight objects
198 MIDTERM REVIEW
199 Midterm Question 1 Write a method that returns the temperature in Celsius degrees for a temperature value in Fahrenheit degrees. The equation is C=(F 32)*5/9. The returned temperature can be a decimal number. The temperature given in Fahrenheit is an integer value.
200 Midterm Question 2 Write a method that returns the number of occurrences of a given letter for a given string (no assumptions should be made on the string content or the letter chosen, i.e. Parameters).
201 Midterm Question 3 Write a program that reads one integer number and prints if it is prime or not (a prime number is only divisible by one and by itself).
202 Midterm Question 4 Write a program that reads one sentence as user input and prints the number of vowels and consonants used in the sentence. Note that the sentence can contain other elements than letters (e.g., punctuation, apostrophe, ).
203 INTRODUCTION TO NEXT READING
204 Static Static Can be used for a variable or a method Is independent of any object of the class: Variable: the content is shared by all objects of the class Method: no need of an object to call it (use class name) Classic use Counting objects Sharing resources between objects of the same class
205 Overloading Constructor Different number of parameters All instance data initialized no matter what Default values if not provided by parameters Method overloading Same method, different parameters print() and println()
206 The This reference Used to refer to the current object s: Variables Constructors Methods Clarifies what is called: this.variablename this( parameters); this.methodname( ); Helps diminish the number of variable names that programmers have to come up with May reduces amount of coding by referring to already existing code
207 Assignment for Thursday Reading of Chapter 7 See webct for details
208 READING 7 TEST
209 Today Reading 7Test Questions & Answers Individual test Team test Mini lecture
210 Reading 7 Individual test Question 0 Are you ready? Question 1 Question 2 Question 3 Question 4 Question 5 Question 6 Question 7 Question 8 Question 9 Question 10 Question 11
211 Reading 7 Team test
212 Question What is the value of values.length? a) 5 b) 6 c) 18 d) 7 e) 0
213 Question The statement System.out.println(values[7]) will: a) Cause an ArrayOutOfBoundsException to be thrown b) Output nothing c) Cause a syntax error d) Output 18 e) Output 7
214 Question In Java, arrays are: a) primitive data b) primitive data types if the type stored in the array is a primitive data type and objects if the type stored in the array is an object c) Objects d) Strings e) Wrappers classes
215 Question 4 Assume that BankAccount is predefined class and that the declaration BankAccount[] firstempirebank has already been performed. Then the following instruction reserves memory space for: firstempirebank = new BankAccount[1000]; a) A single BankAccount entry b) A reference variable to the memory that stores all 1000 BankAccount entries c) 1000 BankAccount entries d) 1000 reference variables and 1000 BankAccount entries e) 1000 reference variables, each of which point to a single BankAccount entry
CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University
Graphics & Applets CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Back to Chapter
More informationChapter 2 Exercise Solutions
Chapter 2 Exercise Solutions EX 2.1. EX 2.2. EX 2.3. EX 2.4. EX 2.5. Explain the following programming statement in terms of objects and the services they provide. System.out.println ("I gotta be me!");
More informationCSC 1051 Algorithms and Data Structures I. Midterm Examination October 7, Name:
CSC 1051 Algorithms and Data Structures I Midterm Examination October 7, 2013 Name: Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please answer questions in the spaces
More informationData Representation and Applets
Data Representation and Applets CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Overview Binary representation Data types revisited
More informationData Representation and Applets
Data Representation and Applets CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: http://www.csc.villanova.edu/~map/1051/
More informationData Representation and Applets
Data Representation and Applets CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: http://www.csc.villanova.edu/~map/1051/
More informationApplets and the Graphics class
Applets and the Graphics class CSC 2014 Java Bootcamp Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Some slides in this presentation are adapted from the slides accompanying
More informationCSC 1051 Algorithms and Data Structures I. Midterm Examination February 24, Name: KEY 1
CSC 1051 Algorithms and Data Structures I Midterm Examination February 24, 2014 Name: KEY 1 Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please answer questions in
More informationCSC 1051 Algorithms and Data Structures I. Midterm Examination October 9, Name: KEY
CSC 1051 Algorithms and Data Structures I Midterm Examination October 9, 2014 Name: KEY Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please answer questions in the
More informationCSC 1051 Algorithms and Data Structures I. Midterm Examination February 26, Name: Key
CSC 1051 Algorithms and Data Structures I Midterm Examination February 26, 2015 Name: Key Question Value 1 10 Score 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please answer questions in the
More informationFull file at
Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class
More informationLearning objectives: Objects and Primitive Data. Introduction to Objects. A Predefined Object. The print versus the println Methods
CSI1102 Introduction to Software Design Chapter 2: Objects and Primitive Data Learning objectives: Objects and Primitive Data Introducing objects and their properties Predefined objects: System.out Variables
More informationCSC 1051 Algorithms and Data Structures I. Midterm Examination February 25, Name: KEY A
CSC 1051 Algorithms and Data Structures I Midterm Examination February 25, 2016 Name: KEY A Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please answer questions in
More informationCSC Algorithms and Data Structures I. Midterm Examination February 25, Name:
CSC 1051-001 Algorithms and Data Structures I Midterm Examination February 25, 2016 Name: Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please answer questions in the
More informationCSC 1051 Algorithms and Data Structures I. Midterm Examination March 2, Name:
CSC 1051 Algorithms and Data Structures I Midterm Examination March 2, 2017 Name: Question Value Score 1 10 2 10 3 20 4 20 5 20 6 20 TOTAL 100 Please answer questions in the spaces provided. If you make
More informationChapter 2: Objects and Primitive Data
Chapter 2: Objects and Primitive Data Multiple Choice 1. c 2. e 3. d 4. b 5. a 6. e 7. b 8. c 9. d 10. b True/False 1. T 2. F 3. T 4. T 5. T 6. F 7. T 8. T Short Answer 2.1. Explain the following programming
More informationData and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:
Data and Expressions Data and Expressions Let's explore some other fundamental programming concepts Chapter 2 focuses on: Character Strings Primitive Data The Declaration And Use Of Variables Expressions
More informationCourse Outline. Introduction to java
Course Outline 1. Introduction to OO programming 2. Language Basics Syntax and Semantics 3. Algorithms, stepwise refinements. 4. Quiz/Assignment ( 5. Repetitions (for loops) 6. Writing simple classes 7.
More informationChapter 2: Data and Expressions
Chapter 2: Data and Expressions CS 121 Department of Computer Science College of Engineering Boise State University April 21, 2015 Chapter 2: Data and Expressions CS 121 1 / 53 Chapter 2 Part 1: Data Types
More informationCSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI
CSCI 2010 Principles of Computer Science Data and Expressions 08/09/2013 CSCI 2010 1 Data Types, Variables and Expressions in Java We look at the primitive data types, strings and expressions that are
More informationChapter. Let's explore some other fundamental programming concepts
Data and Expressions 2 Chapter 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design 2007 Pearson Addison-Wesley. All rights reserved Data and Expressions Let's explore some
More informationChapter 2: Data and Expressions
Chapter 2: Data and Expressions CS 121 Department of Computer Science College of Engineering Boise State University January 15, 2015 Chapter 2: Data and Expressions CS 121 1 / 1 Chapter 2 Part 1: Data
More informationCOMP 202 Java in one week
CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator COMP 202 Java in one week The Java Programming Language A programming language
More informationCONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2
CONTENTS: Compilation Data and Expressions COMP 202 More on Chapter 2 Programming Language Levels There are many programming language levels: machine language assembly language high-level language Java,
More informationCOMP 202 Java in one week
COMP 202 Java in one week... Continued CONTENTS: Return to material from previous lecture At-home programming exercises Please Do Ask Questions It's perfectly normal not to understand everything Most of
More informationChapter 2. Elementary Programming
Chapter 2 Elementary Programming 1 Objectives To write Java programs to perform simple calculations To obtain input from the console using the Scanner class To use identifiers to name variables, constants,
More informationReview Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013
Review Chapters 1 to 4 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections 2.1 2.5 Instructor:
More informationCOMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements
COMP-202 Unit 4: Programming With Iterations CONTENTS: The while and for statements Introduction (1) Suppose we want to write a program to be used in cash registers in stores to compute the amount of money
More informationProgram Fundamentals
Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java
More informationJava Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2
Java Foundations Introduction to Program Design and Data Structures 4th Edition Lewis TEST BANK Full download at : https://testbankreal.com/download/java-foundations-introduction-toprogram-design-and-data-structures-4th-edition-lewis-test-bank/
More informationCOMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015
COMP-202: Foundations of Programming Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015 Announcements Midterm Exams on 4 th of June (12:35 14:35) Room allocation will be announced soon
More informationChapter 3. Selections
Chapter 3 Selections 1 Outline 1. Flow of Control 2. Conditional Statements 3. The if Statement 4. The if-else Statement 5. The Conditional operator 6. The Switch Statement 7. Useful Hints 2 1. Flow of
More informationChapter 3 Syntax, Errors, and Debugging. Fundamentals of Java
Chapter 3 Syntax, Errors, and Debugging Objectives Construct and use numeric and string literals. Name and use variables and constants. Create arithmetic expressions. Understand the precedence of different
More informationCS111: PROGRAMMING LANGUAGE II
1 CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1: Introduction Lecture Contents 2 Course info Why programming?? Why Java?? Write once, run anywhere!! Java basics Input/output Variables
More informationLecture Set 2: Starting Java
Lecture Set 2: Starting Java 1. Java Concepts 2. Java Programming Basics 3. User output 4. Variables and types 5. Expressions 6. User input 7. Uninitialized Variables 0 This Course: Intro to Procedural
More informationTOPIC 2 INTRODUCTION TO JAVA AND DR JAVA
1 TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson, and instructor materials prepared
More informationLecture Set 2: Starting Java
Lecture Set 2: Starting Java 1. Java Concepts 2. Java Programming Basics 3. User output 4. Variables and types 5. Expressions 6. User input 7. Uninitialized Variables 0 This Course: Intro to Procedural
More informationLast Class. While loops Infinite loops Loop counters Iterations
Last Class While loops Infinite loops Loop counters Iterations public class January31{ public static void main(string[] args) { while (true) { forloops(); if (checkclassunderstands() ) { break; } teacharrays();
More informationSelec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal
Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program
More informationWelcome to the Primitives and Expressions Lab!
Welcome to the Primitives and Expressions Lab! Learning Outcomes By the end of this lab: 1. Be able to define chapter 2 terms. 2. Describe declarations, variables, literals and constants for primitive
More informationExpressions and Data Types CSC 121 Spring 2015 Howard Rosenthal
Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types
More informationHTML Links Tutorials http://www.htmlcodetutorial.com/ http://www.w3.org/markup/guide/ Quick Reference http://werbach.com/barebones/barebones.html Applets A Java application is a stand-alone program with
More informationWhat did we talk about last time? Examples switch statements
Week 4 - Friday What did we talk about last time? Examples switch statements History of computers Hardware Software development Basic Java syntax Output with System.out.print() Mechanical Calculation
More informationAYBUKE BUYUKCAYLI KORAY OZUYAR MUSTAFA SOYLU. Week 21/02/ /02/2007 Lecture Notes: ASCII
AYBUKE BUYUKCAYLI KORAY OZUYAR MUSTAFA SOYLU Week 21/02/2007-23/02/2007 Lecture Notes: ASCII 7 bits = 128 characters 8 bits = 256characters Unicode = 16 bits Char Boolean boolean frag; flag = true; flag
More informationProgramming with Java
Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules
More informationMcGill University School of Computer Science COMP-202A Introduction to Computing 1
McGill University School of Computer Science COMP-202A Introduction to Computing 1 Midterm Exam Thursday, October 26, 2006, 18:00-20:00 (6:00 8:00 PM) Instructors: Mathieu Petitpas, Shah Asaduzzaman, Sherif
More informationAppendix F: Java Graphics
Appendix F: Java Graphics CS 121 Department of Computer Science College of Engineering Boise State University August 21, 2017 Appendix F: Java Graphics CS 121 1 / 15 Topics Graphics and Images Coordinate
More informationIntro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming
Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals
More informationCSC 1051 Algorithms and Data Structures I. Midterm Examination October 6, Name:
CSC 1051 Algorithms and Data Structures I Midterm Examination October 6, 2016 Name: Question Value Score 1 20 2 20 3 20 4 20 5 20 TOTAL 100 Please answer questions in the spaces provided. If you make a
More informationSelec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal
Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program
More informationCMPT 125: Lecture 4 Conditionals and Loops
CMPT 125: Lecture 4 Conditionals and Loops Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 17, 2009 1 Flow of Control The order in which statements are executed
More informationPace University. Fundamental Concepts of CS121 1
Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction
More informationChapter 3: Program Statements
Chapter 3: Program Statements Multiple Choice 1 e 2 d 3 e 4 d 5 c 6 a 7 b 8 c 9 d 10 a True/False 1 T 2 F 3 F 4 F 5 T 6 F 7 T 8 T 9 F Short Answer 31 What happens in the MinOfThree program if two or more
More informationData Representation and Applets
Data Representation and Applets CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: http://www.csc.villanova.edu/~map/1051/f13
More informationCMPT 125: Lecture 3 Data and Expressions
CMPT 125: Lecture 3 Data and Expressions Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 3, 2009 1 Character Strings A character string is an object in Java,
More informationSection 2: Introduction to Java. Historical note
The only way to learn a new programming language is by writing programs in it. - B. Kernighan & D. Ritchie Section 2: Introduction to Java Objectives: Data Types Characters and Strings Operators and Precedence
More informationCOMP 202. Java in one week
COMP 202 CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator Java in one week The Java Programming Language A programming language
More informationA variable is a name for a location in memory A variable must be declared
Variables A variable is a name for a location in memory A variable must be declared, specifying the variable's name and the type of information that will be held in it data type variable name int total;
More informationExpressions and Data Types CSC 121 Fall 2015 Howard Rosenthal
Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and
More informationUsing Classes and Objects
Using Classes and Objects CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Today
More informationPractice Midterm 1 Answer Key
CS 120 Software Design I Fall 2018 Practice Midterm 1 Answer Key University of Wisconsin - La Crosse Due Date: October 5 NAME: Do not turn the page until instructed to do so. This booklet contains 10 pages
More informationH212 Introduction to Software Systems Honors
Introduction to Software Systems Honors Lecture #04: Fall 2015 1/20 Office hours Monday, Wednesday: 10:15 am to 12:00 noon Tuesday, Thursday: 2:00 to 3:45 pm Office: Lindley Hall, Room 401C 2/20 Printing
More informationCOMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string
COMP 202 Built in Libraries and objects CONTENTS: Introduction to objects Introduction to some basic Java libraries string COMP 202 Objects and Built in Libraries 1 Classes and Objects An object is an
More informationIntroduction to Programming Using Java (98-388)
Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;
More informationJava Coding 3. Over & over again!
Java Coding 3 Over & over again! Repetition Java repetition statements while (condition) statement; do statement; while (condition); where for ( init; condition; update) statement; statement is any Java
More informationAppendix F: Java Graphics
Appendix F: Java Graphics CS 121 Department of Computer Science College of Engineering Boise State University August 21, 2017 Appendix F: Java Graphics CS 121 1 / 1 Topics Graphics and Images Coordinate
More informationInstructions PLEASE READ (notice bold and underlined phrases)
Assignment 2 Writing Basic Java Programs Required Reading Java Foundations Chapter 2 Data and Expressions Chapter 3 Sections 3.1-3.2, 3.4-3.7 Chapter 4 Sections 4.2-4.5, 4.7-4.8 Instructions PLEASE READ
More informationJava I/O and Control Structures
Java I/O and Control Structures CSC 2014 Java Bootcamp Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Some slides in this presentation are adapted from the slides accompanying
More information2: Basics of Java Programming
2: Basics of Java Programming CSC 1051 Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/
More informationpublic static void main(string[] args) { GTest mywindow = new GTest(); // Title This program creates the following window and makes it visible:
Basics of Drawing Lines, Shapes, Reading Images To draw some simple graphics, we first need to create a window. The easiest way to do this in the current version of Java is to create a JFrame object which
More informationFaculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Midterm Examination
First Name: Last Name: McGill ID: Section: Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Midterm Examination Tuesday, November 4, 2008 Examiners: Mathieu Petitpas [Section 1] 18:30
More informationECE 122 Engineering Problem Solving with Java
ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction Outline Problem: How do I input data and use it in complicated expressions Creating complicated expressions
More informationDarrell Bethea May 25, 2011
Darrell Bethea May 25, 2011 Yesterdays slides updated Midterm on tomorrow in SN014 Closed books, no notes, no computer Program 3 due Tuesday 2 3 A whirlwind tour of almost everything we have covered so
More informationPrimitive Data, Variables, and Expressions; Simple Conditional Execution
Unit 2, Part 1 Primitive Data, Variables, and Expressions; Simple Conditional Execution Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Overview of the Programming Process Analysis/Specification
More informationJava I/O and Control Structures Algorithms in everyday life
Introduction Java I/O and Control Structures Algorithms in everyday life CSC 2014 Java Bootcamp Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Source: http://xkcd.com/627/
More informationCS1004: Intro to CS in Java, Spring 2005
CS4: Intro to CS in Java, Spring 25 Lecture #8: GUIs, logic design Janak J Parekh janak@cs.columbia.edu Administrivia HW#2 out New TAs, changed office hours How to create an Applet Your class must extend
More informationIntroduction to Java & Fundamental Data Types
Introduction to Java & Fundamental Data Types LECTURER: ATHENA TOUMBOURI How to Create a New Java Project in Eclipse Eclipse is one of the most popular development environments for Java, as it contains
More informationGraphics Applets. By Mr. Dave Clausen
Graphics Applets By Mr. Dave Clausen Applets A Java application is a stand-alone program with a main method (like the ones we've seen so far) A Java applet is a program that is intended to transported
More informationAP Computer Science A
AP Computer Science A 1st Quarter Notes Table of Contents - section links Click on the date or topic below to jump to that section Date : 9/8/2017 Aim : Java Basics Objects and Classes Data types: Primitive
More informationConditional Execution
Unit 3, Part 3 Conditional Execution Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Review: Simple Conditional Execution in Java if () { else {
More informationComputer Science is...
Computer Science is... Machine Learning Machine learning is the study of computer algorithms that improve automatically through experience. Example: develop adaptive strategies for the control of epileptic
More informationMethods CSC 121 Fall 2016 Howard Rosenthal
Methods CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand what a method is in Java Understand Java s Math Class and how to use it Learn the syntax of method construction Learn both void methods
More informationChapter 2: Data and Expressions
Chapter 2: Data and Expressions CS 121 Department of Computer Science College of Engineering Boise State University August 21, 2017 Chapter 2: Data and Expressions CS 121 1 / 51 Chapter 1 Terminology Review
More informationTop-Down Program Development
Top-Down Program Development Top-down development is a way of thinking when you try to solve a programming problem It involves starting with the entire problem, and breaking it down into more manageable
More informationMethods CSC 121 Spring 2017 Howard Rosenthal
Methods CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Understand what a method is in Java Understand Java s Math Class and how to use it Learn the syntax of method construction Learn both void methods
More information4 WORKING WITH DATA TYPES AND OPERATIONS
WORKING WITH NUMERIC VALUES 27 4 WORKING WITH DATA TYPES AND OPERATIONS WORKING WITH NUMERIC VALUES This application will declare and display numeric values. To declare and display an integer value in
More informationUniversità degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M
Università degli Studi di Bologna Facoltà di Ingegneria Principles, Models, and Applications for Distributed Systems M tutor Isam M. Al Jawarneh, PhD student isam.aljawarneh3@unibo.it Mobile Middleware
More informationIntroduction to Software Development (ISD) David Weston and Igor Razgon
Introduction to Software Development (ISD) David Weston and Igor Razgon Autumn term 2013 Course book The primary book supporting the ISD module is: Java for Everyone, by Cay Horstmann, 2nd Edition, Wiley,
More informationCEN 414 Java Programming
CEN 414 Java Programming Instructor: H. Esin ÜNAL SPRING 2017 Slides are modified from original slides of Y. Daniel Liang WEEK 2 ELEMENTARY PROGRAMMING 2 Computing the Area of a Circle public class ComputeArea
More informationJava How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.
Java How to Program, 9/e Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Copyright 1992-2012 by Pearson Copyright 1992-2012 by Pearson Before writing a program to solve a problem, have
More informationFaculty of Science Midterm. COMP-202B - Introduction to Computing I (Winter 2008)
Student Name: Student Number: Section: Faculty of Science Midterm COMP-202B - Introduction to Computing I (Winter 2008) Friday, March 7, 2008 Examiners: Prof. Jörg Kienzle 18:15 20:15 Mathieu Petitpas
More informationPROGRAMMING FUNDAMENTALS
PROGRAMMING FUNDAMENTALS Q1. Name any two Object Oriented Programming languages? Q2. Why is java called a platform independent language? Q3. Elaborate the java Compilation process. Q4. Why do we write
More informationJava for Non Majors. Final Study Guide. April 26, You will have an opportunity to earn 20 extra credit points.
Java for Non Majors Final Study Guide April 26, 2017 The test consists of 1. Multiple choice questions 2. Given code, find the output 3. Code writing questions 4. Code debugging question 5. Short answer
More informationMr. Monroe s Guide to Mastering Java Syntax
Mr. Monroe s Guide to Mastering Java Syntax Getting Started with Java 1. Download and install the official JDK (Java Development Kit). 2. Download an IDE (Integrated Development Environment), like BlueJ.
More informationIntroduction to Java Applications
2 Introduction to Java Applications OBJECTIVES In this chapter you will learn: To write simple Java applications. To use input and output statements. Java s primitive types. Basic memory concepts. To use
More information@Override public void start(stage primarystage) throws Exception { Group root = new Group(); Scene scene = new Scene(root);
Intro to Drawing Graphics To draw some simple graphics, we first need to create a window. The easiest way to do this in the current version of Java is to create a JavaFX application. Previous versions
More informationCSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals
CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals 1 Recall From Last Time: Java Program import java.util.scanner; public class EggBasketEnhanced { public static void main(string[]
More informationCOMP 110 Project 1 Programming Project Warm-Up Exercise
COMP 110 Project 1 Programming Project Warm-Up Exercise Creating Java Source Files Over the semester, several text editors will be suggested for students to try out. Initially, I suggest you use JGrasp,
More informationBasic Computation. Chapter 2
Basic Computation Chapter 2 Outline Variables and Expressions The Class String Keyboard and Screen I/O Documentation and Style Variables Variables store data such as numbers and letters. Think of them
More informationText User Interfaces. Keyboard IO plus
Text User Interfaces Keyboard IO plus User Interface and Model Model: objects that solve problem at hand. User interface: interacts with user getting input from user giving output to user reporting on
More information