Course overview: Introduction to programming concepts
|
|
- Howard Jefferson
- 6 years ago
- Views:
Transcription
1 Course overview: Introduction to programming concepts What is a program? The Java programming language First steps in programming Program statements and data Designing programs. This part will give an introduction to general programming concepts, and to the Java programming language. 1
2 What is a program? A program is a set of instructions which control a computer (laptop, desktop, tablet, etc) Programs can be written for huge variety of tasks: performing complex computations; financial trading; computer graphics and games; medical diagnosis and data processing; aircraft autopilot, etc Programs can read data from computer keyboard, mouse movements and actions, from data files, databases and any other sensors/data sources on the computer and from internet if connected. Programs can present information graphically on computer screen, can write to text files, or update any other device connected to computer if permitted to do so. 2
3 What is a program? Example of simple program: read a number X; read a number Y; calculate Z = (X + Y) divided by 2; display Z; This computes average of two numbers, eg: for X = 203, Y = 1965, displays
4 What is a program? Another name for programs is software as opposed to hardware, the physical computer and devices. Programs are written in text files in the format of some programming language The most widely-used programming languages are C, C++, C# and Java. We ll use Java, as it s simplest of the popular languages. Java was invented in 1995, originally for web browsers and internet software (eg., to animate web pages). Now in general use. 4
5 The Java programming language We write Java programs in text files (eg., using WordPad or JCreator), with.java file extension, eg.: Program1.java public class Program1 { public static void main(string[] args) { int X = 203; int Y = 1965; int Z = (X + Y)/2; System.out.println("The answer is: " + Z); Here, three integer-valued variables X, Y, Z are declared. X and Y are given values 203 and 1965, then Z is calculated from them, and then displayed. 5
6 Running Program1.java 6
7 First steps in programming Open the Windows console (Start; All Programs; Accessories; Command Prompt) In the Windows console, cd to the directory cllexamples where Program1.java is (on memory stick) Compile the program with javac, and run it with java: javac Program1.java java Program1 Alternatively, open Program1.java with JCreator, or use 7
8 Data in computer 8
9 First steps in programming A Java program in a file Name.java can have the text public class Name { public static void main(string[] args) { // Your program code goes here The text between the inner { brackets can change for different programs. Give programs meaningful names: Average.java would be better name for our first program. Program statements: individual instructions and steps the computer should take. 9
10 Eg.: int X = 203; Introduce an integer variable called X, and assign the value 203 to it. int Z = (X + Y)/2; Introduce an integer variable called Z, and assign (X + Y) divided by 2 to it. Statements end with a ; Try changing the values assigned to X, Y, re-compile and re-run. 10
11 First steps in programming Of course, a more useful program is one that can read inputs from user: import javax.swing.joptionpane; // dialog support public class Average { public static void main(string[] args) { String xvalue = JOptionPane.showInputDialog( "Enter 1st integer value:"); int X = Integer.parseInt(xvalue); String yvalue = JOptionPane.showInputDialog( "Enter 2nd integer value:"); int Y = Integer.parseInt(yvalue); 11
12 int Z = (X + Y)/2; System.out.println("Their average is: " + Z); The dialogs prompt user for the X, Y values. Input from user is stored in String variables xvalue, yvalue these store pieces of text. Then converted to numbers by Integer.parseInt. Eg., string 334 is converted to number
13 Average.java input dialog 13
14 First steps in programming If we enter some wrong data (not integers), our program crashes a professional program should be robust & continue despite errors Dialogs can be used to show results: JOptionPane.showMessageDialog(null, "The result is: " + Z); The User Interface of a program consists of the visual components used to exchange data between program and users in this case the input/output dialogs. Also called Graphical User Interface (GUI). 14
15 First steps in programming Alternatively, read values from console: import java.util.scanner; // input support class AverageConsole { public static void main(string[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter 1st integer value:"); int X = input.nextint(); System.out.println("Enter 2nd integer value:"); int Y = input.nextint(); int Z = (X + Y)/2; System.out.println("Their average is: " + Z); 15
16 First steps in programming Average2.java: import javax.swing.joptionpane; // dialog support public class Average2 { public static void main(string[] args) { String xvalue = JOptionPane.showInputDialog( "Enter 1st integer value:"); int X = Integer.parseInt(xvalue); String yvalue = JOptionPane.showInputDialog( "Enter 2nd integer value:"); int Y = Integer.parseInt(yvalue); int Z = (X + Y)/2; 16
17 JOptionPane.showMessageDialog(null, "Their average is: " + Z); Try changing program to calculate average of three input values. 17
18 Output from Average2.java 18
19 Program Statements Programs consist of program statements individual processing instructions, operating on variables Assignment statements assign a value to a variable: X = 530; Can also declare/introduce the variable: int X = 530; Conditional statements enable decisions to be made: if a condition is true, one behaviour is executed; if condition is false another behaviour is executed. 19
20 Max.java: import javax.swing.joptionpane; // dialog support public class Max { public static void main(string[] args) { String xvalue = JOptionPane.showInputDialog( "Enter 1st integer value:"); int X = Integer.parseInt(xvalue); String yvalue = JOptionPane.showInputDialog( "Enter 2nd integer value:"); int Y = Integer.parseInt(yvalue); int Z; if (X < Y) 20
21 { Z = Y; else { Z = X; JOptionPane.showMessageDialog(null, "The largest value is: " + Z); 21
22 The statement if (X < Y) { Z = Y; else { Z = X; tests the condition X < Y, ( is X less than Y? ), if this is true then the statement Z = Y; is executed, otherwise (if X equals Y or is larger than Y), the statement Z = X is executed. Effect is to always set Z to be the larger of X and Y. 22
23 Console version MaxConsole.java: import java.util.scanner; // input support public class MaxConsole { public static void main(string[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter 1st integer value:"); int X = input.nextint(); System.out.println("Enter 2nd integer value:"); int Y = input.nextint(); int Z; if (X < Y) { Z = Y; else { Z = X; 23
24 System.out.println("The largest value is: " + Z); 24
25 Conditions can be as complex as needed, and multiple conditions can be tested: import javax.swing.joptionpane; // dialog support public class StudentMarks { public static void main(string[] args) { String markvalue = JOptionPane.showInputDialog( "Enter the student s mark:"); int mark = Integer.parseInt(markvalue); String result; if (mark < 40) { result = "Fail"; else if (mark >= 40 && mark < 50) { result = "Pass -- grade D"; 25
26 else if (mark >= 50 && mark < 60) { result = "Pass -- grade C"; else if (mark >= 60 && mark < 70) { result = "Pass -- grade B"; else { result = "Pass -- grade A"; JOptionPane.showMessageDialog(null, "The student s result is: " + result); The symbols && mean and. result is a String variable it stores a piece of text. 26
27 Conditional Statements Examples of different cases: Input Output 10 Fail 42 Pass grade D 55 Pass grade C 67 Pass grade B 70 Pass grade A Try executing StudentMarks with other example input values. 27
28 Loop Statements Loop statements repeat some instructions over & over again until a task is completed for statements loop for a fixed number of times: for (int i = a; i <= b; i++) { statements means execute the statements with i = a, then with i = a+1, i = a+2,..., then with i = b If a > b, does nothing If a equals b, just one iteration, for x = a. 28
29 Loop Statements import javax.swing.joptionpane; // dialog support public class SumNumbers { public static void main(string[] args) { String nvalue = JOptionPane.showInputDialog( "Enter the number to sum:"); int n = Integer.parseInt(nvalue); int sum = 0; for (int i = 1; i <= n; i++) { sum = sum + i; JOptionPane.showMessageDialog(null, "The sum is: " + sum); 29
30 calculates sum of numbers from 1 to n. Results for different input values: 30
31 n sum
32 Graphics/drawing example: import javax.swing.jframe; import java.awt.graphics; import java.awt.color; import javax.swing.jpanel; // drawing support public class Drawings extends JPanel { public void paintcomponent(graphics g) { super.paintcomponent(g); for (int i = 0; i < 10; i++) { if (i % 2 == 0) { g.setcolor(color.pink); g.drawoval(10 + i*10, 10 + i*10, 50 + i*10, 50 + i*10); else 32
33 { g.setcolor(color.green); g.drawrect(10 + i*10, 10 + i*10, 50 + i*10, 50 + i*10); public static void main(string[] args) { JFrame app = new JFrame(); app.add(new Drawings()); app.setsize(300, 300); app.setvisible(true); drawoval(x, y, X, Y ) draws an oval at x, y position, of size X, Y. 33
34 Output from Drawings.java 34
35 Drawing example Notice that y=0 is at top: y increases from top to bottom, x increases from left to right. The condition if (i % 2 == 0) is true if i is an even integer (0, 2, 4, 8) in this case a pink oval is drawn at position (10 + i 10, 10 + i 10). Condition is false if i is odd (1, 3, 5, 7, 9) in this case a green rectangle is drawn at (10 + i 10, 10 + i 10). Try changing the positions & sizes to see the effect. 35
36 Graphics/drawing example: import javax.swing.jframe; import java.awt.graphics; import java.awt.color; import javax.swing.jpanel; // drawing support public class Drawings2 extends JPanel { public void paintcomponent(graphics g) { super.paintcomponent(g); for (int i = 0; i < 10; i++) { if (i % 2 == 0) { g.setcolor(color.pink); g.filloval(10 + i*10, 10 + i*10, 50 + i*10, 50 + i*10); else 36
37 { g.setcolor(color.green); g.fillrect(10 + i*10, 10 + i*10, 50 + i*10, 50 + i*10); public static void main(string[] args) { JFrame app = new JFrame(); app.add(new Drawings2()); app.setsize(300, 300); app.setvisible(true); filloval(x, y, X, Y ) draws a filled oval at x, y position, with size X, Y. 37
38 Output from Drawings2.java 38
39 Drawing spirals: import javax.swing.jframe; import java.awt.graphics; import java.awt.color; import javax.swing.jpanel; // drawing support public class Drawings3 extends JPanel { public void paintcomponent(graphics g) { super.paintcomponent(g); int centerx = getwidth()/2; int centery = getheight()/2; int radius = 20; int w = 2*radius; int h = 2*radius; g.drawarc(centerx, centery, w, h, 0, 180); int radius2 = 30; 39
40 g.drawarc(centerx - 20, centery - 10, 2*radius2, 2*radius2, 0, -180); int radius3 = 40; g.drawarc(centerx - 20, centery - 20, 2*radius3, 2*radius3, 0, 180); int radius4 = 50; g.drawarc(centerx - 40, centery - 30, 2*radius4, 2*radius4, 0, -180); int radius5 = 50; g.drawarc(centerx - 40, centery - 40, 2*radius5, 2*radius5, 0, 180); public static void main(string[] args) 40
41 { JFrame app = new JFrame(); app.add(new Drawings3()); app.setsize(300, 300); app.setvisible(true); drawarc(x, y, w, h, 0, 180) draws an anticlockwise semicircle within the box from x, y position to x+w, y+h. drawarc(x, y, w, h, 0, 180) draws a clockwise semicircle. 41
42 Output from Drawings3.java 42
43 Summary so far Simple program structure: public class Program {... Variables of integer type (int x;) these can store values of integers, eg.: -214, 0, 1, 55, 1000, , etc. Variables of String type (String s;) these can store strings/text, eg.: Result, Enter a value Assignment statements var = value; Conditional statements if (Condition) { statement1 else { statement2 Bounded loops: for (int var = a; condition; var++) { statement Simple graphics code. 43
44 More advanced Java double variables (rational numbers) Unbounded loops (while statements) What is programming? Multiple operations; recursion Multiple classes in a program Array variables. 44
45 Calculations with rational numbers double variables can store fractional values: 0.5, 2.25, , etc. Java provides functions for square root: Math.sqrt(d), x to power y, etc: Math.pow(x,y) These functions return double values in general but integers can be used as doubles (1.0, -3.0, etc). Example: calculate total amount earned if invest deposit (eg, 100) for n years at interest rate rate (eg. 5%, or 0.05). 45
46 Calculating compound interest deposit grows with interest to: total = deposit (1 + rate) n after n years at rate rate. public class Investment { public static void main(string[] args) { double amount = 100.0; // total money double deposit = 100.0; // original investment double rate = 0.05; // interest rate for (int year = 1; year <= 10; year++) { amount = deposit * Math.pow(1.0 + rate, year); System.out.println( "After " + year + " years, total is: " + amount); 46
47 Amounts after n years: n amount
48 Calculating compound interest How many years does it take for investment to double? Need while loop: public class Investment2 { public static void main(string[] args) { double amount = 100.0; // total money double deposit = 100.0; // original investment double rate = 0.05; // interest rate int year = 1; while (amount < 2*deposit) { amount = deposit * Math.pow(1.0 + rate, year); System.out.println( "After " + year + " years, total is: " + amount); 48
49 year = year + 1; A while (E) { C loop repeats C until E is false but may run forever! Here, termination when year = 15. Try changing the rate and see the effect on the result. 49
50 What is Programming? Given: a problem ( draw a spiral, find how many years it takes to double an investment at 5% interest ) First: idea for solution Second: plan an algorithm to carry out the solution Third: code up algorithm in a programming language (Java) Fourth: test/correct your code. 50
51 What is Programming? Problem to draw a spiral Idea for solution: draw semi-circles of increasing radius, joined end-to-end Algorithm: draw semi-circle 1 with radius 20, centered on panel center X, Y; draw semi-circle 2 with radius 30, displaced to X-20, Y-10, etc. Code in Java: use drawarc to draw the semi-circles Test/correct the code. Algorithms can be expressed in words before coding. 51
52 What is Programming? Problem to find number of years until investment doubles Idea for solution: calculate total amount earned for successive years, stopping when this amount is at least twice the original deposit Algorithm: compute total earned to year by amount = deposit (1.0 + rate) year for year = 1, 2, 3,... stopping when amount 2 deposit Code in Java: use while loop to repeat calculation until the stopping condition is true Test with different rates and deposits. 52
53 Reading data from files Programs can read data from files (usually, text files) Eg.: to read student marks and classify these into grades Idea is that program reads lines of text from file (should be numbers), and converts each to a grade, until end of file (eof) is reached. 53
54 import java.io.*; public class StudentMarksFile { public static void main(string[] args) { File file = new File("marks.txt"); /* default input file */ BufferedReader br; String s = ""; boolean eof = false; try { br = new BufferedReader(new FileReader(file)); catch (FileNotFoundException _e) { System.out.println("File not found: " + file); return; while (!eof) 54
55 { try { s = br.readline(); catch (IOException _ex) { System.out.println("Reading failed."); return; if (s == null) // the file has ended { eof = true; break; int mark = Integer.parseInt(s); String result; if (mark < 0 && mark > 100) { result = "Invalid mark " + mark; else if (mark < 40) { result = "Fail"; else if (mark < 50) 55
56 { result = "Pass -- grade D"; else if (mark < 60) { result = "Pass -- grade C"; else if (mark < 70) { result = "Pass -- grade B"; else { result = "Pass -- grade A"; System.out.println( "The student s result is: " + result); // ends the while loop over file 56
57 Programs with multiple operations/classes So far we ve written all code in main method of one class. This is method where execution starts. Also possible to write several operations in one class, called from main method: factorial example. For larger programs, best to create separate classes + call their code from main method. We ll show how to do this with lottery example. 57
58 Calculating factorials For integer n > 0, its factorial is product: n (n 1) public class Factorial { public static int fact(int n) { if (n <= 1) { return 1; else { return n*fact(n-1); public static void main(string[] args) { for (int n = 1; n <= 14; n++) { System.out.println( "Factorial " + n + "! = " + fact(n)); 58
59 Recursion is another way of looping: fact(5) calls fact(4), which calls fact(3), etc. return e; ends the call and returns value of e to the caller. 59
60 Calculating factorials Notice that factorials for n > 12 don t appear correct: the int type is too small to represent them, need to use long integer type instead: public class Factorial { public static long fact(int n) { if (n <= 1) { return 1; else { return n*fact(n-1); public static void main(string[] args) { for (int n = 1; n <= 21; n++) { System.out.println( "Factorial " + n + "! = " + fact(n)); 60
61 All data on a computer is finite, int variables can hold numbers up to 2,147,483,
62 Programs with multiple classes Problem to Carry out lottery with three numbers in range 1 to 30 for user to guess with five guesses Idea for solution: generate random numbers, ask user to guess these, and count correct guesses Algorithm: Generate 3 random integers in 1..30; Ask user for 5 guesses; Count and display the correct guesses Code in Java: use Random class, and nextint(30) + 1 to generate the random numbers Test with different cases of correct/incorrect guesses. 62
63 import java.util.random; // to generate random numbers import javax.swing.joptionpane; // dialog support public class Lottery { public static void main(string[] args) { Random rand = new Random(); int ball1 = 1 + rand.nextint(30); // first lottery number int ball2 = 1 + rand.nextint(30); // second lottery number int ball3 = 1 + rand.nextint(30); // third lottery number int correct = 0; for (int i = 1; i <= 5; i++) { String sguess = JOptionPane.showInputDialog("Enter your guess:"); int guess = Integer.parseInt(sguess); if (guess == ball1) { System.out.println("Correct guess of ball 1"); correct++; 63
64 else if (guess == ball2) { System.out.println("Correct guess of ball 2"); correct++; else if (guess == ball3) { System.out.println("Correct guess of ball 3"); correct++; else { System.out.println("Sorry, wrong guess!"); System.out.println("You guessed " + correct + " correct"); Random is a built-in class, rand is an instance of Random which we use in our program. 64
65 Random rand = new Random(); declares rand as variable storing an instance of Random, and assigns a new instance of Random to rand. rand.nextint(30) generates a random integer in the range 0 to
66 Array variables So far, we ve seen variables that store single items an individual integer, rational, string, or class instance Sometimes useful to have one variable storing group of items such as the 3 balls in lottery game Array variables store group of items of same kind. Eg.: int[] balls = new int[3]; declares balls as an array of 3 integers. Individual items are written as balls[0], balls[1], balls[2]. 66
67 Data in array variables 67
68 Lottery with array import java.util.random; // to generate random numbers import javax.swing.joptionpane; // dialog support public class Lottery2 { public static void main(string[] args) { Random rand = new Random(); int[] balls = new int[3]; // 3 lottery balls for (int i = 0; i < 3; i++) { balls[i] = 1 + rand.nextint(30); int correct = 0; for (int j = 1; j <= 5; j++) { String sguess = JOptionPane.showInputDialog("Enter your guess:"); int guess = Integer.parseInt(sguess); 68
69 for (int k = 0; k < 3; k++) { if (guess == balls[k]) { System.out.println("Correct guess of ball " + (k+1)); correct++; // end of if // end of inner for-loop // end of outer for-loop System.out.println("You guessed " + correct + " correct"); A loop of form for (int i = 0; i < n; i++) {... code for array[i]... is often used to process array of size n. Notice that numbering starts from 0! Array lottery version has fewer lines of code. Also, easy to change number of balls. 69
70 Summary Program structure, class definitions Variables of integer, rational, string, class instance types Array variables Assignment, conditional, loop statements Simple graphics code. 70
71 Further resources We hope you have enjoyed this course. The following are useful for further study: Java JDK can be downloaded from: oracle.com/technetwork/java/javase/downloads/ Choose the JDK option, this will provide the javac compiler and java execution tool. JCreator is a visual tool for creating and running Java programs, download from jcreator.com Java library information is here: 71
Course overview. Programming with the Java programming language (5 weeks) Website construction and management (2 weeks).
Course overview Web page design with HTML (3 weeks) Programming with the Java programming language (5 weeks) Website construction and management (2 weeks). The course will enable you to design websites,
More informationControl Statements: Part Pearson Education, Inc. All rights reserved.
1 5 Control Statements: Part 2 5.2 Essentials of Counter-Controlled Repetition 2 Counter-controlled repetition requires: Control variable (loop counter) Initial value of the control variable Increment/decrement
More informationMidterm Examination (MTA)
M105: Introduction to Programming with Java Midterm Examination (MTA) Spring 2013 / 2014 Question One: [6 marks] Choose the correct answer and write it on the external answer booklet. 1. Compilers and
More informationControl Structures (Deitel chapter 4,5)
Control Structures (Deitel chapter 4,5) 1 2 Plan Control Structures ifsingle-selection Statement if else Selection Statement while Repetition Statement for Repetition Statement do while Repetition Statement
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 informationM105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014
M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014 Question One: Choose the correct answer and write it on the external answer booklet. 1. Java is. a. case
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 informationLesson 3: Accepting User Input and Using Different Methods for Output
Lesson 3: Accepting User Input and Using Different Methods for Output Introduction So far, you have had an overview of the basics in Java. This document will discuss how to put some power in your program
More informationWhat two elements are usually present for calculating a total of a series of numbers?
Dec. 12 Running Totals and Sentinel Values What is a running total? What is an accumulator? What is a sentinel? What two elements are usually present for calculating a total of a series of numbers? Running
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 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 informationChapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.
Chapter 3 Selections Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 1 Motivations If you assigned a negative value for radius
More informationArrays. Eng. Mohammed Abdualal
Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2114) Created by Eng: Mohammed Alokshiya Modified by Eng: Mohammed Abdualal Lab 9 Arrays
More informationExample: Monte Carlo Simulation 1
Example: Monte Carlo Simulation 1 Write a program which conducts a Monte Carlo simulation to estimate π. 1 See https://en.wikipedia.org/wiki/monte_carlo_method. Zheng-Liang Lu Java Programming 133 / 149
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 informationFundamentals of Programming Data Types & Methods
Fundamentals of Programming Data Types & Methods By Budditha Hettige Overview Summary (Previous Lesson) Java Data types Default values Variables Input data from keyboard Display results Methods Operators
More informationJump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.
Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:
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 informationCheck out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.
Chapter 4 Lab Loops and Files Lab Objectives Be able to convert an algorithm using control structures into Java Be able to write a while loop Be able to write an do-while loop Be able to write a for loop
More informationReview. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char
Review Primitive Data Types & Variables int, long float, double boolean char String Mathematical operators: + - * / % Comparison: < > = == 1 1.3 Conditionals and Loops Introduction to Programming in
More informationInput from Files. Buffered Reader
Input from Files Buffered Reader Input from files is always text. You can convert it to ints using Integer.parseInt() We use BufferedReaders to minimize the number of reads to the file. The Buffer reads
More informationPlease answer the following questions. Do not re-code the enclosed codes if you have already completed them.
Dec. 9 Loops Please answer the following questions. Do not re-code the enclosed codes if you have already completed them. What is a loop? What are the three loops in Java? What do control structures do?
More information3 CREATING YOUR FIRST JAVA APPLICATION (USING WINDOWS)
GETTING STARTED: YOUR FIRST JAVA APPLICATION 15 3 CREATING YOUR FIRST JAVA APPLICATION (USING WINDOWS) GETTING STARTED: YOUR FIRST JAVA APPLICATION Checklist: The most recent version of Java SE Development
More informationChapter 2 ELEMENTARY PROGRAMMING
Chapter 2 ELEMENTARY PROGRAMMING Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk ١ Objectives To write Java programs to perform simple
More informationIntroduction to Computer Science Unit 3. Programs
Introduction to Computer Science Unit 3. Programs This section must be updated to work with repl.it Programs 1 to 4 require you to use the mod, %, operator. 1. Let the user enter an integer. Your program
More informationCIS 162 Project 1 Business Card Section 04 (Kurmas)
CIS 162 Project 1 Business Card Section 04 (Kurmas) Due Date at the start of lab on Monday, 17 September (be prepared to demo in lab) Before Starting the Project Read zybook chapter 1 and 3 Know how to
More informationObject Oriented Programming. Java-Lecture 6 - Arrays
Object Oriented Programming Java-Lecture 6 - Arrays Arrays Arrays are data structures consisting of related data items of the same type In Java arrays are objects -> they are considered reference types
More informationExample. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.
Example Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct. 1... 2 Scanner input = new Scanner(System.in); 3 int x = (int) (Math.random()
More informationLab 9: Creating a Reusable Class
Lab 9: Creating a Reusable Class Objective This will introduce the student to creating custom, reusable classes This will introduce the student to using the custom, reusable class This will reinforce programming
More informationJump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.
Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:
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 informationChapter 3 Selection Statements
Chapter 3 Selection Statements 3.1 Introduction Java provides selection statements that let you choose actions with two or more alternative courses. Selection statements use conditions. Conditions are
More informationJava GUI Test #1 Solutions 7/10/2015
SI@UCF Java GUI Test #1 Solutions 7/10/2015 1) (12 pts) Jimmy's box for crayons has dimensions L x W x H. Each crayon he puts in has a height of exactly H. Thus, he stands each crayon up in the box forming
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! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like
Indefinite loops while loop! indefinite loop: A loop where it is not obvious in advance how many times it will execute.! We often use language like " "Keep looping as long as or while this condition is
More informationNested Loops ***** ***** ***** ***** ***** We know we can print out one line of this square as follows: System.out.
Nested Loops To investigate nested loops, we'll look at printing out some different star patterns. Let s consider that we want to print out a square as follows: We know we can print out one line of this
More informationLesson 10: Quiz #1 and Getting User Input (W03D2)
Lesson 10: Quiz #1 and Getting User Input (W03D2) Balboa High School Michael Ferraro September 1, 2015 1 / 13 Do Now: Prep GitHub Repo for PS #1 You ll need to submit the 5.2 solution on the paper form
More informationCPS109 Lab 7. Source: Big Java, Chapter 7 Preparation: read Chapter 7 and the lecture notes for this week.
1 CPS109 Lab 7 Source: Big Java, Chapter 7 Preparation: read Chapter 7 and the lecture notes for this week. Objectives: 1. To practice using one- and two-dimensional arrays 2. To practice using partially
More informationCS 106 Introduction to Computer Science I
CS 106 Introduction to Computer Science I 06 / 02 / 2015 Instructor: Michael Eckmann Today s Topics Operators continue if/else statements User input Operators + when used with numeric types (e.g. int,
More informationEng. Mohammed Alokshiya
Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Computer Programming Lab (ECOM 2114) Lab 1 Introduction to Java Eng. Mohammed Alokshiya September 28, 2014 Java Programming
More informationLoops. CSE 114, Computer Science 1 Stony Brook University
Loops CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Motivation Suppose that you need to print a string (e.g., "Welcome to Java!") a user-defined times N: N?
More informationAssignment 2. Application Development
Application Development Assignment 2 Content Application Development Day 2 Lecture The lecture covers the key language elements of the Java programming language. You are introduced to numerical data and
More informationIntroduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017
Introduction to OOP with Java Instructor: AbuKhleif, Mohammad Noor Sep 2017 Lecture 03: Control Flow Statements: Selection Instructor: AbuKhleif, Mohammad Noor Sep 2017 Instructor AbuKhleif, Mohammad Noor
More informationRepe$$on CSC 121 Spring 2017 Howard Rosenthal
Repe$$on CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Learn the following three repetition structures in Java, their syntax, their similarities and differences, and how to avoid common errors when
More informationArray. Array Declaration:
Array Arrays are continuous memory locations having fixed size. Where we require storing multiple data elements under single name, there we can use arrays. Arrays are homogenous in nature. It means and
More information1. Download the JDK 6, from
1. Install the JDK 1. Download the JDK 6, from http://java.sun.com/javase/downloads/widget/jdk6.jsp. 2. Once the file is completed downloaded, execute it and accept the license agreement. 3. Select the
More informationBuilding Java Programs
Building Java Programs Chapter 5 Random Numbers reading: 5.1, 5.6 1 http://xkcd.com/221/ 2 The while loop while loop: Repeatedly executes its body as long as a logical test is true. while (test) { statement(s);
More informationExample Program. public class ComputeArea {
COMMENTS While most people think of computer programs as a tool for telling computers what to do, programs are actually much more than that. Computer programs are written in human readable language for
More informationIntroduction to Computer Programming
Introduction to Computer Programming Lecture 2- Primitive Data and Stepwise Refinement Data Types Type - A category or set of data values. Constrains the operations that can be performed on data Many languages
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 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 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 informationBuilding Java Programs
Building Java Programs Chapter 5 Lecture 5-4: do/while loops, assertions reading: 5.1, 5.5 1 The do/while loop do/while loop: Performs its test at the end of each repetition. Guarantees that the loop's
More informationCOMP-202B - Introduction to Computing I (Winter 2011) - All Sections Example Questions for In-Class Quiz
COMP-202B - Introduction to Computing I (Winter 2011) - All Sections Example Questions for In-Class Quiz The in-class quiz is intended to give you a taste of the midterm, give you some early feedback about
More informationCS 231 Data Structures and Algorithms Fall Event Based Programming Lecture 06 - September 17, Prof. Zadia Codabux
CS 231 Data Structures and Algorithms Fall 2018 Event Based Programming Lecture 06 - September 17, 2018 Prof. Zadia Codabux 1 Agenda Event-based Programming Misc. Java Operator Precedence Java Formatting
More informationKey Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent
Programming 2 Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent information Input can receive information
More informationUsing Graphics. Building Java Programs Supplement 3G
Using Graphics Building Java Programs Supplement 3G Introduction So far, you have learned how to: output to the console break classes/programs into static methods store and use data with variables write
More informationChapter 4 Loops. int x = 0; while ( x <= 3 ) { x++; } System.out.println( x );
Chapter 4 Loops Sections Pages Review Questions Programming Exercises 4.1 4.7, 4.9 4.10 104 117, 122 128 2 9, 11 13,15 16,18 19,21 2,4,6,8,10,12,14,18,20,24,26,28,30,38 Loops Loops are used to make a program
More informationComputer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming
Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #2
More informationOutline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.
OOP in Java 1 Outline 1. Getting started, primitive data types and control structures 2. Classes and objects 3. Extending classes 4. Using some standard packages 5. OOP revisited Parts 1 to 3 introduce
More informationRepe$$on CSC 121 Fall 2015 Howard Rosenthal
Repe$$on CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while
More informationCondi(onals and Loops
Condi(onals and Loops 1 Review Primi(ve Data Types & Variables int, long float, double boolean char String Mathema(cal operators: + - * / % Comparison: < > = == 2 A Founda(on for Programming any program
More informationToday. Book-keeping. File I/O. Subscribe to sipb-iap-java-students. Inner classes. Debugging tools
Today Book-keeping File I/O Subscribe to sipb-iap-java-students Inner classes http://sipb.mit.edu/iap/java/ Debugging tools Problem set 1 questions? Problem set 2 released tomorrow 1 2 So far... Reading
More informationCS 211: Methods, Memory, Equality
CS 211: Methods, Memory, Equality Chris Kauffman Week 2-1 So far... Comments Statements/Expressions Variable Types little types, what about Big types? Assignment Basic Output (Input?) Conditionals (if-else)
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 informationBuilding Java Programs
Building Java Programs Chapter 5 Lecture 5-4: do/while loops, assertions reading: 5.1, 5.5 1 The do/while loop do/while loop: Performs its test at the end of each repetition. Guarantees that the loop's
More informationProgramming Constructs Overview. Method Call System.out.print( hello ); Method Parameters
Programming Constructs Overview Method calls More selection statements More assignment operators Conditional operator Unary increment and decrement operators Iteration statements Defining methods 27 October
More informationCSE 114 Computer Science I
CSE 114 Computer Science I Iteration Cape Breton, Nova Scotia What is Iteration? Repeating a set of instructions a specified number of times or until a specific result is achieved How do we repeat steps?
More informationMethods. Eng. Mohammed Abdualal
Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2114) Created by Eng: Mohammed Alokshiya Modified by Eng: Mohammed Abdualal Lab 8 Methods
More informationBuilding Java Programs
Building Java Programs Chapter 5 Lecture 5-2: Random Numbers reading: 5.1, 5.6 1 http://xkcd.com/221/ 2 Randomness Lack of predictability: don't know what's coming next Random process: outcomes do not
More informationProgram Control Flow
Lecture slides for: Chapter 3 Program Control Flow Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2
More informationProgram Control Flow
Lecture slides for: Chapter 3 Program Control Flow Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2
More informationControls Structure for Repetition
Controls Structure for Repetition So far we have looked at the if statement, a control structure that allows us to execute different pieces of code based on certain conditions. However, the true power
More informationChapter 5 Lab Methods
Chapter 5 Lab Methods Lab Objectives Be able to write methods Be able to call methods Be able to write javadoc comments Be able to create HTML documentation using the javadoc utility Introduction Methods
More informationComputer Programming, I. Laboratory Manual. Experiment #3. Selections
Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #3
More informationCS 106 Introduction to Computer Science I
CS 106 Introduction to Computer Science I 01 / 23 / 2015 Instructor: Michael Eckmann Today s Topics Questions? Comments? Review variables variable declaration assignment (changing a variable's value) using
More informationSt. Edmund Preparatory High School Brooklyn, NY
AP Computer Science Mr. A. Pinnavaia Summer Assignment St. Edmund Preparatory High School Name: I know it has been about 7 months since you last thought about programming. It s ok. I wouldn t want to think
More information(A) 99 ** (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution
Ch 5 Arrays Multiple Choice Test 01. An array is a ** (A) data structure with one, or more, elements of the same type. (B) data structure with LIFO access. (C) data structure, which allows transfer between
More informationCOMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette
COMP 250: Java Programming I Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette Variables and types [Downey Ch 2] Variable: temporary storage location in memory.
More informationIntroduction to Computer Programming
Introduction to Computer Programming Lecture #7 - Conditional Loops The Problem with Counting Loops Many jobs involving the computer require repetition, and that this can be implemented using loops. Counting
More informationProgramming: Java. Chapter Objectives. Control Structures. Chapter 4: Control Structures I. Program Design Including Data Structures
Chapter 4: Control Structures I Java Programming: Program Design Including Data Structures Chapter Objectives Learn about control structures Examine relational and logical operators Explore how to form
More information[ the academy_of_code] Senior Beginners
[ the academy_of_code] Senior Beginners 1 Drawing Circles First step open Processing Open Processing by clicking on the Processing icon (that s the white P on the blue background your teacher will tell
More informationSupplementary Test 1
Name: Please fill in your Student Number and Name. Student Number : Student Number: University of Cape Town ~ Department of Computer Science Computer Science 1015F ~ 2009 Supplementary Test 1 Question
More informationDate: Dr. Essam Halim
Assignment (1) Date: 11-2-2013 Dr. Essam Halim Part 1: Chapter 2 Elementary Programming 1 Suppose a Scanner object is created as follows: Scanner input = new Scanner(System.in); What method do you use
More informationProgramming Problems 15th Annual Computer Science Programming Contest
Programming Problems 15th Annual Computer Science Programming Contest Department of Mathematics and Computer Science Western Carolina University March 0, 200 Criteria for Determining Scores Each program
More informationPractice Midterm 1. Problem Points Score TOTAL 50
CS 120 Software Design I Spring 2019 Practice Midterm 1 University of Wisconsin - La Crosse February 25 NAME: Do not turn the page until instructed to do so. This booklet contains 10 pages including the
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 informationTWO-DIMENSIONAL FIGURES
TWO-DIMENSIONAL FIGURES Two-dimensional (D) figures can be rendered by a graphics context. Here are the Graphics methods for drawing draw common figures: java.awt.graphics Methods to Draw Lines, Rectangles
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 informationSample Solution A10 R6.2 R6.3 R6.5. for (i = 10; i >= 0; i++)... never ends. for (i = -10; i <= 10; i = i + 3)... 6 times
Sample Solution A10 R6.2 0000000000 0123456789 0246802468 0369258147 0482604826 0505050505 0628406284 0741852963 0864208642 0987654321 R6.3 for (i = 10; i >= 0; i++)... never ends for (i = -10; i
More informationThere are several files including the start of a unit test and the method stubs in MindNumber.java. Here is a preview of what you will do:
Project MindNumber Collaboration: Solo. Complete this project by yourself with optional help from section leaders. Do not work with anyone else, do not copy any code directly, do not copy code indirectly
More informationUsing APIs. Chapter 3. Outline Fields Overall Layout. Java By Abstraction Chapter 3. Field Summary static double PI
Outline Chapter 3 Using APIs 3.1 Anatomy of an API 3.1.1 Overall Layout 3.1.2 Fields 3.1.3 Methods 3.2 A Development Walkthrough 3.2.1 3.2.2 The Mortgage Application 3.2.3 Output Formatting 3.2.4 Relational
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 informationTester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time
Tester vs. Controller Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG For effective illustrations, code examples will mostly be written in the form of a tester
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 informationRepetition CSC 121 Fall 2014 Howard Rosenthal
Repetition CSC 121 Fall 2014 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while
More informationElementary Programming
Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG Learning Outcomes Learn ingredients of elementary programming: data types [numbers, characters, strings] literal
More informationChapter 3 Selections. 3.1 Introduction. 3.2 boolean Data Type
3.1 Introduction Chapter 3 Selections Java provides selections that let you choose actions with two or more alternative courses. Selection statements use conditions. Conditions are Boolean expressions.
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 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 information