Program Elements. Notes. Exercises CHAPTER 3

Size: px
Start display at page:

Download "Program Elements. Notes. Exercises CHAPTER 3"

Transcription

1 CHAPTER 3 Program Elements Notes Chapter 3 introduces the program elements that are the underlying constructs used inside an object to define the services it contributes to a program. Without these constructs, classes, objects, and their methods cannot be made concrete. Chapter 2 introduced the abstract concepts of classes, objects and methods. Chapter 3 introduces a minimum amount of detail to be able to write useful programs. Chapter 3 establishes this detail so that Chapter 4 can lay a strong foundation, both abstract and concrete, for object-oriented programming. In this way, object-oriented programming is introduced early in the book, but in a way that is very tangible. In addition, this chapter also explores the basic activities that a programmer should go through when developing software. These activities form the cornerstone of high-quality software development and represent the first step towards a disciplined development process. We feel strongly that these issues and activities should be introduced early and often to students. Avoiding these activities only encourages students to form bad habits and practices that have to be corrected later. The Average example is implemented twice in order to demonstrate to students that alternative implementations should be considered. Exercises 3-9 What is the result of the following expressions when length equals 8, width equals 3, and height equals 2.25? Assume length and width are integer variables, and height is a floating point variable. a) length / width 8 / 3 = 2 b) length / height 8 / 2.55 = c) length % width 8 % 3 = 2 d) width % length 3 % 8 = 3 e) length * width + height 8 * = f) length + width * height * 2.25 = Give an equivalent expression for the following: a) total < sum 13

2 sum > total b) MAX <= highest highest >= MAX c) intensity > threshold threshold < intensity 3-11 Explain three reasons to use constants in a program instead of literals. Not Provided 3-12 Java is strongly typed. What does that mean? Not Provided 3-13 What is wrong with the following code fragment? Using braces and correct indentation, rewrite it so that it produces correct output. if (total == MAX) if (total < sum) System.out.println ("total equals MAX and total is less than sum"); else System.out.println ("total is not equal to MAX"); The else goes with the second if, not the first if as the indentation indicates. Use braces after first if will correct the problem. if (total == MAX) { if (total < sum) total equals MAN and total is less than sum"); else total is not equal to MAX"); 3-14 What is wrong with the following code fragment? Will this code compile if it is part of a valid program? Explain completely. if (length = MIN_LENGTH) System.out.println ("The length cannot be reduced further."); The if statement needs to be changed to: if (length == MIN_LENGTH) System.out.println ("The length cannot be reduced further."); so that the statement will check for equality. The code will not compile. Unlike other languages, the condition of an if statement must evaluate to a boolean value. 14 Chapter 3 Program Elements

3 3-15 What is wrong with the following code fragment? What are three distinct ways it could be changed to remove the flaw? count = 50; while (count >= 0) { System.out.println (count); count = count + 1; The code is an infinite loop. It could be avoided by initializing count to a negative value such that the condition is initially false, or by changing the condition such that it is initially false, or by changing the increment of count to a decrement. The third option is probably preferred, otherwise the loop has no purpose. Programming Projects 3-16 Write a program which reads an integer value and prints the sum of all even integers between 2 and the input value, inclusive. Print an error message if the input value is less than 2. Prompt accordingly. ******************************************************************* Evens.java Programming Project Application Authors: Lewis and Loftus Classes: Evens ******************************************************************* import java.io.*; public class Evens { =============================================================== Calculate and print sum of all even numbers up to and including the number entered by the user. =============================================================== public static void main(string[] args) throws IOException { int sum = 0; int count = 2; int number; BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in)); 15

4 Prompt user for an input value and store it System.out.print("Enter a number with a value of at least 2: "); System.out.flush(); number = Integer.parseInt (stdin.readline()); The program executes if the input value is at least 2. If not, the error message in the else statement is printed. if (number >= 2) { while(count <= number) { sum = sum + count; count = count + 2; The sum of all even numbers up to " + number + " is " + sum); else Minimum value of 2 required."); method main class Evens 3-17 Write a program which reads an integer value between 0 and 100 (inclusive), representing the amount of a purchase in cents. Produce an error message if the input value is not in that range. If the input is valid, determine the amount of change that would be received from one dollar, and print the number of quarters, dimes, nickels, and pennies that should be returned. Maximize the coins with the highest value. Follow the format below. The user input is shown in boldface type. Enter the purchase amount [0-100]: 36 Your change of 64 cents is given as: 2 Quarters 1 Dimes 0 Nickels 4 Pennies Hint: 64 / 25 equals 2, and 64 % 25 equals 14. ******************************************************************* Change.java Programming Project Application 16 Chapter 3 Program Elements

5 Authors: Lewis and Loftus Classes: Change ******************************************************************* import java.io.*; public class Change { ========================================================= Calculate and report the change given for a user- supplied purchase amount ========================================================= public static void main(string[] args) throws IOException { int change, purchase; int quarters, nickels, dimes, pennies; BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in)); Prompt user for an input value and store it System.out.print("Enter the purchase amount [0-100]: "); System.out.flush(); purchase = Integer.parseInt (stdin.readline()); The program executes if the input value is between 0 & 100. If not an error message is printed. if (purchase >= 0) { if (purchase <= 100) { Calculate and print the amount of change change = purchase; System.out.print("Your change of " + change); cents is given as:"); Calculate the coins to be returned Note that this changes the value of the variable "change." 17

6 quarters = (change / 25); change = change % 25; dimes = (change / 10); change = change % 10; nickels = (change / 5); change = change % 5; pennies = change; Output the result. " + quarters + " Quarter"); " + dimes + " Dimes"); " + nickels + " Nickels"); " + pennies + " Pennies"); else Purchase must between 0 and 100 cents."); else Purchase must between 0 and 100 cents."); method main class Change 3-18 In Problem 3-17, the coins were always expressed as plural even if there was only one (1 Dimes). Modify your answer to print the singular form of the word for each coin when only 1 is used. ******************************************************************* Change2.java Programming Project Application Authors: Lewis and Loftus Classes: Change2 ******************************************************************* import java.io.*; public class Change2 { ========================================================= Calculate and report the change given for a user supplied purchase amount ========================================================= public static void main(string[] args) throws IOException { 18 Chapter 3 Program Elements

7 int change, purchase; int quarters, nickels, dimes, pennies; BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in)); Prompt user for an input value and store it System.out.print("Enter the purchase amount [0-100]: "); System.out.flush(); purchase = Integer.parseInt (stdin.readline()); The program executes if the input value is between 0 & 100. If not an error message is printed. if (purchase >= 0) { if (purchase <= 100) { Calculate and print the amount of change change = purchase; System.out.print("Your change of " + change); cents is given as:"); Calculate the coins to be returned Note that this changes the value of the variable "change." quarters = (change / 25); change = change % 25; dimes = (change / 10); change = change % 10; nickels = (change / 5); change = change % 5; pennies = change; Output the result. if (quarters >= 2) else if (quarters == 1) if (dimes >= 2) " + quarters + " Quarters"); " + quarters + " Quarter"); " + dimes + " Dimes"); 19

8 else if (dimes == 1) " + dimes + " Dime"); if (nickels >= 2) else if (nickels == 1) " + nickels + " Nickels"); " + nickels + " Nickel"); if (pennies >= 2) else if (pennies == 1) " + pennies + " Pennies"); " + pennies + " Penny"); else Purchase must between 0 and 100 cents."); else Purchase must between 0 and 100 cents."); method main class Change Modify the answer to Problem 3-17 to continue processing input values until a sentinel value of -1 is entered. Change the prompt accordingly and do not print an error message when the sentinel value is entered. ******************************************************************* Change3.java Programming Project Application Authors: Lewis and Loftus Classes: Change3 ******************************************************************* import java.io.*; public class Change3 { static public int SENTINEL = -1; ========================================================= 20 Chapter 3 Program Elements

9 Calculate and report the change given for a user supplied purchase amount ========================================================= public static void main(string[] args) throws IOException { int change, purchase = 0; int quarters, nickels, dimes, pennies; boolean invalid; BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in)); while (purchase!= SENTINEL) { invalid = true; Prompt user for an input value and store it System.out.print("Enter the purchase amount [0-100]: "); System.out.flush(); purchase = Integer.parseInt (stdin.readline()); The program executes if the input value is between 0 & 100. If not an error message is printed. if (purchase >= 0) { if (purchase <= 100) { invalid = false; Calculate and print the amount of change change = purchase; System.out.print("Your change of " + change); cents is given as:"); Calculate the coins to be returned Note that this changes the value of the variable "change." quarters = (change / 25); change = change % 25; dimes = (change / 10); change = change % 10; nickels = (change / 5); 21

10 change = change % 5; pennies = change; Output the result. if (quarters >= 2) else if (quarters == 1) if (dimes >= 2) else if (dimes == 1) if (nickels >= 2) else if (nickels == 1) if (pennies >= 2) else if (pennies == 1) " + quarters + " Quarters"); " + quarters + " Quarter"); " + dimes + " Dimes"); " + dimes + " Dime"); " + nickels + " Nickels"); " + nickels + " Nickel"); " + pennies + " Pennies"); " + pennies + " Penny"); if (invalid) Purchase must between 0 and 100 cents."); method main class Change Modify the Football_Choice program so that it does not ask the receive / kickoff question unless the user wins the coin toss. Not Provided 3-21 Modify the Average program to validate the grades entered to make sure they are in the range 0 to 100, inclusive. Print an error message if a grade is not valid, then continue to collect grades. Continue to use the sentinel value to indicate the end of the input, but do not print an error message when it is entered. Do not count an invalid grade or include it as part of the running sum. ******************************************************************* 22 Chapter 3 Program Elements

11 Average3.java Programming Project Application Authors: Lewis and Loftus Classes: Average3 ******************************************************************* import java.io.*; class Average3 { static final int SENTINEL = -1; ============================================================ Modified version of Average program to validate the grades entered. Process until the sentinel value is entered. ============================================================ public static void main (String[] args) throws IOException { int max = 0, count = 0, grade = 9999; float sum = 0, average; boolean invalid; BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in)); Read and process all grades while (grade!= SENTINEL) { invalid = true; Prompt user for grades System.out.print ("Enter a grade between 0 & 100 (-1 to quit): "); System.out.flush(); grade = Integer.parseInt (stdin.readline()); if (grade >= 0) if (grade <= 100) { invalid = false; count = count + 1; sum = sum + grade; grade is in range 23

12 if (grade > max) max = grade; If input value was out of range, print error message if (invalid) { System.out.print ("Grade between 0 & 100 required "); System.out.println ("(or -1 to exit)."); if (count == 0) System.out.println ("No valid grades were entered."); else { average = sum / count; System.out.println(); System.out.println ("Total number of students: " + count); System.out.println ("Average grade: " + average); System.out.println ("Highest grade: " + max); method main class Average Modify the Average program to determine and produce the minimum grade in addition to the maximum. ******************************************************************* Average4.java Programming Project Application Authors: Lewis and Loftus Classes: Average4 ******************************************************************* import java.io.*; class Average4 { static final int SENTINEL = -1; ============================================================ 24 Chapter 3 Program Elements

13 Modified version of Average program to validate the grades entered, process until the sentinel value is entered, and record and print min grade. ============================================================ public static void main (String[] args) throws IOException { int max = 0, min = 101; int count = 0, grade = 101; float sum = 0, average; boolean invalid; BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in)); Read and process all grades while (grade!= SENTINEL) { invalid = true; Prompt user for grades System.out.print ("Enter a grade between 0 & 100 (-1 to quit): "); System.out.flush(); grade = Integer.parseInt (stdin.readline()); if (grade >= 0) if (grade <= 100) { invalid = false; count = count + 1; sum = sum + grade; if (grade > max) max = grade; if (grade < min) min = grade; grade is in range If input value was out of range, print error message if (invalid) { System.out.print ("Grade between 0 & 100 required "); System.out.println ("(or -1 to exit)."); if (count == 0) System.out.println ("No valid grades were entered."); 25

14 else { average = sum / count; System.out.println(); System.out.println ("Total number of students: " + count); System.out.println ("Average grade: " + average); System.out.println ("Highest grade: " + max); System.out.println ("Lowest grade: " + min); method main class Average Modify the Average program to read and process exactly 17 grades. ******************************************************************* Average5.java Programming Project Application Authors: Lewis and Loftus Classes: Average5 ******************************************************************* import java.io.*; class Average5 { static final int STUDENTS = 17; ============================================================ Modified version of Average program to validate the grades entered. Process 17 students exactly. ============================================================ public static void main (String[] args) throws IOException { int max = 0, min = 101; int count = 0, grade = 101; float sum = 0, average; boolean invalid; BufferedReader stdin = new BufferedReader 26 Chapter 3 Program Elements

15 (new InputStreamReader (System.in)); Read and process all grades while (count < STUDENTS ) { invalid = true; Prompt user for grades System.out.print ("Enter a grade for student #" + (count+1) + ":"); System.out.flush(); grade = Integer.parseInt (stdin.readline()); if (grade >= 0) if (grade <= 100) { invalid = false; count = count + 1; sum = sum + grade; if (grade > max) max = grade; if (grade < min) min = grade; grade is in range If input value was out of range, print error message if (invalid) { System.out.print ("Grade between 0 & 100 required."); average = sum / count; System.out.println(); System.out.println ("Total number of students: " + count); System.out.println ("Average grade: " + average); System.out.println ("Highest grade: " + max); System.out.println ("Lowest grade: " + min); method main class Average5 27

16 3-24 Modify the Average program to prompt for and read the exact number of students in the class, then loop until exactly that many valid grades have been read. ******************************************************************* Average6.java Programming Project Application Authors: Lewis and Loftus Classes: Average6 ******************************************************************* import java.io.*; class Average6 { ============================================================ Modified version of Average program to validate the grades entered. Process n students exactly. ============================================================ public static void main (String[] args) throws IOException { int max = 0, min = 101; int count = 0, grade = 101; float sum = 0, average; int number_students; boolean invalid; BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in)); Prompt user for number of grades System.out.print("Enter a the number of scores to be processed: "); System.out.flush(); number_students = Integer.parseInt (stdin.readline()); Read and process all grades while (count < number_students ) { invalid = true; Prompt user for grades System.out.print ("Enter a grade for student #" + (count+1) + ":"); 28 Chapter 3 Program Elements

17 System.out.flush(); grade = Integer.parseInt (stdin.readline()); if (grade >= 0) if (grade <= 100) { invalid = false; count = count + 1; sum = sum + grade; if (grade > max) max = grade; if (grade < min) min = grade; grade is in range If input value was out of range, print error message if (invalid) { System.out.print ("Grade between 0 & 100 required."); average = sum / count; System.out.println(); System.out.println ("Total number of students: " + count); System.out.println ("Average grade: " + average); System.out.println ("Highest grade: " + max); System.out.println ("Lowest grade: " + min); method main class Average6 29

18 30 Chapter 3 Program Elements

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius Programming Concepts Practice Test 1 1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius 2) Consider the following statement: System.out.println("1

More information

AP Computer Science Static Methods, Strings, User Input

AP Computer Science Static Methods, Strings, User Input AP Computer Science Static Methods, Strings, User Input Static Methods The Math class contains a special type of methods, called static methods. A static method DOES NOT operate on an object. This is because

More information

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

System.out.println(\nEnter Product Number 1-5 (0 to stop and view summary) : Benjamin Michael Java Homework 3 10/31/2012 1) Sales.java Code // Sales.java // Program calculates sales, based on an input of product // number and quantity sold import java.util.scanner; public class

More information

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O 1 Sending Output to a (Text) File import java.util.scanner; import java.io.*; public class TextFileOutputDemo1 public static void

More information

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 Oct 4, 2013, p 1 Name: CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 1. (max 18) 4. (max 16) 2. (max 12) 5. (max 12) 3. (max 24) 6. (max 18) Total: (max 100)

More information

First Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science

First Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science First Java Programs V. Paúl Pauca Department of Computer Science Wake Forest University CSC 111D Fall, 2015 Hello World revisited / 8/23/15 The f i r s t o b l i g a t o r y Java program @author Paul Pauca

More information

Iteration CHAPTER 6. Topic Summary

Iteration CHAPTER 6. Topic Summary CHAPTER 6 Iteration TOPIC OUTLINE 6.1 while Loops 6.2 for Loops 6.3 Nested Loops 6.4 Off-by-1 Errors 6.5 Random Numbers and Simulations 6.6 Loop Invariants (AB only) Topic Summary 6.1 while Loops Many

More information

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION 1. Write a loop that computes (No need to write a complete program) 100 1 99 2 98 3 97... 4 3 98 2 99 1 100 Note: this is not the only solution; double sum

More information

Sample CSE8A midterm Multiple Choice (circle one)

Sample CSE8A midterm Multiple Choice (circle one) Sample midterm Multiple Choice (circle one) (2 pts) Evaluate the following Boolean expressions and indicate whether short-circuiting happened during evaluation: Assume variables with the following names

More information

public static void main(string[] args) { System.out.println("hello, world"); } }

public static void main(string[] args) { System.out.println(hello, world); } } Java in 21 minutes hello world basic data types classes & objects program structure constructors garbage collection I/O exceptions Strings Hello world import java.io.*; public class hello { public static

More information

Chulalongkorn University International School of Engineering Department of Computer Engineering 2140105 Computer Programming Lab.

Chulalongkorn University International School of Engineering Department of Computer Engineering 2140105 Computer Programming Lab. Chulalongkorn University Name International School of Engineering Student ID Department of Computer Engineering Station No. 2140105 Computer Programming Lab. Date Lab 2 Using Java API documents, command

More information

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language Translation Translating to Java Introduction to Computer Programming The job of a programmer is to translate a problem description into a computer language. You need to be able to convert a problem description

More information

J a v a Quiz (Unit 3, Test 0 Practice)

J a v a Quiz (Unit 3, Test 0 Practice) Computer Science S-111a: Intensive Introduction to Computer Science Using Java Handout #11 Your Name Teaching Fellow J a v a Quiz (Unit 3, Test 0 Practice) Multiple-choice questions are worth 2 points

More information

Introduction to Java Applications. 2005 Pearson Education, Inc. All rights reserved.

Introduction to Java Applications. 2005 Pearson Education, Inc. All rights reserved. 1 2 Introduction to Java Applications 2.2 First Program in Java: Printing a Line of Text 2 Application Executes when you use the java command to launch the Java Virtual Machine (JVM) Sample program Displays

More information

Lesson: All About Sockets

Lesson: All About Sockets All About Sockets http://java.sun.com/docs/books/tutorial/networking/sockets/index.html Page 1 sur 1 The Java TM Tutorial Start of Tutorial > Start of Trail Trail: Custom Networking Lesson: All About Sockets

More information

Using Files as Input/Output in Java 5.0 Applications

Using Files as Input/Output in Java 5.0 Applications Using Files as Input/Output in Java 5.0 Applications The goal of this module is to present enough information about files to allow you to write applications in Java that fetch their input from a file instead

More information

Basics of Java Programming Input and the Scanner class

Basics of Java Programming Input and the Scanner class Basics of Java Programming Input and the Scanner class 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 information

Chapter 2 Introduction to Java programming

Chapter 2 Introduction to Java programming Chapter 2 Introduction to Java programming 1 Keywords boolean if interface class true char else package volatile false byte final switch while throws float private case return native void protected break

More information

Java Basics: Data Types, Variables, and Loops

Java Basics: Data Types, Variables, and Loops Java Basics: Data Types, Variables, and Loops If debugging is the process of removing software bugs, then programming must be the process of putting them in. - Edsger Dijkstra Plan for the Day Variables

More information

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard INPUT & OUTPUT I/O Example Using keyboard input for characters import java.util.scanner; class Echo{ public static void main (String[] args) { Scanner sc = new Scanner(System.in); // scanner for the keyboard

More information

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013 Masters programmes in Computer Science and Information Systems Object-Oriented Design and Programming Sample module entry test xxth December 2013 This sample paper has more questions than the real paper

More information

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10) File class in Java File Input and Output (Savitch, Chapter 10) TOPICS File Input Exception Handling File Output Programmers refer to input/output as "I/O". The File class represents files as objects. The

More information

5.2 Q2 The control variable of a counter-controlled loop should be declared as: a.int. b.float. c.double. d.any of the above. ANS: a. int.

5.2 Q2 The control variable of a counter-controlled loop should be declared as: a.int. b.float. c.double. d.any of the above. ANS: a. int. Java How to Program, 5/e Test Item File 1 of 5 Chapter 5 Section 5.2 5.2 Q1 Counter-controlled repetition requires a.a control variable and initial value. b.a control variable increment (or decrement).

More information

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

CSE 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 EggBasket { public static void main(string[]

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 4 Lecture 4-1: Scanner; if/else reading: 3.3 3.4, 4.1 Interactive Programs with Scanner reading: 3.3-3.4 1 Interactive programs We have written programs that print console

More information

13 File Output and Input

13 File Output and Input SCIENTIFIC PROGRAMMING -1 13 File Output and Input 13.1 Introduction To make programs really useful we have to be able to input and output data in large machinereadable amounts, in particular we have to

More information

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner java.util.scanner java.util.scanner is a class in the Java API used to create a Scanner object, an extremely versatile object that you can use to input alphanumeric characters from several input sources

More information

Creating a Simple, Multithreaded Chat System with Java

Creating a Simple, Multithreaded Chat System with Java Creating a Simple, Multithreaded Chat System with Java Introduction by George Crawford III In this edition of Objective Viewpoint, you will learn how to develop a simple chat system. The program will demonstrate

More information

LAB4 Making Classes and Objects

LAB4 Making Classes and Objects LAB4 Making Classes and Objects Objective The main objective of this lab is class creation, how its constructer creation, object creation and instantiation of objects. We will use the definition pane to

More information

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. Exam Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) The JDK command to compile a class in the file Test.java is A) java Test.java B) java

More information

INPUT AND OUTPUT STREAMS

INPUT AND OUTPUT STREAMS INPUT AND OUTPUT The Java Platform supports different kinds of information sources and information sinks. A program may get data from an information source which may be a file on disk, a network connection,

More information

LOOPS CHAPTER CHAPTER GOALS

LOOPS CHAPTER CHAPTER GOALS jfe_ch04_7.fm Page 139 Friday, May 8, 2009 2:45 PM LOOPS CHAPTER 4 CHAPTER GOALS To learn about while, for, and do loops To become familiar with common loop algorithms To understand nested loops To implement

More information

Topic 11 Scanner object, conditional execution

Topic 11 Scanner object, conditional execution Topic 11 Scanner object, conditional execution "There are only two kinds of programming languages: those people always [complain] about and those nobody uses." Bjarne Stroustroup, creator of C++ Copyright

More information

This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output: 1 2 3 4 5 6 7 8 9 10

This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output: 1 2 3 4 5 6 7 8 9 10 Java Loops & Methods The while loop Syntax: while ( condition is true ) { do these statements Just as it says, the statements execute while the condition is true. Once the condition becomes false, execution

More information

Programming Languages CIS 443

Programming Languages CIS 443 Course Objectives Programming Languages CIS 443 0.1 Lexical analysis Syntax Semantics Functional programming Variable lifetime and scoping Parameter passing Object-oriented programming Continuations Exception

More information

Chapter 2 Elementary Programming

Chapter 2 Elementary Programming Chapter 2 Elementary Programming 2.1 Introduction You will learn elementary programming using Java primitive data types and related subjects, such as variables, constants, operators, expressions, and input

More information

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75 Preet raj Core Java and Databases CS4PR Time Allotted: 3 Hours Final Exam: Total Possible Points 75 Q1. What is difference between overloading and overriding? 10 points a) In overloading, there is a relationship

More information

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement CompSci 125 Lecture 08 Chapter 5: Conditional Statements Chapter 4: return Statement Homework Update HW3 Due 9/20 HW4 Due 9/27 Exam-1 10/2 Programming Assignment Update p1: Traffic Applet due Sept 21 (Submit

More information

Homework/Program #5 Solutions

Homework/Program #5 Solutions Homework/Program #5 Solutions Problem #1 (20 points) Using the standard Java Scanner class. Look at http://natch3z.blogspot.com/2008/11/read-text-file-using-javautilscanner.html as an exampleof using the

More information

Files and input/output streams

Files and input/output streams Unit 9 Files and input/output streams Summary The concept of file Writing and reading text files Operations on files Input streams: keyboard, file, internet Output streams: file, video Generalized writing

More information

CS 121 Intro to Programming:Java - Lecture 11 Announcements

CS 121 Intro to Programming:Java - Lecture 11 Announcements CS 121 Intro to Programming:Java - Lecture 11 Announcements Next Owl assignment up, due Friday (it s short!) Programming assignment due next Monday morning Preregistration advice: More computing? Take

More information

In this Chapter you ll learn:

In this Chapter you ll learn: Now go, write it before them in a table, and note it in a book. Isaiah 30:8 To go beyond is as wrong as to fall short. Confucius Begin at the beginning, and go on till you come to the end: then stop. Lewis

More information

Part I. Multiple Choice Questions (2 points each):

Part I. Multiple Choice Questions (2 points each): Part I. Multiple Choice Questions (2 points each): 1. Which of the following is NOT a key component of object oriented programming? (a) Inheritance (b) Encapsulation (c) Polymorphism (d) Parallelism ******

More information

Object-Oriented Programming in Java

Object-Oriented Programming in Java CSCI/CMPE 3326 Object-Oriented Programming in Java Class, object, member field and method, final constant, format specifier, file I/O Dongchul Kim Department of Computer Science University of Texas Rio

More information

Unit 6. Loop statements

Unit 6. Loop statements Unit 6 Loop statements Summary Repetition of statements The while statement Input loop Loop schemes The for statement The do statement Nested loops Flow control statements 6.1 Statements in Java Till now

More information

Everyday Math Online Games (Grades 1 to 3)

Everyday Math Online Games (Grades 1 to 3) Everyday Math Online Games (Grades 1 to 3) FOR ALL GAMES At any time, click the Hint button to find out what to do next. Click the Skip Directions button to skip the directions and begin playing the game.

More information

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I CS 106 Introduction to Computer Science I 01 / 21 / 2014 Instructor: Michael Eckmann Today s Topics Introduction Homework assignment Review the syllabus Review the policies on academic dishonesty and improper

More information

COSC 1020 3.0 Introduction to Computer Science I Section A, Summer 2005. Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

COSC 1020 3.0 Introduction to Computer Science I Section A, Summer 2005. Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19 Term Test #2 COSC 1020 3.0 Introduction to Computer Science I Section A, Summer 2005 Family Name: Given Name(s): Student Number: Question Out of Mark A Total 16 B-1 7 B-2 4 B-3 4 B-4 4 B Total 19 C-1 4

More information

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Handout 1 CS603 Object-Oriented Programming Fall 15 Page 1 of 11 Handout 1 Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Java

More information

Mail User Agent Project

Mail User Agent Project Mail User Agent Project Tom Kelliher, CS 325 100 points, due May 4, 2011 Introduction (From Kurose & Ross, 4th ed.) In this project you will implement a mail user agent (MUA) that sends mail to other users.

More information

Visual Logic Instructions and Assignments

Visual Logic Instructions and Assignments Visual Logic Instructions and Assignments Visual Logic can be installed from the CD that accompanies our textbook. It is a nifty tool for creating program flowcharts, but that is only half of the story.

More information

Moving from CS 61A Scheme to CS 61B Java

Moving from CS 61A Scheme to CS 61B Java Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you

More information

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq Introduction to Programming using Java wertyuiopasdfghjklzxcvbnmqwertyui

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 5 Lecture 5-2: Random Numbers reading: 5.1-5.2 self-check: #8-17 exercises: #3-6, 10, 12 videos: Ch. 5 #1-2 1 The Random class A Random object generates pseudo-random* numbers.

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: 3.3-3.4 self-check: #16-19 exercises: #11 videos: Ch. 3 #4 Interactive programs We have written programs that print

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: 3.3-3.4 self-check: #16-19 exercises: #11 videos: Ch. 3 #4 Interactive programs We have written programs that print

More information

Conditionals (with solutions)

Conditionals (with solutions) Conditionals (with solutions) For exercises 1 to 27, indicate the output that will be produced. Assume the following declarations: final int MAX = 25, LIMIT = 100; int num1 = 12, num2 = 25, num3 = 87;

More information

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be... What is a Loop? CSC Intermediate Programming Looping A loop is a repetition control structure It causes a single statement or a group of statements to be executed repeatedly It uses a condition to control

More information

Introduction to Java

Introduction to Java Introduction to Java The HelloWorld program Primitive data types Assignment and arithmetic operations User input Conditional statements Looping Arrays CSA0011 Matthew Xuereb 2008 1 Java Overview A high

More information

Building a Multi-Threaded Web Server

Building a Multi-Threaded Web Server Building a Multi-Threaded Web Server In this lab we will develop a Web server in two steps. In the end, you will have built a multi-threaded Web server that is capable of processing multiple simultaneous

More information

JAVA - FILES AND I/O

JAVA - FILES AND I/O http://www.tutorialspoint.com/java/java_files_io.htm JAVA - FILES AND I/O Copyright tutorialspoint.com The java.io package contains nearly every class you might ever need to perform input and output I/O

More information

Introduction to Java. Module 12: Networking (Java Sockets) Prepared by Costantinos Costa for EPL 233. ΕΠΛ233 Αντικειμενοστρεφής Προγραμματισμός 1

Introduction to Java. Module 12: Networking (Java Sockets) Prepared by Costantinos Costa for EPL 233. ΕΠΛ233 Αντικειμενοστρεφής Προγραμματισμός 1 Introduction to Java Module 12: Networking (Java Sockets) Prepared by Costantinos Costa for EPL 233 ΕΠΛ233 Αντικειμενοστρεφής Προγραμματισμός 1 What Is a Socket? A socket is one end-point of a two-way

More information

Course Intro Instructor Intro Java Intro, Continued

Course Intro Instructor Intro Java Intro, Continued Course Intro Instructor Intro Java Intro, Continued The syllabus Java etc. To submit your homework, do Team > Share Your repository name is csse220-200830-username Use your old SVN password. Note to assistants:

More information

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements 9 Control Statements 9.1 Introduction The normal flow of execution in a high level language is sequential, i.e., each statement is executed in the order of its appearance in the program. However, depending

More information

The following four software tools are needed to learn to program in Java:

The following four software tools are needed to learn to program in Java: Getting Started In this section, we ll see Java in action. Some demo programs will highlight key features of Java. Since we re just getting started, these programs are intended only to pique your interest.

More information

Stream Classes and File I/O

Stream Classes and File I/O Stream Classes and File I/O A stream is any input source or output destination for data. The Java API includes about fifty classes for managing input/output streams. Objects of these classes can be instantiated

More information

Software Testing. Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program.

Software Testing. Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program. Software Testing Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program. Testing can only reveal the presence of errors and not the

More information

Evaluation. Copy. Evaluation Copy. Chapter 7: Using JDBC with Spring. 1) A Simpler Approach... 7-2. 2) The JdbcTemplate. Class...

Evaluation. Copy. Evaluation Copy. Chapter 7: Using JDBC with Spring. 1) A Simpler Approach... 7-2. 2) The JdbcTemplate. Class... Chapter 7: Using JDBC with Spring 1) A Simpler Approach... 7-2 2) The JdbcTemplate Class... 7-3 3) Exception Translation... 7-7 4) Updating with the JdbcTemplate... 7-9 5) Queries Using the JdbcTemplate...

More information

Introduction to Java. CS 3: Computer Programming in Java

Introduction to Java. CS 3: Computer Programming in Java Introduction to Java CS 3: Computer Programming in Java Objectives Begin with primitive data types Create a main class with helper methods Learn how to call built-in class methods and instance methods

More information

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4 JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4 NOTE: SUN ONE Studio is almost identical with NetBeans. NetBeans is open source and can be downloaded from www.netbeans.org. I

More information

The C Programming Language course syllabus associate level

The C Programming Language course syllabus associate level TECHNOLOGIES The C Programming Language course syllabus associate level Course description The course fully covers the basics of programming in the C programming language and demonstrates fundamental programming

More information

AP Computer Science Java Subset

AP Computer Science Java Subset APPENDIX A AP Computer Science Java Subset The AP Java subset is intended to outline the features of Java that may appear on the AP Computer Science A Exam. The AP Java subset is NOT intended as an overall

More information

An Overview of Java. overview-1

An Overview of Java. overview-1 An Overview of Java overview-1 Contents What is Java Major Java features Java virtual machine Java programming language Java class libraries (API) GUI Support in Java Networking and Threads in Java overview-2

More information

Java Program Coding Standards 4002-217-9 Programming for Information Technology

Java Program Coding Standards 4002-217-9 Programming for Information Technology Java Program Coding Standards 4002-217-9 Programming for Information Technology Coding Standards: You are expected to follow the standards listed in this document when producing code for this class. Whether

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 28, 2010 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

Arrays in Java. Working with Arrays

Arrays in Java. Working with Arrays Arrays in Java So far we have talked about variables as a storage location for a single value of a particular data type. We can also define a variable in such a way that it can store multiple values. Such

More information

Reading Input From A File

Reading Input From A File Reading Input From A File In addition to reading in values from the keyboard, the Scanner class also allows us to read in numeric values from a file. 1. Create and save a text file (.txt or.dat extension)

More information

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand: Introduction to Programming and Algorithms Module 2 CS 146 Sam Houston State University Dr. Tim McGuire Introduction To Computers And Java Chapter Objectives To understand: the meaning and placement of

More information

Example of a Java program

Example of a Java program Example of a Java program class SomeNumbers static int square (int x) return x*x; public static void main (String[] args) int n=20; if (args.length > 0) // change default n = Integer.parseInt(args[0]);

More information

Event-Driven Programming

Event-Driven Programming Event-Driven Programming Lecture 4 Jenny Walter Fall 2008 Simple Graphics Program import acm.graphics.*; import java.awt.*; import acm.program.*; public class Circle extends GraphicsProgram { public void

More information

Chapter 2: Elements of Java

Chapter 2: Elements of Java Chapter 2: Elements of Java Basic components of a Java program Primitive data types Arithmetic expressions Type casting. The String type (introduction) Basic I/O statements Importing packages. 1 Introduction

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa September 14, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

Continuous Integration Part 2

Continuous Integration Part 2 1 Continuous Integration Part 2 This blog post is a follow up to my blog post Continuous Integration (CI), in which I described how to execute test cases in Code Tester (CT) in a CI environment. What I

More information

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit. Scanner The Scanner class is intended to be used for input. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit. For example, suppose the input

More information

Division of Informatics, University of Edinburgh

Division of Informatics, University of Edinburgh CS1Bh Lecture Note 20 Client/server computing A modern computing environment consists of not just one computer, but several. When designing such an arrangement of computers it might at first seem that

More information

Lecture 1 Introduction to Java

Lecture 1 Introduction to Java Programming Languages: Java Lecture 1 Introduction to Java Instructor: Omer Boyaci 1 2 Course Information History of Java Introduction First Program in Java: Printing a Line of Text Modifying Our First

More information

Lecture J - Exceptions

Lecture J - Exceptions Lecture J - Exceptions Slide 1 of 107. Exceptions in Java Java uses the notion of exception for 3 related (but different) purposes: Errors: an internal Java implementation error was discovered E.g: out

More information

Introduction to Programming

Introduction to Programming Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems sjmaybank@dcs.bbk.ac.uk Spring 2015 Week 2b: Review of Week 1, Variables 16 January 2015 Birkbeck

More information

Chapter 3. Input and output. 3.1 The System class

Chapter 3. Input and output. 3.1 The System class Chapter 3 Input and output The programs we ve looked at so far just display messages, which doesn t involve a lot of real computation. This chapter will show you how to read input from the keyboard, use

More information

Crash Course in Java

Crash Course in Java Crash Course in Java Based on notes from D. Hollinger Based in part on notes from J.J. Johns also: Java in a Nutshell Java Network Programming and Distributed Computing Netprog 2002 Java Intro 1 What is

More information

Socket Programming in Java

Socket Programming in Java Socket Programming in Java Learning Objectives The InetAddress Class Using sockets TCP sockets Datagram Sockets Classes in java.net The core package java.net contains a number of classes that allow programmers

More information

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following: In creating objects of the type, we have used statements similar to the following: f = new (); The parentheses in the expression () makes it look like a method, yet we never created such a method in our

More information

WRITING DATA TO A BINARY FILE

WRITING DATA TO A BINARY FILE WRITING DATA TO A BINARY FILE TEXT FILES VS. BINARY FILES Up to now, we have looked at how to write and read characters to and from a text file. Text files are files that contain sequences of characters.

More information

1.00/1.001 - Session 2 Fall 2004. Basic Java Data Types, Control Structures. Java Data Types. 8 primitive or built-in data types

1.00/1.001 - Session 2 Fall 2004. Basic Java Data Types, Control Structures. Java Data Types. 8 primitive or built-in data types 1.00/1.001 - Session 2 Fall 2004 Basic Java Data Types, Control Structures Java Data Types 8 primitive or built-in data types 4 integer types (byte, short, int, long) 2 floating point types (float, double)

More information

Conditional Statements. 15-110 Summer 2010 Margaret Reid-Miller

Conditional Statements. 15-110 Summer 2010 Margaret Reid-Miller Conditional Statements 15-110 Summer 2010 Margaret Reid-Miller Conditional statements Within a method, we can alter the flow of control (the order in which statements are executed) using either conditionals

More information

Rationale for Software Architecture

Rationale for Software Architecture Rationale for Software Architecture Bedir Tekinerdoğan University of Twente Department of Computer Science Enschede, The Netherlands e:mail bedir@cs.utwente.nl http://www.cs.utwente.nl/~bedir/ http://trese.cs.utwente.nl/taosad/

More information

Coding Standard for Java

Coding Standard for Java Coding Standard for Java 1. Content 1. Content 1 2. Introduction 1 3. Naming convention for Files/Packages 1 4. Naming convention for Classes, Interfaces, Members and Variables 2 5. File Layout (.java)

More information

CS170 Lab 11 Abstract Data Types & Objects

CS170 Lab 11 Abstract Data Types & Objects CS170 Lab 11 Abstract Data Types & Objects Introduction: Abstract Data Type (ADT) An abstract data type is commonly known as a class of objects An abstract data type in a program is used to represent (the

More information

CASCADING IF-ELSE. Cascading if-else Semantics. What the computer executes: What is the truth value 1? 3. Execute path 1 What is the truth value 2?

CASCADING IF-ELSE. Cascading if-else Semantics. What the computer executes: What is the truth value 1? 3. Execute path 1 What is the truth value 2? CASCADING IF-ELSE A cascading if- is a composite of if- statements where the false path of the outer statement is a nested if- statement. The nesting can continue to several levels. Cascading if- Syntax

More information

Introduction to Computer Programming, Spring Term 2014 Practice Assignment 3 Discussion 15.3.2014-20.3.2014

Introduction to Computer Programming, Spring Term 2014 Practice Assignment 3 Discussion 15.3.2014-20.3.2014 German University in Cairo Media Engineering and Technology Prof. Dr. Slim Abdennadher Dr. Ahmed Gamal Introduction to Computer Programming, Spring Term 2014 Practice Assignment 3 Discussion 15.3.2014-20.3.2014

More information