115
Computer Science Notes Chapter 1 Page 1 of 115 Chapter 1: Introduction to Computers, Programs, and Java /** * The Chap01Basics class implements an application that * prints a single line of text to the console, and shows the * basics of appropriate code documentation using javadoc comments. * (This is a javadoc comment for the class.) * @author Kevin Mirus */ public class Chap01Basics { /** * (This is a javadoc comment for the main method.) * @param args is not used */ public static void main(String[] args) { //Your code goes after this comment. /*Here is another way to make a comment.*/ System.out.println("Hello, World!"); }//end method main(String[]) }//end class Chap01Basics 1.1: Introduction 1.2: What is a Computer? 1.2.1: Central Processing Unit (CPU) 1.2.2: Memory 1.2.3: Storage Devices 1.2.4: Input and Output Devices 1.2.5: Communication Devices

Com Sci Chapter 1 Lecture Notes - Madison Area …faculty.madisoncollege.edu/kmirus/20092010A/804208/... · Web view... (Java SE) as opposed to the Enterprise Edition (Java EE),

Embed Size (px)

Citation preview

Computer Science Notes Chapter 1 Page 1 of 83

Chapter 1: Introduction to Computers, Programs, and Java

/** * The Chap01Basics class implements an application that * prints a single line of text to the console, and shows the * basics of appropriate code documentation using javadoc comments. * (This is a javadoc comment for the class.) * @author Kevin Mirus */public class Chap01Basics {

/** * (This is a javadoc comment for the main method.) * @param args is not used */public static void main(String[] args) {

//Your code goes after this comment./*Here is another way to make a comment.*/

System.out.println("Hello, World!");

}//end method main(String[])}//end class Chap01Basics

1.1: Introduction

1.2: What is a Computer?

1.2.1: Central Processing Unit (CPU)

1.2.2: Memory

1.2.3: Storage Devices

1.2.4: Input and Output Devices

1.2.5: Communication Devices

Computer Science Notes Chapter 1 Page 2 of 83

1.3: Programs Programs (software) are instructions to the computer.

o Machine language is a set of primitive instructions built in to every computer Example: 1101101010011010

o Assembly language is a “low-level” programming language in which a mnemonic is used to represent a machine-language instruction

Example: ADDF3 R1, R2, R3 Assembly was created to make programming “easy” (!). Required the use of an assembler program to translate the assembly language into

machine language.o “High-level” languages like Java, C, BASIC, FORTRAN, etc. are English-like and “easy” to

learn. These instructions are stored in a source file. Example: area = 5 * 5 * 3.14; A compiler is a program that translates the high-level source file into machine language. A linker then links other needed machine code files to your machine code file, and stores

the result as an executable file that runs on your computer

Source File Compiler Machine-Language File Linker Executable File

o The Java compiler takes a slightly different route; it creates a bytecode file, which is then interpreted line-by-line by a program called the Java Virtual Machine (JVM) to run your program.

o The JVM runs bytecode the same on any machine, so Java source code is completely portable between platforms.

1.4: Operating Systems

1.4.1: Controlling and Monitoring System Activities

1.4.2: Allocating and Assigning System Recources

1.4.3: Scheduling Operations

1.5: Number Systems

1.6: Java, the World Wide Web, and Beyond

1.7: The Java Language Specification, API, JDK, and IDE The Java language specification details the syntax and semantics of the Java language http://java.sun.com/docs/books/jls The application program interface (API) contains predefined classes (i.e., programs) that you can use in your programming. http://java.sun.com/javase/6/docs/api/ We will be using the Java Standard edition (Java SE) as opposed to the Enterprise Edition (Java EE), or the Micro Edition (Java ME). The latest version of Java is version 6. The programs that let you write and run version 6 Java code are found in the Java Development Toolkit, version 6 (or JDK 6). An Integrated Development Environment (IDE) is a program that lets you write source code, debug your source code, compile your source code, and run your program all from one place. Very nice. You used to have to use 3 different programs to do all of that. We will be using eclipse http://www.eclipse.org/downloads/

Computer Science Notes Chapter 1 Page 3 of 83

1.8: A Simple Java ProgramSee page 1… Class name main method ; (the statement terminator) Reserved words Comments Matching braces

Notice five key features of this program that must be present in all your programs:1. public class ClassName2. public static void main(String[] args)3. //lots of comments4. A method call (in this example, to the println() method)5. Nested sets of curly brackets { } to denote a block of code.

The “atoms” of computer programming in high-level languages are called statements. Statements always end with a semicolon or a closing curly bracket.

Types of Java Statements Variable declaration statement (for declaring variables) assignment statement (for setting r changing the values stored in the variable) object declaration/instantiation statement (for creating instances of an object) Method (subroutine) call statement (including input/output routines) empty statement block statement (One or more statements grouped together using {} ) control statement:

o while statement o do..while statement o if statement o for statement o switch statement o break statement (found in loops and switch statements only) o continue statement (found in loops only) o return statement (found in subroutine definitions only)

One or more statements can be grouped together into a block statement.One or more statements or block statements can be grouped together along with a name into a method.variables (called instance fields) and one or more methods can be grouped together with a name into a class.One or more classes can be grouped together into a package.One or more classes or packages are grouped together to form a program.

1.9: Creating, Compiling, and Executing a Java Program1.10: (GUI) Displaying Text in a Message Dialog Box

Chapter 2: Elementary Programming

Computer Science Notes Chapter 1 Page 4 of 83

import java.util.Scanner;// The import statement tells the compiler where to find additional classes that will be used.// In this case, the Scanner class will be used, which reads in and stores keystrokes from the keyboard.

/**The Chap02Basics class implements an application that * illustrates the basics of computer programming: * retrieving user input, performing calculations, * and generating output in a console. * Specifically, this program computes the area, hypotenuse, and perimeter * of a right triangle, given the lengths of the two legs. * This is meant as an example of the material in Chapter 2 of the text * _Introduction to Java Programming: Brief Version_, 7th ed. by Y. D. Liang * @author Kevin Mirus */

public class Chap02Basics{

/** Calculates the area, hypotenuse, and perimeter of a right triangle, * given the lengths of the two legs. * @param args is not used. */public static void main(String[] args){

//Tell the user what the program doesSystem.out.println("This program will calculate the hypotenuse, perimeter, and

area " +"of a right triangle given the lengths of its legs.");

// ********************************************************************// Here is the portion of the code that reads data into memory.// ********************************************************************//Declare variables for the data to be read in: i.e., the lengths of the two

legsdouble legA, legB;

//Declare a String object to store the uer's name, //and initalize that String to store the name ClydeString userName = "Clyde";

//Create a Scanner object for reading in the user's inputScanner keyboard = new Scanner(System.in);

//Prompt the user for his/her name, and store in userNameSystem.out.println("Please enter your name: ");userName = keyboard.next();

//Prompt the user for the lengths of the legs, //and store those two pieces of information in legA and legB.System.out.println("Please enter the length of the "

+ "first leg of the right triangle:");legA = keyboard.nextDouble();

System.out.println("Please enter the length of the "+ "second leg of the right triangle:");

legB = keyboard.nextDouble();

Computer Science Notes Chapter 1 Page 5 of 83

// ********************************************************************// Here is the portion of the code that// performs calculations on the data in memory.// ********************************************************************//Declare variables for the quantities to be calculated.double hypotenuse, perimeter , area;

//Calculate the hypotenuse using the Pythagorean Theorem:// a^2 + b^2 = c^2// c = sqrt(a^2 + b^2)hypotenuse = Math.sqrt(legA*legA + legB*legB);

//Calculate the perimeter by adding up the lengths of the three sides.perimeter = legA + legB + hypotenuse;

//Calculate the area using the formula area = (1/2)(base)(height).area = 0.5 * legA * legB;

// ********************************************************************// Here is the portion of the code that displays// memory values for output.// ********************************************************************

//Report the results for hypotenuse.System.out.println();System.out.println("Okay, " + userName + ", the hypotenuse of your "

+ "right triangle is: " + hypotenuse);

//Report the results for perimeter.System.out.println("The perimeter of your "

+ "right triangle is: " + perimeter);

//Report the results for areaSystem.out.println("The area of your "

+ "right triangle is: " + area);

//Tell the user that the program is done.System.out.println("\nI hope you enjoyed your results.");

}//end of method main(String[])}//end of class Chap02Basics

Section 2.1: Introduction

Section 2.2: Writing Simple Programs

Computer Science Notes Chapter 1 Page 6 of 83

Practice: Go through the steps above to decide how to write a program to compute the area of a rectangle, then implement (i.e., write) the program.

Plan for writing a program to compute the area of a rectangle:1. Information needed and how to store it

Need: length, width, areaStore them in floating-point variablesNamesof the variables: length, width, arealength and width will come from…keyboard (user)

2. Algorithm:Area = length times width

3. Information to show and its format:Length (echo back to user)Width (echo back to user)area

4. Translate that task into code using the programming techniques you have at your disposal.

Program to compute the area of a rectangle:import java.util.Scanner;

public class RectangleArea{

public static void main(String[] args){

double length, width, area;

Scanner keyboard = new Scanner(System.in);

System.out.println("Please enter the length of the rectangle:");length = keyboard.nextDouble();

System.out.println("Please enter the width of the rectangle:");width = keyboard.nextDouble();

area = length * width;

System.out.println("The length of your rectangle is: " + length);System.out.println("The width of your rectangle is: " + width);System.out.println("The area of your rectangle is: " + area);

System.out.println("All done!");

}//end method main}//end class RectangleArea

Computer Science Notes Chapter 1 Page 7 of 83

VARIABLE: a piece of memory with a name used for storing data and computational results. Choose descriptive names for variables.

o Example: good variable names to represent the legs of a right triangle would be legA and legB as opposed to a and b.

Variables must be declared in Java before they are used so that the JVM can set aside the appropriate amount of memory. Example:

//Declare variables for the data to be stored: i.e., the lengths of the two legsdouble legA, legB;

//Declare variables for the quantities to be calculated.double hypotenuse, perimeter , area;

The equals sign ( = ) is used to assign a value to a variable. Example://Calculate the area using the formula area = (1/2)(base)(height).area = 0.5 * legA * legB;

The plus sign ( + ) is used to perform addition and to concatenate strings with other strings or numerical values. If a string is too long, then you should break it up over two lines using concatenation. Examples:

//Calculate the perimeter by adding up the lengths of the three sides.perimeter = legA + legB + hypotenuse;

System.out.println("Okay, " + userName + ", the hypotenuse of your "+ "right triangle is: " + hypotenuse);

Section 2.3: IdentifiersAn identifier is the name of any programming entity you create, like a variable, constant, method, class,

or package.Rules for naming identifiers: An identifier is a sequence of letters, digits, the underscore ( _ ), or the dollar sign ( $ ). An identifier must start with a letter, underscore ( _ ), or the dollar sign ( $ ). It can not start with a digit. An identifier can not be a reserved word (like class, double, or int). An identifier can not be the words true, false, or null. An identifier can be any length.

Tips for naming identifiers: Identifiers are case sensitive; legA is different from lega. Use descriptive names, like cylinderRadius instead of r for the radius of a cylinder. Use “camel type” or underscores to break up long names into easy-to-recognize pieces, like cylinderRadius or triangle_perimeter. By convention, the $ is only used to start an identifier name in mechanically generated source code. By convention, primitive data type identifiers start with a lower-case letter. By convention, constants are capitalized. By convention, method identifiers start with a lower-case letter. By convention, class identifiers start with an upper -case letter.

Computer Science Notes Chapter 1 Page 8 of 83

Section 2.4: Variables

Section 2.4.1: Declaring VariablesA statement that declares a variable is called a variable declaration.

The syntax for a single variable declaration is:datatype variableName;

Example:double hypotenuse;

The syntax for multiple variable declarations of the same type is:datatype variableName1, variableName2, variableName3, …;

Example:double legA, legB;

To declare and initialize a variable in one statement:datatype variableName1 = value;

Example:double area = 0.0;

Java Primitive Data TypesType Description Sizeint An integer in the range

-2,147,483,648 int 2,147,483,647These range limits are stored in java.lang.Integer.MIN_VALUEand java.lang.Integer.MAX_VALUE

4 bytes(32-bit signed)

double Double-precision floating point: 10308 and about 15 significant figuresThese range limits are stored in java.lang.Double.MIN_VALUEand java.lang.Double.MAX_VALUE

8 bytes(64-bit IEEE 754)(1 bit for the sign;11 bits for the exponent;52 bits for the fraction)

char Character type, using Unicode 2 bytesboolean The type with 2 truth values: true and false 1 bitshort A short integer in the range -32768 short 32767

These range limits are stored in java.lang.Short.MIN_VALUEand java.lang.Short.MAX_VALUE

2 bytes(16-bit signed)

long A long integer in the range -9,223,372,036,854,775,808 long 9,223,372,036,854,775,807These range limits are stored in java.lang.Long.MIN_VALUEand java.lang.Long.MAX_VALUE

8 bytes(64-bit signed)

byte -128 integer byte 127These range limits are stored in java.lang.Byte.MIN_VALUEand java.lang.Byte.MAX_VALUE

1 byte(8-bit signed)

Computer Science Notes Chapter 1 Page 9 of 83

float Single-precision floating point: 1038 and about 7 significant figuresThese range limits are stored in java.lang.Float.MIN_VALUEand java.lang.Float.MAX_VALUE

4 bytes(32-bit IEEE 754)(1 bit for the sign;8 bits for the exponent;23 bits for the fraction)

Section 2.5: Assignment Statements and the Assignment OperatorAn assignment statement assigns a value to a variable.Java uses the equals sign ( = ) for the assignment operator, or symbol that tells the JVM to store a value in a variable’s memory location.An expression is a collection of values, variables, and operators that represent a computation.Example:

//Calculate the area.area = 0.5 * legA * legB;

//Calculate the perimeter.perimeter = legA + legB + hypotenuse;

A variable can be used in the expression of its own assignment statement. This is quite common…Example:

//increment the variable counter.counter = counter + 1;

An assignment expression is an assignment statement that is part of another statement. The value used by the statement is computed after the assignment is made.Examples:

The assignment expression statement Is equaivalent to:System.out.println( x = 1); x = 1;

System.out.println(x);i = j = k = 2; k = 2;

j = k;i = j;

Section 2.5: Declaring and Initializing Variables in One Step

The statement Is equaivalent to:int j = 5; int j;

j = 5;int j = 5, k = 7; int j, k;

j = 5;k = 7;

Computer Science Notes Chapter 1 Page 10 of 83

Section 2.6: Constants A constant represents a value that never changes. To declare a constant, precede its data type with the keyword final. By convention, use capital letters for a constant’s identifier. Constants are a good programming technique because:

o You don’t have to repeatedly type the same number when writing the program.o The value can be changed in a single location, if necessary.o A descriptive name for the constant makes the program easy to read.

Example: Compute the area of a circle.final double PI = 3.1415927;double radius = 2.5;double area;area = radius * radius * PI;

Note: you can access the value of pi to 15 digits using the constant for pi stored in the math class: Math.PI:

double radius = 2.5;double area;area = radius * radius * Math.PI;

Section 2.7: Numeric Data Types and Operations

Section 2.7.1: Numeric Operators

Operator Meaning Example Result+ Addition 34 + 1 35

29.5 + 2.7E2 299.5-88.2 + 5 -83.2

- Subtraction 34 – 0.1 33.9* Multiplication 300 * 30 9000/ Division 1.0 / 2.0 0.5

24 / 2 12Note: integer division only keeps the quotient and discards the remainder

1 / 2 0

% Remainder(integers only)

20 % 3 2

Computer Science Notes Chapter 1 Page 11 of 83

public class DisplayTime { public static void main(String[] args) { int seconds = 500; int minutes = seconds / 60; int remainingSeconds = seconds % 60; System.out.println(seconds + " seconds is " + minutes + " minutes and " + remainingSeconds + " seconds"); }}//Where are all the comments???

Section 2.7.2: Numeric LiteralsA literal is a constant value that appears in a program. An integer literal is assumed to be an int. For longer integer literals, append an L to the literal: 2147483648L To denote an octal literal, use a zero prefix: 07577 To denote a hexadecimal literal, use a 0x prefix: 0xFFFF A floating-point literal is assumed to be a double. For float literals, append an f or F to the literal: 23.5F Scientific notation: 1.23456103 = 1.23456e3 = 1.23456e+3; 2.510-4 = 2.5e-4

Section 2.7.3: Evaluating Java ExpressionsJava follows standard mathematical order of operationsPractice: Translate the following calculation into Java:

CORRECT: z = (3 + 4*x) / 5 – 20*(y – 5)*(a + b + c) / (3*x) + 9*(4/x + (9 + x)/y);

Section 2.7.4: Shorthand Operators… can be used when the variable in the expression is stores the resulting answer…

Operator Meaning Example Equivalent+= Addition Assignment i += 8 i = i + 8-= Subtraction Assignment i -= 8 i = i - 8*= Multiplication

Assignmenti *= 8 i = i * 8

/= Division Assignment i /= 8 i = i / 8%= Remainder Assignment i %= 8 i = i % 8++var Preincrement Increments var by 1 and

uses the new value in var in the expression

var++ Postincrement Uses the old value in var in the expression, then increments var

--var Predecrement Decrements var by 1 and uses the new value in var in the expression

Computer Science Notes Chapter 1 Page 12 of 83

var-- Postdecrement Uses the old value in var in the expression, then decrements var

Section 2.8: Numeric Type Conversions…are done automatically by the compiler:

1. If one of the operands is a double, then the other is converted to double.2. Otherwise, if one of the operands is a float, then the other is converted to float.3. Otherwise, if one of the operands is a long, then the other is converted to long.4. Otherwise, both operands are converted to int.

Type casting explicitly converts data type by placing desired data type in parentheses in front of variable:int i = 1, j = 3;System.out.println(i / j); //output is 0System.out.println((float)i / (float)j); //output is 0.333333333

Type casting can be used to round off numbers to a desired number of decimal places. The following example rounds off a monetary amount to two decimals:public class SalesTax { public static void main(String[] args) { double purchaseAmount = 197.55; double tax = purchaseAmount * 0.06; System.out.println("Unformatted sales tax is " + tax); System.out.println("Formatted sales tax is " + (int)(tax * 100) / 100.0); }}

Unformatted sales tax is 11.853Formatted sales tax is 11.85

Section 2.9: Character Data Type and OperationsThe data type char is used to represent individual characters.A character literal is enclosed in single quotes.Example:public class CharExample{

public static void main(String[] args) {

char letter1 = 'K';char letter2 = 'A';char letter3 = 'M';char numChar = '4';System.out.println("My initials are: " + letter1 + letter2 + letter3);System.out.println("The value of numChar is: " + numChar);System.out.println("One more than numChar is: " + (numChar+1));

}}

Computer Science Notes Chapter 1 Page 13 of 83

Section 2.9.1: Unicode and ASCII code

Section 2.9.2: Escape Sequences for Special CharactersEscape sequences are designed to display special characters in string literals.Escape sequences are preceded by a backslash

public class EscapeSequenceExample{

public static void main(String[] args) {

System.out.println("He said \"Java is Fun\".\n\"Java is Fun.\"");}

}He said "Java is Fun"."Java is Fun."\b backspace\t tab\n linefeed\f formfeed\r carriage return\\ backslash\’ single quote\” double quote

Computer Science Notes Chapter 1 Page 14 of 83

Section 2.9.3: Casting Between char and Numeric Data Types When an integer is cast to a char, only the lower 16 bits of data are used.When a float or double is cast to a char, the floating-point value is cast to an int, which is then cast to a char.When a char is cast to a numeric type, the character’s Unicode value is cast to the specified numeric type.

Section 2.10: The String Type The data type of String is used to store a string (or sequence) of characters.The String type is not a primitive data type; it is a reference type (more in Chap07).Strings can be concatenated with the + operator.

public class StringExamples {

public static void main(String[] args){

String message1 = "Welcome to Java.";String message2 = "Welcome " + "to " + "Java.";System.out.println("message1 = " + message1);System.out.println("message2 = " + message2);System.out.println();

String message3 = "Chapter " + 2;String message4 = "Supplement " + 'B';System.out.println("message3 = " + message3);System.out.println("message4 = " + message4);System.out.println();

message2 += " Java is fun!";System.out.println("message2 = " + message2);System.out.println();

int i = 2, j = 3;System.out.println("i = " + i);System.out.println("j = " + j);System.out.println("concatenation: i + j = " + i + j);System.out.println("addition: i + j = " + (i + j));

}}

message1 = Welcome to Java.message2 = Welcome to Java.

message3 = Chapter 2message4 = Supplement B

message2 = Welcome to Java. Java is fun!

i = 2j = 3concatenation: i + j = 23addition: i + j = 5

Computer Science Notes Chapter 1 Page 15 of 83

Section 2.11: Console Input Using the Scanner Class To use the Scanner class to read input you need to do three things:

1. Have the following statement as the very beginning of your source code:import java.util.Scanner;

2. Create a “variable” to store the information from the scanner. Use the following line of source code:Scanner keyboard = new Scanner(System.in);

(You can change the variable name keyboard to whatever you want, but that is the only thing you can change.)

3. Store information from the scanner into primitive variables or strings using an appropriate method of the scanner class. Here are seven examples of seven key input methods:

a. String userName = keyboard.next(); //the String is delimited by spaces

b. int a = keyboard.nextInt();c. double x = keyboard.nextDouble();d. float y = keyboard.nextFloat();e. byte b = keyboard.nextByte();f. short c = keyboard.nextShort();g. long d = keyboard.nextLong();

The program at the start of these notes uses the next and nextDouble methods.

Methods for Scanner objectsMethod DescriptionnextByte() Reads an integer of the byte typenextShort() Reads an integer of the short typenextInt() Reads an integer of the int typenextLong() Reads an integer of the long typenextFloat() Reads a number of the float typenextDouble() Reads a number of the double typenext() Reads a string that ends before a whitespacenextLine() Reads a line of characters (i.e., string ending with a

line separator)

A Scanner object reads items separated by whitespaces. A whitespace is one of the following characters: , \t, \f, \r, \n

Computer Science Notes Chapter 1 Page 16 of 83

import java.util.Scanner; // Scanner is in java.util

public class TestScanner { public static void main(String args[]) { // Create a Scanner Scanner input = new Scanner(System.in);

// Prompt the user to enter an integer System.out.print("Enter an integer: "); int intValue = input.nextInt(); System.out.println("You entered the integer " + intValue);

// Prompt the user to enter a double value System.out.print("Enter a double value: "); double doubleValue = input.nextDouble(); System.out.println("You entered the double value " + doubleValue);

// Prompt the user to enter a string System.out.print("Enter a string without space: "); String string = input.next(); System.out.println("You entered the string " + string); }}

Section 2.12: Case Studies

Section 2.13: Programming Style and Documentation Programming style deals with how the source code to a program looks: Documentation is the body of explanatory remarks and comments pertaining to a program.

Section 2.13.1: Appropriate Comments and Comment Styles At the start of a program, include a summary of what the program does, its key features, its supporting data structures, and any unique techniques it uses. A long program should also have comments that introduce each major step and explain anything that is difficult to read. javadoc comments ( /** … */ ) are used to give information about classes, methods, and public variables. Comments of this type can be read by the javadoc utility program which generates HTML support documents from them.

Section 2.13.2: Naming Conventions Use descriptive names with straightforward meanings for your variables, constants, classes, and methods. Names are case-sensitive. Start the names of variables and methods with a lowercase letter. Start the names of classes with an uppercase letter. Capitalize every letter in the name of a constant.

Computer Science Notes Chapter 1 Page 17 of 83

Section 2.13.3: Proper Indentation and Spacing Indent lines of code by the same amount that are at the same “nesting level” in a program. Put a single blank space on either side of a binary operator.

Section 2.13.4: Block Styles A block is a group of statements surrounded by (curly) braces, { }. In end-of-line style, the opening brace for the block is at the end of the line. In next-line style, the opening brace for the block is at the start of the next line.

/**Here is a simple program written using the end-of-line block style. */

public class BlockStyleTest {public static void main(String[] args) {

System.out.println("Block Styles.");}

}

/**Here is a simple program written using the next-line block style. */public class BlockStyleTest {

public static void main(String[] args){

System.out.println("Block Styles.");}

}

Section 2.14: Programming Errors

Section 2.14.1: Syntax Errors

Section 2.14.2: Runtime Errors

Section 2.14.3: Logic Errors

Section 2.15: Debugging

Computer Science Notes Chapter 1 Page 18 of 83

Section 2.16: (GUI) Getting Input from Dialog Boxes

import javax.swing.JOptionPane;// The import statement tells the compiler where to find the JOptionPane class,// which contains the code for dialog boxes.

/**The Chap02BasicsGUI class implements an application that * illustrates the basics of computer programming: * retrieving user input, performing calculations, * and generating output using a GUI interface of dialog boxes. * Specifically, this program computes the area, hypotenuse, and perimeter * of a right triangle, given the lengths of the two legs. * This is meant as an example of the material in Chapter 2 of the text * _Introduction to Java Programming: Brief Version_, 7th ed. by Y. D. Liang * @author Kevin Mirus */

public class Chap02BasicsGUI{

/** Calculates the area, hypotenuse, and perimeter of a right triangle, * given the lengths of the two legs. * @param args is not used. */public static void main(String[] args){

//Tell the user what the program doesJOptionPane.showMessageDialog(null, "This program will calculate " +

"the hypotenuse, perimeter, and area of a right triangle " +"given the lengths of its legs.", "Chap02BasicsGUI Intro",JOptionPane.INFORMATION_MESSAGE);

// ********************************************************************// Here is the portion of the code that reads data into memory.// ********************************************************************//Declare variables for the data to be read in: i.e., the lengths of the two

legsdouble legA, legB;

//Input dialog boxes return strings as output, so we also need a String object//for each numeric variable, which will then get converted to doubles.String legA_String, legB_String;

//Declare a String object to store the user's name.String userName;

//Prompt the user for his/her name, and store in userNameuserName = JOptionPane.showInputDialog(null, "Please enter your name.",

"Your name", JOptionPane.QUESTION_MESSAGE);

//Prompt the user for the length of the first leg. legA_String = JOptionPane.showInputDialog(null, "Please enter the " +

"length of the first leg of the right triangle:", "First Leg",JOptionPane.QUESTION_MESSAGE);

//Convert the string from the input dialog box to a double-precision //number, and store the answer in legAlegA = Double.parseDouble(legA_String);

//Prompt the user for the length of the second leg,

Computer Science Notes Chapter 1 Page 19 of 83

//then convert the string to a number and store in legBlegB_String = JOptionPane.showInputDialog(null, "Please enter the " +

"length of the second leg of the right triangle:", "Second Leg",JOptionPane.QUESTION_MESSAGE);

legB = Double.parseDouble(legB_String);

// ********************************************************************// Here is the portion of the code that// performs calculations on the data in memory.// ********************************************************************//Declare variables for the quantities to be read calculated.double hypotenuse, perimeter , area;

//Calculate the hypotenuse using the Pythagorean Theorem:// a^2 + b^2 = c^2// c = sqrt(a^2 + b^2)hypotenuse = Math.sqrt(legA*legA + legB*legB);

//Calculate the perimeter by adding up the lengths of the three sides.perimeter = legA + legB + hypotenuse;

//Calculate the area using the formula area = (1/2)(base)(height).area = 0.5 * legA * legB;

// ********************************************************************// Here is the portion of the code that displays// memory values for output.// ********************************************************************//Report the results for hypotenuseString hypotenuseString = "Okay, " + userName + ", the hypotenuse of your "

+ "right triangle is: " + hypotenuse;JOptionPane.showMessageDialog(null, hypotenuseString, "Hypotenuse Results",

JOptionPane.INFORMATION_MESSAGE);

//Report the results for perimeterString perimeterString = "The perimeter of your right triangle is: " +

perimeter;JOptionPane.showMessageDialog(null, perimeterString, "Perimeter Results",

JOptionPane.INFORMATION_MESSAGE);

//Report the results for areaString areaString = "The area of your right triangle is: " + area;JOptionPane.showMessageDialog(null, areaString, "Area Results",

JOptionPane.INFORMATION_MESSAGE);

//Tell the user that the program is done.JOptionPane.showMessageDialog(null, "I hope you enjoyed your results.", "All

Done",JOptionPane.INFORMATION_MESSAGE);

}//end of main(String[])}//end of class Chap02BasicsGUI

Computer Science Notes Chapter 1 Page 20 of 83

Section 2.16.1: Converting Strings to NumbersIf a string contains a sequence of characters meant to represent a number, then you can convert that string to a number using either the parseInt method of the Integer class, or the parseDouble method of the Double class.

String stringX = "123";int x = Integer.parseInt(stringX);System.out.println("x + 5 = " + (x + 5));

String stringY = "456.789";double y = Double.parseDouble(stringY);System.out.println("y + 5 = " + (y + 5));

Section 2.16.2: Using Input Dialog Boxes

Computer Science Notes Chapter 1 Page 21 of 83

Chapter 3: Selections

import java.util.Scanner;//The import statement tells the linker which additional classes that will be used.//In this case, the Scanner class will be used.//The Scanner class reads in and stores keystrokes from the keyboard.

/**The Chap03Basics class implements an application that * computes income tax, and is meant to * illustrate the basics of selection statements * (i.e., if and switch statements). * This is meant as an example of the material in Chapter 3 of the text * _Introduction to Java Programming: Brief Version_, 7th ed. by Y. D. Liang * @author Kevin Mirus */

public class Chap03Basics{

/** Prompts the user to enter a tax year, filing status, and income, * then computes the income tax due according to those values, * and prints the results. * @param args is not used. */public static void main(String[] args){

final int FIRST_TAX_YEAR = 2007;final int LAST_TAX_YEAR = 2008;final int SINGLE = 1; //filing status of singlefinal int JOINT = 2; //filing status of married filing jointlyfinal int SEPARATE = 3; //filing status of married filing separatelyfinal int HEAD = 4; //filing status of Head of Householdfinal String SINGLE_TEXT = "Single";final String JOINT_TEXT ="Married Filing Jointly";final String SEPARATE_TEXT ="Married Filing Separately";final String HEAD_TEXT = "Head of Household";

//Tell the user what the program doesString programPurpose = "This program performs U.S. federal tax " +

"calculations for any year between " + FIRST_TAX_YEAR + " and " + LAST_TAX_YEAR;

System.out.println(programPurpose);

//Create a Scanner object for reading in the user's inputScanner keyboard = new Scanner(System.in);

//Read in the tax year, and make sure it is in the specified rangeString prompt = "\nPlease enter the tax year (" + FIRST_TAX_YEAR +

" through " + LAST_TAX_YEAR + "):";System.out.println(prompt);int taxYear = keyboard.nextInt();

if (taxYear < FIRST_TAX_YEAR || taxYear > LAST_TAX_YEAR){

System.out.println("Invalid tax year. Program is now terminating.");System.exit(0);

}

//Read in the income, and make sure it is positive.prompt = "\nPlease enter your income:";

Computer Science Notes Chapter 1 Page 22 of 83

System.out.println(prompt);double income = keyboard.nextDouble();if (income < 0){

System.out.println("Invalid (negative) income. " +"Program is now terminating.");

System.exit(0);;}

//Read in the filing status, and make sure it is valid.System.out.println("\nUse one of the menu choices below to enter " +

"your filing status.");System.out.println(SINGLE + ") " + SINGLE_TEXT);System.out.println(JOINT + ") " + JOINT_TEXT);System.out.println(SEPARATE + ") " + SEPARATE_TEXT);System.out.println(HEAD + ") " + HEAD_TEXT);prompt = "\nPlease enter your filing status: ";System.out.println(prompt);int filingStatus = keyboard.nextInt();if (!(filingStatus == SINGLE || filingStatus == JOINT ||

filingStatus == SEPARATE || filingStatus == HEAD)){

System.out.println("Invalid filing status. " +"Program is now terminating.");

System.exit(0);;}

//Declare variables to store the tax rates for each tax bracket.//Initialize them with the most common values used from 2003 - 2008.//They can be set to new values, if needed, when the income cutoffs get set.//See http://www.moneychimp.com/features/tax_brackets.htm for all the info.double taxRate1 = 0.10;double taxRate2 = 0.15;double taxRate3 = 0.25;double taxRate4 = 0.28;double taxRate5 = 0.33;double taxRate6 = 0.35;

//Declare variables to store the upper income cutoffs for each tax bracket.//Initialize them to zero in case something is wrong //with the taxYear value or the filingStatus value.double cutoff1 = 0.00;double cutoff2 = 0.00;double cutoff3 = 0.00;double cutoff4 = 0.00;double cutoff5 = 0.00;

//Set the income cutoffs for each tax year and filing statusswitch (taxYear){

case 2007://Set the income cutoffs for each bracket and filing status.if (filingStatus == SINGLE){

cutoff1 = 7825.00;cutoff2 = 31850.00;cutoff3 = 77100.00;cutoff4 = 160850.00;cutoff5 = 349700.00;

}

Computer Science Notes Chapter 1 Page 23 of 83

else if (filingStatus == JOINT){

cutoff1 = 15650.00;cutoff2 = 63700.00;cutoff3 = 128500.00;cutoff4 = 195850.00;cutoff5 = 349700.00;

}else if (filingStatus == SEPARATE){

cutoff1 = 7825.00;cutoff2 = 31850.00;cutoff3 = 64250.00;cutoff4 = 97925.00;cutoff5 = 174850.00;

}else if (filingStatus == HEAD){

cutoff1 = 15650.00;cutoff2 = 63700.00;cutoff3 = 128500.00;cutoff4 = 195850.00;cutoff5 = 349700.00;

}break;

case 2008://Set the income cutoffs for each bracket and filing status.if (filingStatus == SINGLE){

cutoff1 = 8025.00;cutoff2 = 32550.00;cutoff3 = 78850.00;cutoff4 = 164550.00;cutoff5 = 357700.00;

}else if (filingStatus == JOINT){

cutoff1 = 16050.00;cutoff2 = 65100.00;cutoff3 = 131450.00;cutoff4 = 200300.00;cutoff5 = 357700.00;

}else if (filingStatus == SEPARATE){

cutoff1 = 8025.00;cutoff2 = 32550.00;cutoff3 = 65725.00;cutoff4 = 100150.00;cutoff5 = 178850.00;

}else if (filingStatus == HEAD){

cutoff1 = 11450.00;cutoff2 = 43650.00;cutoff3 = 112650.00;cutoff4 = 182400.00;cutoff5 = 357700.00;

}break;

Computer Science Notes Chapter 1 Page 24 of 83

default:System.out.println("Invalid tax year. Program is now

terminating.");System.exit(0);

}//end of switch statement for setting the income cutoffs based on taxYear

//Compute the tax due.double tax = 0.0;int taxBracket = 0;double taxBracketRate = 0.0;if (income <= cutoff1)

{tax = income * taxRate1;taxBracket = 1;taxBracketRate = taxRate1;

}else if (income <= cutoff2){

tax = cutoff1 * taxRate1 + (income - cutoff1) * taxRate2;

taxBracket = 2;taxBracketRate = taxRate2;

}else if (income <= cutoff3)

{tax = cutoff1 * taxRate1

+ (cutoff2 - cutoff1) * taxRate2 + (income - cutoff2) * taxRate3;

taxBracket = 3;taxBracketRate = taxRate3;

}else if (income <= cutoff4)

{tax = cutoff1 * taxRate1

+ (cutoff2 - cutoff1) * taxRate2 + (cutoff3 - cutoff2) * taxRate3+ (income - cutoff3) * taxRate4;

taxBracket = 4;taxBracketRate = taxRate4;

}else if (income <= cutoff5)

{tax = cutoff1 * taxRate1

+ (cutoff2 - cutoff1) * taxRate2 + (cutoff3 - cutoff2) * taxRate3+ (cutoff4 - cutoff3) * taxRate4 + (income - cutoff4) * taxRate5;

taxBracket = 5;taxBracketRate = taxRate5;

}

else{

tax = cutoff1 * taxRate1 + (cutoff2 - cutoff1) * taxRate2 + (cutoff3 - cutoff2) * taxRate3+ (cutoff4 - cutoff3) * taxRate4 + (cutoff5 - cutoff4) * taxRate5 + (income - cutoff5) * taxRate6;

taxBracket = 6;

Computer Science Notes Chapter 1 Page 25 of 83

taxBracketRate = taxRate6;}

System.out.println("\nHere are your results:");System.out.println("filing year = " + taxYear);

String filingStatusEcho = "filing status = ";if (filingStatus == SINGLE)

filingStatusEcho += SINGLE_TEXT;else if (filingStatus == JOINT)

filingStatusEcho += JOINT_TEXT;else if (filingStatus == SEPARATE)

filingStatusEcho += SEPARATE_TEXT;else if (filingStatus == HEAD)

filingStatusEcho += HEAD_TEXT;System.out.println(filingStatusEcho);

System.out.println("income = $" + String.format("%,12.2f", income) );

System.out.println("income tax owed = $" + String.format("%,12.2f", tax));System.out.println("tax bracket = " + taxBracket);System.out.println("tax bracket rate = "

+ String.format("%4.1f", taxBracketRate*100) + "%");

System.out.println("\nProgram is now terminating.");}//end method main(String[])

}//end of class Chap03Basics

Computer Science Notes Chapter 1 Page 26 of 83

Section 3.1: IntroductionExample: Problem to solve: If the user enters a negative value for a radius of a circle, then display an error message; otherwise compute and display the circumference.

↓ Pseudocode..Get the user’s input for a circle radiusIf (the radius is negative)

Then print an error messageOtherwise

Compute and print the circumference

↓ Real codeimport java.util.Scanner;

public class CircleCircumference{

public static void main(String[] args){

System.out.println("This program will compute the circumference of " +"a circle given its radius.");

Scanner keyboard = new Scanner(System.in);

// Get the user’s input for a circle radiusSystem.out.println("Enter the radius of a circle:");double radius = keyboard.nextDouble();

if (radius < 0.0) System.out.println("Bad entry; you entered r = " + radius + ", and the radius of a circle should NOT be negative.");else System.out.println("For a circle of radius " + radius + ", the circumference is: " + (2*Math.PI*radius) + ".");

}}

Computer Science Notes Chapter 1 Page 27 of 83

Section 3.2: boolean Data Type and Operations The comparison operators are: <, <=, >, >=, = =, != Comparison operators are used to compare numeric values. The result of a comparison calculation is a Boolean value of true or false. true and false Are Boolean literals and reserved keywords The boolean data type contains one of two values: true or false. Boolean variables hold Boolean values. The Boolean operators are: !, &&. ||, and ^ Boolean operators relate boolean expressions to determine the overall truth or falsehood of the statement.Comparison operators: used to compare the value of two numerical expressions.Operator Name Example Result< Less than 1 < 2 true<= Less than or equal to 1 <= 2 true> Greater than 1 > 2 false>= Greater than or equal to 1 >= 1 true== Equal to 1 = = 2 false!= Not equal to 1 != 2 true

Boolean operators: used to determine the truth of a combination of expressions.Operator Name Description! Not Logical negation&& And Logical conjunction|| Or Logical disjunction^ Exclusive or Logical exclusion

import java.util.Scanner;

public class BooleanExample{

public static void main(String[] args){

Scanner keyboard = new Scanner(System.in);

System.out.println("This program will determine where you were born " +"based on your answers to two questions.");

boolean lovePackers = true;boolean loveWisconsin = true;System.out.println("Type true if you love the Packers, ");System.out.println("or type false if you dislike the Packers.");lovePackers = keyboard.nextBoolean();

System.out.println("Type true if you love Wisconsin, ");System.out.println("or type false if you dislike Wisconsin.");loveWisconsin = keyboard.nextBoolean();

if (loveWisconsin == true && lovePackers == true)System.out.println("You must be a native Wisconsinite.");

if (loveWisconsin == true && lovePackers == false)System.out.println("You must be a Wisconsin immigrant.");

if (loveWisconsin == false && lovePackers == true)System.out.println("You must be from Minnesota.");

Computer Science Notes Chapter 1 Page 28 of 83

if (loveWisconsin == false && lovePackers == false)System.out.println("You must be from Illinois.");

//Exclusive or://i.e., you love Wisconsin or you love the Packers, but not both.if (loveWisconsin ^ lovePackers)

System.out.println("That's good enough for me.");

//Longhand exclusive or:if ((loveWisconsin || lovePackers) && !(loveWisconsin && lovePackers))

System.out.println("That's good enough for me.");}

}

More Boolean notes: To test if a variable is within a range of numbers:WRONG WAY TO TEST A NUMERICAL RANGE

CORRECT WAY TO TEST A NUMERICAL RANGE

int numberOfDaysInAMonth = 32;if (1 <= numberOfDaysInAMonth <= 31)

...

int numberOfDaysInAMonth = 32;if (1 <= numberOfDaysInAMonth &&

numberOfDaysInAMonth <= 31)...

&& is a conditional, or short-circuit operator because if the first expression evaluates to false, then the overall expression is false, and so the second expression’s value is not computed because there is no need to. || is also a short-circuit operator because if the first expression evaluates to true, then the overall expression is true, and so second expression’s value is not computed because there is no need to. & is an unconditional operator because both expressions’ values are computed before the overall value of the expression is determined.

Computer Science Notes Chapter 1 Page 29 of 83

Section 3.2.1: Example: Determining Leap Year See www.cs.armstrong.edu/liang/intro7e/book/LeapYear.java

Section 3.2.2: Example: A Simple Math Learning Tool See www.cs.armstrong.edu/liang/intro7e/book/AdditionQuiz.java

Section 3.3: if Statements Section 3.3.1: Simple if Statements The if statement by itself forces a program to execute a statement only if a given condition is true.

Syntax of a simple if statement:if (condition)

{conditionTrueStatement(s);

}nextStatement;

Example:import java.util.Scanner;

public class CircleCircumference2{

public static void main(String[] args){

System.out.println("This program will compute the circumference of " +"a circle given its radius.");

Scanner keyboard = new Scanner(System.in);

// Get the user’s input for a circle radiusSystem.out.println("Enter the radius of a circle:");double radius = keyboard.nextDouble();

if (radius >= 0.0) System.out.println("For a circle of radius " + radius + ", the circumference is: " + (2*Math.PI*radius) + ".");

System.out.println("This program is done now.");}

}

Computer Science Notes Chapter 1 Page 30 of 83

Section 3.3.2: if … else Statements The if .. else statement forces a program to execute one statement only if a given condition is true, and a different statement if the condition is false.

Syntax of a simple if statement:if (condition)

{conditionTrueStatement(s);

}else

{conditionFalseStatement(s);

}

nextStatement;

Example:import java.util.Scanner;

public class CircleCircumference{

public static void main(String[] args){

System.out.println("This program will compute the circumference of " +"a circle given its radius.");

Scanner keyboard = new Scanner(System.in);

// Get the user’s input for a circle radiusSystem.out.println("Enter the radius of a circle:");double radius = keyboard.nextDouble();

if (radius < 0.0) System.out.println("Bad entry; you entered r = " + radius + ", and the radius of a circle should NOT be negative.");else System.out.println("For a circle of radius " + radius + ", the circumference is: " + (2*Math.PI*radius) + ".");System.out.println("This program is done now.");

}}

Computer Science Notes Chapter 1 Page 31 of 83

Section 3.3.3: Nested if Statements Syntax of a nested if statement: Use the syntax of an if … else statement, with the else statements containing additional if … else statements.

Example:Compute the letter grade of a numerical score according to the following grading scale:A 92 % - 100 % AB 88 % - 91 % B 82 % - 87 % BC 78 % - 81 % C 72 % - 77 % D 65 % - 71 % F 0 % - 64 %

import java.util.Scanner;

public class NestedIfExample{

public static void main(String[] args){

Scanner keyboard = new Scanner(System.in);

System.out.println("This program will convert a numerical score " +"into a letter Grade");

System.out.println("Enter a numerical score.");double score = keyboard.nextDouble();String letterGrade;

if (score >= 91.5) letterGrade = "A";else if (score >= 87.5) letterGrade = "AB";else if (score >= 81.5) letterGrade = "B";else if (score >= 77.5) letterGrade = "BC";else if (score >= 71.5) letterGrade = "C";else if (score >= 64.5) letterGrade = "D";else letterGrade = "F";

System.out.println("A score of " + score + " earns a letter grade of " + letterGrade + ".");

}}

Computer Science Notes Chapter 1 Page 32 of 83

Example:Write the Wisconsite/Packer messages using nested if statements instead of compound boolean expressions.

if (loveWisconsin == true && lovePackers == true)

System.out.println("You must be a native Wisconsinite.");if (loveWisconsin == true && lovePackers == false)

System.out.println("You must be a Wisconsin immigrant.");

if (loveWisconsin == false && lovePackers == true)

System.out.println("You must be from Minnesota.");if (loveWisconsin == false && lovePackers == false)

System.out.println("You must be from Illinois.");

//Exclusive or://i.e., you love Wisconsin or you love the Packers, but not both.if (loveWisconsin ^ lovePackers)

System.out.println("That's good enough for me.");

if (loveWisconsin == true)if (lovePackers == true) System.out.println("You must

be a native Wisconsinite."); else

System.out.println("You must be an immigrant.");

else if (lovePackers == true)

System.out.println("You must be from Minnesota."); else

System.out.println("You must be from Illinois.");

//Exclusive or:if (loveWisconsin) if (!lovePackers)

System.out.println("That's good enough for me."); else;else if (lovePackers) System.out.println("That's good enough for me.");

Section 3.3.4: Problem: An Improved Math Learning Tool Notice the use of the Math.random() method.

Section 3.3.5: Problem: Lottery

Section 3.3.6: Problem: Computing Body Mass Index

Section 3.3.7: Problem: Computing Taxes Notice the use of the System.exit(0) method.

Section 3.3.8: Problem: Guessing Birth Dates

Computer Science Notes Chapter 1 Page 33 of 83

Section 3.4: switch Statements Syntax of a simple switch statement:

switch (integerExpression){

case value1:statement(s)1;break;

case value2:statement(s)2;break;

case valueN:statement(s)N;break;

default:statement(s)Default;

}nextStatement;

Example:import java.util.Scanner;

public class SwitchStatementExample{

public static void main(String[] args){

Scanner keyboard = new Scanner(System.in);

System.out.println("This program will give you a one-problem arithmetic quiz.");

System.out.println("\nYour menu of problem types is:");System.out.println("+: Addition problem.");System.out.println("-: Subtraction problem.");System.out.println("*: Multiplication problem.");System.out.println("/: Division problem.");System.out.println("Enter the symbol for the type of problem you want.");

//Get the user's menu choice, then extract the first character.String operationChoiceString = keyboard.next();char operationChoice = operationChoiceString.charAt(0);

//Generate two random numbers between 0 and 9 for the quiz question.//Use the fact that the Math.random() method //generates random floating point numbers between 0 and 1int number1 = (int) (Math.random() * 10);int number2 = (int) (Math.random() * 10);

//Declare a variable to store the answer to the quiz question.int correctAnswer = 0;

//The quiz will always be: number1 operationChoice number2.//So, we need to adjust number1 and number2 //to always give nice answers for the chosen operationChoice.

Computer Science Notes Chapter 1 Page 34 of 83

switch (operationChoice){

case '+': //Compute the answer to the addition quiz question.correctAnswer = number1 + number2;break;

case '-': //Compute the answer to the subtraction quiz question.//Swap numbers if necessary so number1 is greater than number 2if (number2 > number1){

int temp = number1;number1 = number2;number2 = temp;

}correctAnswer = number1 - number2;break;

case '*': //Compute the answer to the multiplication quiz question.correctAnswer = number1 * number2;break;

case '/': //Compute the answer to the division quiz question.//Make sure the divisor is not zero.if (number2 == 0)

number2 = 3;//Create a new dividend that's a multiple of the divisor. number1 = (int) (Math.random() * 10) * number2;correctAnswer = number1 / number2;break;

default://Create the set-up for a simple addition quiz question, //because the user isn't smart enough to enter a value for //operationChoice correctly.number1 = 1;number2 = 1;correctAnswer = number1 + number2;operationChoice = '+';

}

//Print the quiz question.System.out.println("What is " + number1 + " " + operationChoice +

" " + number2 + " ?");

//Read the user's answer.int userAnswer = keyboard.nextInt();

//Tell the user is s/he is correct or not.if (userAnswer == correctAnswer)

System.out.println("You are correct!");else

System.out.println("Sorry, the correct answer is: " + correctAnswer);}

}

Computer Science Notes Chapter 1 Page 35 of 83

Section 3.5: Conditional Expressions Syntax of a conditional expression: booleanExpression ? expression1 : expression2; If booleanExpression is true, then expression1 is evaluated; otherwise, expression2 is evaluated.

Example: Computing the absolute value of a number.if … else method for computing an absolute value:import java.util.Scanner;

public class AbsoluteValue{

public static void main(String[] args){

Scanner keyboard = new Scanner(System.in);System.out.println("This program will compute the absolute " +

"value of a given number.");// Get the user’s input for the numberSystem.out.println("Enter a number:");double x = keyboard.nextDouble();

double abs_x;

if (x < 0.0)abs_x = -x;

elseabs_x = x;

System.out.println("|" + x + "| = " + abs_x);}

}

Conditional expression method that does the same thingimport java.util.Scanner;

public class AbsoluteValue{

public static void main(String[] args){

Scanner keyboard = new Scanner(System.in);System.out.println("This program will compute the absolute " +

"value of a given number.");// Get the user’s input for the numberSystem.out.println("Enter a number:");double x = keyboard.nextDouble();

double abs_x;abs_x = (x < 0.0) ? -x: x;

System.out.println("|" + x + "| = " + abs_x);}

}

Computer Science Notes Chapter 1 Page 36 of 83

Section 3.6: Formatting Console OutputExample:

// the following line produces an output where the format specifier// %6.2f will be replaced with the floating point number 1.5 // written using 6 spaces and 2 digits after the decimal point // (and followed by a newline)System.out.printf("Price is: $%6.2f\n", 1.517);sample output: Price is: $ 1.50

Format TypesCode Type Exampled Decimal integer System.out.printf("%5d", 123);

//output: 123

x Hexadecimal integer System.out.printf("%5x", 123);//output: 7B

o Octal integer System.out.printf("%5o", 123);//output: 173

f Fixed floating point System.out.printf("%6.2f", 123.);//output:123.00

e Exponential floating point System.out.printf("%10.2e", 123.);//output: 1.23e+1

g General floating point (printf decides whether to use f or e)

System.out.printf("%6.2g", 123);//output:123.00

s String System.out.printf("%6s", "123");//output: 123

b Boolean value System.out.printf("%b", lovePackers);//output:true

c Character value System.out.printf("%c", menuChoice);//output:g

Format FlagsFlag Meaning Example- Left justifiation System.out.printf("%-5dhello", 123);

//output:123 hello

0 Show leading zeros System.out.printf("%06d", 123);//output:

Computer Science Notes Chapter 1 Page 37 of 83

000123+ Show a + sign for positive numbers System.out.printf("%+6d", 123);

//output: +123

( Enclose negative numbers in parentheses System.out.printf("%(6d", -123);//output: (123)

, Show decimal separators System.out.printf("%,10d", 123000);//output: 123,000

Note: to access this functionality use Java version 5.0 or higher.

The format method of the String class also recognizes format specifiers.Example:

String outputString = String.format("%-5dhello", 123);System.out.println(outputString);//output:23 hello

Computer Science Notes Chapter 1 Page 38 of 83

Section 3.7: Operator Precedence and Associativity

Operator Precedence ChartPrecedence OperatorHighest Precedence var++ and var-- (Postfix operators)

+, (Unary operators)++var and --var (Prefix operators)(type) (casting)! (Not)*, /, %+, (Binary addition and subtraction)<, <=, >, >= (Comparison)& (Unconditional and)^ (Exclusive or)| (Unconditional or)&& (Conditional and)|| (Conditional or)

Lowest Precedence =, +=, -=, *=, /=, %= (Assignment operators)

From left to right, according to the operator precedence

Section 3.8: (GUI) Confirmation DialogsReview: The showMessageDialog() method (of the javax.swing.JOptionPane class) displays a message in a dialog box. The showInputDialog() method (of the javax.swing.JOptionPane class) displays a dialog box that can be used to retrieve String input.

New GUI method: The showConfirmDialog() method (of the javax.swing.JOptionPane class) displays a dialog box with Yes, no, and Cancel buttons. This method returns a value of 0 (stored in the constant JOptionPane.YES_OPTION), 1 (stored in the constant JOptionPane.NO_OPTION), or 2 (stored in the constant JOptionPane.CANCEL_OPTION). See www.cs.armstrong.edu/liang/intro7e/book/GuessBirthDateUsingConfirmationDialog.java

Computer Science Notes Chapter 1 Page 39 of 83

Chapter 4: Loopsimport java.util.Scanner;

/**The Chap04Basics class implements an application that * performs several mathematical tasks, and is meant to * illustrate the basics of loops * (i.e., while, do-while, and for loop statements). * This is meant as an example of the material in Chapter 4 of the text * _Introduction to Java Programming: Brief Version_, 7th ed. by Y. D. Liang * @author Kevin Mirus */

public class Chap04Basics{

/** Computes x^n, x^(-n), n!, sqrt(x), sin(x), e^x, and a multiplication table. * Uses loops for input validation and program repetition. * @param args is not used. */public static void main(String[] args){

//Tell the user what the program doesSystem.out.println("This program can compute several mathematical " +

"functions and print a multiplication table.");

//Create a Scanner object for reading in the user's inputScanner keyboard = new Scanner(System.in);

//Create a sentinel variable for controlling if the program repetition.int repeatSentinel = 1;do{

System.out.println("\nYour menu of mathematical options is:");System.out.println("1) Compute x^n");System.out.println("2) Compute x^(-n)");System.out.println("3) Compute n!");System.out.println("4) Compute sqrt(x)");System.out.println("5) Compute e^x");System.out.println("6) Compute sin(x)");System.out.println("7) Print a multiplication table");System.out.println("Please enter your menu choice:");int menuChoice = keyboard.nextInt();

switch (menuChoice){

case 1: //1) Compute x^n//Prompt the user for a value of x,System.out.println("\nEnter any real number for x:");double x = keyboard.nextDouble();//Get a value for the exponent n from the user,

//and perform input validation to ensure that it is //a non-negative integer.

int n; do { System.out.println("Enter a non-negative integer for n:"); n = keyboard.nextInt();

Computer Science Notes Chapter 1 Page 40 of 83

if (n < 0) System.out.println("ERROR: Please enter a " + "non-negative integer for n."); }while (n < 0); //Compute x^n double x_pow_n = 1.; for (int i = 1; i <= n; i++) x_pow_n *= x; System.out.println("\n(" + x + ")^" + n + " = " + x_pow_n);

break;

case 2: //2) Compute x^(-n)System.out.println("\nEnter any real number for x:");//Note: x does not need to be declared again, //because it was declared in a switch statementx = keyboard.nextDouble();//Get a value for the exponent n from the user,

//and perform input validation to ensure that it is //a non-negative integer.

do { System.out.println("Enter a non-negative integer for n:"); n = keyboard.nextInt(); if (n < 0) System.out.println("ERROR: Please enter a " + "non-negative integer for n."); }while (n < 0); //Compute x^(-n) x_pow_n = 1.; for (int i = 1; i <= n; i++) x_pow_n /= x; System.out.println("\n(" + x + ")^(-" + n + ") = " + x_pow_n);

break;

case 3: //3) Compute n!//Get a value for n from the user,

//and perform input validation to ensure that it is //between 0 and 20, inclusive, because 20! is the largest

//factorial that fits in a long integer.final long MAX_FACTORIAL = 20;do

{ System.out.println("\nEnter a non-negative integer less " + "than 21 for n:"); n = keyboard.nextInt(); if (n < 0 || n > MAX_FACTORIAL) System.out.println("ERROR: Please enter an " + "integer between 0 and "+MAX_FACTORIAL+ " for n."); }while (n < 0 || n > MAX_FACTORIAL);

//Compute n! long n_factorial = 1; for (int i = 1; i <= n; i++) n_factorial *= i; System.out.print( n + "! = "); if (n > 1) { for (int i = 1; i < n; i++)

Computer Science Notes Chapter 1 Page 41 of 83

System.out.print(i + "*"); System.out.printf(n + " = ");

} System.out.printf("%,1d\n", n_factorial);

break;

case 4: //4) Compute sqrt(x)//Get a value for x from the user,

//and perform input validation to ensure that it is //a non-negative.

do {

System.out.println("\nEnter a nonnegative real " +"number for x:");

x = keyboard.nextDouble(); if (x < 0) System.out.println("ERROR: Please enter a " + "non-negative real number for x."); }while (x < 0); //Get a tolerance for computations from the user System.out.println("Enter a tolerance for the non-exact " + "computations (1e-10 is a recommended value):");

double tolerance = keyboard.nextDouble();tolerance = Math.abs(tolerance);

//Compute sqrt(x) double sqrt_x = x / 2.; double old_sqrt = x; int numberIterations = 0; while(sqrt_x > 0 && Math.abs(sqrt_x - old_sqrt) > tolerance) { old_sqrt = sqrt_x; sqrt_x = 0.5 * (sqrt_x + x / sqrt_x); numberIterations++; }; System.out.println("\nAfter " + numberIterations + " iterations, " + "which yields a tolerance of " + tolerance + ":"); System.out.println(" sqrt(" + x + ") = " + sqrt_x); System.out.println("Math.sqrt(" + x + ") = " + Math.sqrt(x));

break;

case 5: //5) Compute e^x System.out.println("\nEnter any real number for x:");

x = keyboard.nextDouble();//Get a tolerance for computations from the user

System.out.println("Enter a tolerance for the non-exact " + "computations (1e-10 is a recommended value):");

tolerance = keyboard.nextDouble();tolerance = Math.abs(tolerance); //Compute e^x

double e_x = 1.; double termValue = 1.; int numberTerms = 1; do { termValue *= x / numberTerms;

e_x += termValue; numberTerms++;

}while(Math.abs(termValue) > tolerance); System.out.println("\nAfter " + numberTerms + " terms, " +

Computer Science Notes Chapter 1 Page 42 of 83

"which yields a tolerance of " + tolerance + ":"); System.out.println(" exp(" + x + ") = " + e_x); System.out.println("Math.exp(" + x + ") = " + Math.exp(x));

break;case 6: //6) Compute sin(x)

System.out.println("\nEnter any real number for x:");x = keyboard.nextDouble();//Get a tolerance for computations from the userSystem.out.println("Enter a tolerance for the non-exact " + "computations (1e-10 is a recommended value):");tolerance = keyboard.nextDouble();tolerance = Math.abs(tolerance);

//Map x back into an interval between +/- 2pi...double x_1 = x - ((int)(x/(2.*Math.PI))*2.*Math.PI);//Compute sin(x)

double sine_x = x_1; termValue = x_1; numberTerms = 1; do {

termValue = termValue * (-x_1 * x_1) / (2*numberTerms) / (2*numberTerms + 1); sine_x += termValue; numberTerms++;

}while(Math.abs(termValue) > tolerance); System.out.println("\nAfter " + numberTerms + " terms, " + "which yields a tolerance of " + tolerance + ":"); System.out.println(" sin(" + x + ") = " + sine_x); System.out.println("Math.sin(" + x + ") = " + Math.sin(x));

break;

case 7: //7) Print a multiplication tablebreak;

default:System.out.println("That was not a valid menu choice");

}//end switch (menuChoice)

System.out.println("\nEnter 1 to continue or 0 to quit"); repeatSentinel = keyboard.nextInt();}while (repeatSentinel == 1); //end program repetition do-while loop

//Tell the user that the program is done.System.out.println("\nProgram Chap04Basics has terminated.");

}//end of method main(String[])}//end of class Chap04Basics

Computer Science Notes Chapter 1 Page 43 of 83

Section 4.1: IntroductionExample: Print Welcome to Java! 100 times

Without loops Using loops// Print ″Welcome to Java!v 100 timesSystem.out.println("Welcome to Java!″);System.out.println("Welcome to Java!″);System.out.println("Welcome to Java!″);System.out.println("Welcome to Java!″);System.out.println("Welcome to Java!″);

//… 94 more println statements…

System.out.println("Welcome to Java!″);

// Print ″Welcome to Java!″ 100 timesfor (int count = 1; count <= 100; count++) System.out.println("Welcome to Java!″);

Section 4.2: The while Loop Syntax of a while statement:while (condition){

conditionTrueStatement(s);}nextStatement;

Example:public class PrintLoop{

public static void main(String[] args){

// Print "Welcome to Java!" 100 times int counter = 1; int maxPrintLines = 100; while (counter <= maxPrintLines) { System.out.println("Welcome to Java!"); counter++; }

}}

Computer Science Notes Chapter 1 Page 44 of 83

Example:import java.util.Scanner;public class Guessing7Game{

public static void main(String[] args){

// a loop that plays a guessing game

Scanner keyboard = new Scanner(System.in);

System.out.println("Enter a guess:");int guess = keyboard.nextInt();

while (guess != 7){

System.out.println("Bad guess.");System.out.println("Enter a guess:");guess = keyboard.nextInt();

}System.out.println("You guessed correctly!");

}}

Example: INPUT VALIDATION: Notice that this loop keeps on repeating until a valid piece of data is entered.import java.util.Scanner;

public class CircleCircumference{

public static void main(String[] args){

System.out.println("This program will compute the circumference of " +"a circle given its radius.");

Scanner keyboard = new Scanner(System.in);

// Get the user’s input for a circle radiusSystem.out.println("Enter the radius of a circle:");double radius = keyboard.nextDouble();

// a loop that validates an input for a radiuswhile (radius < 0.0){

System.out.println("Bad entry; you entered r = " + radius + ", and the radius of a circle should NOT be negative.");

System.out.println("Enter a positive radius for the circle:");radius = keyboard.nextDouble();

}System.out.println("For a circle of radius " + radius +

", the circumference is: " + (2*Math.PI*radius) + ".");}

}

Computer Science Notes Chapter 1 Page 45 of 83

Example: PROGRAM REPETITION: This is useful if you want to repeat the entire body of a program.

import java.util.Scanner;

public class CompareNumbers{

/** Prompts the user for two numbers to compare. * @param args is not used*/public static void main (String[ ] args){

System.out.println("This program compare two numbers as many times as you like.");

//Declare variables for the data to be read in: two numbers for comparison.double num1, num2;

//Create a Scanner object for reading in the user's inputScanner keyboard = new Scanner(System.in);

int compareAgain = 1;while (compareAgain == 1){

//get the user's dataSystem.out.println("\nPlease enter a number:");num1 = keyboard.nextDouble();

System.out.println("Please enter a second number:");num2 = keyboard.nextDouble();

//Compare the numbersSystem.out.println("Here is the comparison:");if (num1 < num2)

System.out.println(num1 + " < " + num2);else if (num1 > num2)

System.out.println(num1 + " > " + num2);else

System.out.println(num1 + " = " + num2);

System.out.println("Enter 1 to continue or 0 to quit:");compareAgain = keyboard.nextInt();

}System.out.println("\nProgram Terminated.");}

}

Computer Science Notes Chapter 1 Page 46 of 83

Example: Notice that a variable can be defined in a loop, but that it only exists in memory while the loop is executing.

public class InvestmentMaturityDate{

public static void main(String[] args){

// a loop that computes how many years // until a $10,000 investment reaches a target balance of $20,000// at an interest rate of 8%

double initialBalance = 10000.00;double targetBalance = 20000.00;double rate = 0.08;double currentBalance = initialBalance;int years = 0;

while (currentBalance < targetBalance){

years++;double interest = currentBalance * rate;currentBalance = currentBalance + interest;

}//NOTE: the interest variable no longer exists outside the loop//SO, it can not be used for output or further calculations.

System.out.println("An investment of $" + initialBalance + " earning " + (rate*100) + "% interest per year" +" grows to at least $" + targetBalance + " after " + years + " years.");

System.out.printf("In fact, the investment is worth $%,9.2f " +" at the end of the %2d years\n", currentBalance, years);

}}

Computer Science Notes Chapter 1 Page 47 of 83

Example: A loop that executes a pre-determined number of times.public class FutureValueOfAnInvestment{

public static void main(String[] args){

// a loop that computes the value of a $10,000 investment // after 5 years when earning at an interest rate of 8%double initialBalance = 10000.00;double rate = 0.08;int maxYears = 5;double currentBalance = initialBalance;int years = 0;

while (years < maxYears){ years++; double interest = currentBalance * rate; currentBalance = currentBalance + interest;}

System.out.println("An investment of $" + String.format("%,10.2f",initialBalance) +

" invested at " + (rate*100) + "% interest per year " + "grows to $" + String.format("%,10.2f",currentBalance) + " after " + maxYears + " years.");

}}

Computer Science Notes Chapter 1 Page 48 of 83

Section 4.2.1: Problem: Guessing Numbers

Section 4.2.2: Problem: An Advanced Math Learning Tool

Section 4.2.3: Controlling a Loop with a Sentinel ValueExample: Computing the average of a list of user-entered numbers.import java.util.Scanner;public class Average{

public static void main (String[ ] args){

System.out.println("This program computes the average of non-negative " +"numbers.");

//Declare variables for the data entries, number of entries, and average.double dataEntry = 0.0, average = 0.0;int numEntries = 0;

//Create a Scanner object for reading in the user's inputScanner keyboard = new Scanner(System.in);

while (dataEntry >= 0.0){

//get the user's dataSystem.out.println("Please enter a number (or a negative value " +

"to quit):");dataEntry = keyboard.nextDouble();if (dataEntry >= 0.0){

average += dataEntry;numEntries++;

}}if (numEntries > 0){

average = average / numEntries;System.out.println("\nThe average of your " + numEntries +

" values is: " + average);}else

System.out.println("\nNo data enetered.");

System.out.println("\nProgram Terminated.");}//end main()

}

Computer Science Notes Chapter 1 Page 49 of 83

Section 4.3: The do-while Loop Syntax of a do-while statement:do{

Statement(s);} while (condition);nextStatement;

Example: Notice that the program does not have to have the prompt and input lines of code repeated like in the while loop, but that you do need an if statement to handle the error message to the user when an incorrect guess is entered.

import java.util.Scanner;public class Guessing7Game{

public static void main(String[] args){

// a loop that plays a guessing game

Scanner keyboard = new Scanner(System.in);

int guess;do{

System.out.println("Enter a guess:");guess = keyboard.nextInt();if (guess != 7) System.out.println("Bad guess.");

}while (guess != 7);

System.out.println("You guessed correctly!");}

}

Computer Science Notes Chapter 1 Page 50 of 83

Section 4.4: for Loops Syntax of a simple for statement:for (initial_action; loop_continuation_condition; action_after_each_iteration)

Statement;nextStatement;

Syntax of a block for statement:for (initial_action; loop_continuation_condition; action_after_each_iteration){

Statement(s);}nextStatement;

Example: A loop that executes a pre-determined number of times. It is possible to both define and initialize a variable in the header, but that variable only exists in memory while the loop is executing…public class FutureValueOfAnInvestment{

public static void main(String[] args){

// a loop that computes the value of a $10,000 investment // after 5 years when earning at an interest rate of 8%double initialBalance = 10000.00;double rate = 0.08;int maxYears = 5;double currentBalance = initialBalance;int years = 0;

for (years = 1; years <= maxYears; years ++){

double interest = currentBalance * rate;currentBalance = currentBalance + interest;

}

System.out.println("An investment of $" + String.format("%,10.2f",initialBalance) +

" invested at " + (rate*100) + "% interest per year " + "grows to $" + String.format("%,10.2f",currentBalance) + " after " + maxYears + " years.");

}}

Computer Science Notes Chapter 1 Page 51 of 83

Example:

public class IntegerSum{

public static void main(String[] args){

// a loop that sums the numbers from 1 to 10

int sum = 0;int lastInteger = 1000;

for (int i= 1; i <= lastInteger; i++)sum += i;

System.out.println("The sum of integers from 1 to " + lastInteger + " = " + sum);

}}

Section 4.5: Which Loop to Use? while and for loops are pre-test loops. do-while loops are post-test loops. Use a while loop when you want to test the condition first. Use a do-while loop when you want the body to execute at least once. Use a for loop when you want to test the condition first, and the loop will execute a pre-determined number of times.

public class IntegerSum{

public static void main(String[] args){

//Sum the numbers from 1 to 1000.int lastInteger = 1000;int sum = 0;//Perform the calculation with a for loop.for (int i= 1; i <= lastInteger; i++)

sum += i;System.out.println("The sum of integers from 1 to " + lastInteger +

" = " + sum);

//Perform the calculation with a while loop.sum = 0;int i = 0;while (i <= lastInteger){

sum += i;i++;

}System.out.println("The sum of integers from 1 to " + lastInteger +

" = " + sum);//Perform the calculation with a do loop.sum = 0;i = 0;do{

sum += i;

Computer Science Notes Chapter 1 Page 52 of 83

i++;}while (i < lastInteger+1);System.out.println("The sum of integers from 1 to " + lastInteger +

" = " + sum);}

}

Section 4.6: Nested LoopsExample: Print a triangular shape as follows:XXXXXXXXXXXXXXX

public class PrintRightTriangle {

public static void main(String[] args){

// Print a right triangle of x's.int maxRows = 5;

for (int row = 1; row <= maxRows; row++){

for (int col = 1; col <= row; col++){

System.out.print("X");}System.out.println();

}}

}

Section 4.7: Minimizing Numerical Errors

Section 4.8: Case StudiesSection 4.8.1: Problem: Finding the Greatest Common DivisorSection 4.8.2: Problem: Finding the Sales AmountSection 4.8.3: Problem: Displaying a Pyramid of Numbers

Section 4.9: Keywords break and continue break immediately ends the innermost loop that contains it. break breaks out of a loop. It is generally used with an if statement. continue only ends the current iteration of the loop that contains it. Program control goes to the end of the loop body. continue breaks out of an iteration. It is generally used with an if statement.Section 4.9.1: Problem: Displaying Prime Numbers Section 4.10: Controlling a Loop with a Confirmation DialogIf you want the user of a program to decide when to end a loop, you can prompt them if they want to continue using a confirmation dialog box (as opposed to prompting for input from the console in some of the examples above).

Computer Science Notes Chapter 1 Page 53 of 83

Example: PROGRAM REPETITION using a confirmation dialog.

import javax.swing.JOptionPane;

public class Chap04BasicsGUI{

/** Prompts the user for two numbers to compare. * @param args is not used*/public static void main (String[ ] args){

//Tell the user what the program doesJOptionPane.showMessageDialog(null, "This program compare two " +

"numbers as many times as you like.", "Chap04BasicsGUI Intro",JOptionPane.INFORMATION_MESSAGE);

//Declare variables for the data to be read in: two numbers for comparison.double num1, num2;String numberString;

int compareAgain = JOptionPane.YES_OPTION;while (compareAgain == JOptionPane.YES_OPTION){

//get the user's datanumberString = JOptionPane.showInputDialog(null, "Please enter the " +

"first number:", "First Number",JOptionPane.QUESTION_MESSAGE);

num1 = Double.parseDouble(numberString);

numberString = JOptionPane.showInputDialog(null, "Please enter the " +"second number:", "Second Number",JOptionPane.QUESTION_MESSAGE);

num2 = Double.parseDouble(numberString);

//Compare the numbersString resultString = "Here is the comparison:\n";if (num1 < num2)

resultString += (num1 + " < " + num2);else if (num1 > num2)

resultString += (num1 + " > " + num2);else

resultString += (num1 + " = " + num2);

JOptionPane.showMessageDialog(null, resultString, "Results",JOptionPane.INFORMATION_MESSAGE);

compareAgain = JOptionPane.showConfirmDialog(null, "Do you want to continue?");

}JOptionPane.showMessageDialog(null, "Program Terminated.", "All Done",

JOptionPane.INFORMATION_MESSAGE);}

}

Chapter 5: Methods

import java.util.Scanner;

Computer Science Notes Chapter 1 Page 54 of 83

/**The Chap05Basics class implements an application that * plays a four-number lottery game, and is meant to * illustrate the basics of methods. * This is meant as an example of the material in Chapter 5 of the text * _Introduction to Java Programming: Brief Version_, 7th ed. by Y. D. Liang * @author Kevin Mirus */

public class Chap05Basics{

/** Run a four-pick lottery game with input validation. * Uses methods to avoid redundancy and enhance modularity. * @param args is not used. */public static void main(String[] args){

// Tell the user what the program does.System.out.println("This program simulates a four-number lottery game.\n");

Scanner keyboard = new Scanner(System.in);int continueSentinel = 1;do{

//Prompt the user for the range of numbers.String userPrompt = "Please enter a positive lower bound for the " +

"lottery numbers:";int lowerBound = getIntegerGreaterThan(0, userPrompt, keyboard);

userPrompt = "Please enter a positive upper bound for the lottery " +"numbers:";

int upperBound = getIntegerGreaterThan(lowerBound+2, userPrompt, keyboard);

//Compute four distinct winning lottery numbers.int lotto1, lotto2, lotto3, lotto4;lotto1 = getRandomNonDuplicatingIntegerInRange(lowerBound, upperBound,

-1, -1, -1);lotto2 = getRandomNonDuplicatingIntegerInRange(lowerBound, upperBound,

lotto1, -1, -1);lotto3 = getRandomNonDuplicatingIntegerInRange(lowerBound, upperBound,

lotto1, lotto2, -1);lotto4 = getRandomNonDuplicatingIntegerInRange(lowerBound, upperBound,

lotto1, lotto2, lotto3);

//Let user decide to enter numbers by hand or let computer pick.int pick1, pick2, pick3, pick4;System.out.println("Enter 1 if you want to make your own picks.");System.out.println("Enter 2 if you want the computer to make your " +

"picks.");int whoMakesThePicksChoice = keyboard.nextInt();switch (whoMakesThePicksChoice){

case 1: //User does own picks//Prompt the user for four valid picks //i.e., in bounds, no duplicates).//Also, perform input validation on the picks.userPrompt = "Please enter your first lottery pick:";pick1 = getValidNonDuplicatingIntegerInRange(lowerBound,

upperBound, -1238, -1238, -1238, userPrompt,

Computer Science Notes Chapter 1 Page 55 of 83

keyboard);//Get second pick with input validation.userPrompt = "Please enter your second lottery pick:";pick2 = getValidNonDuplicatingIntegerInRange(lowerBound,

upperBound, pick1, pick1, pick1, userPrompt, keyboard);

//Get third pick with input validation.userPrompt = "Please enter your third lottery pick:";pick3 = getValidNonDuplicatingIntegerInRange(lowerBound,

upperBound, pick1, pick2, pick2, userPrompt, keyboard);

//Get fourth pick with input validation.userPrompt = "Please enter your fourth lottery pick:";pick4 = getValidNonDuplicatingIntegerInRange(lowerBound,

upperBound, pick1, pick2, pick3, userPrompt, keyboard);

break;case 2: //Computer does picks.

//Just in case the user enters something besides 2, //this case falls through to the default.

default: //Compute four distinct winning lottery numbers.pick1 = getRandomNonDuplicatingIntegerInRange(lowerBound,

upperBound, -1, -1, -1);pick2 = getRandomNonDuplicatingIntegerInRange(lowerBound,

upperBound, pick1, -1, -1);pick3 = getRandomNonDuplicatingIntegerInRange(lowerBound,

upperBound, pick1, pick2, -1);pick4 = getRandomNonDuplicatingIntegerInRange(lowerBound,

upperBound, pick1, pick2, pick3);}

//Show the results:System.out.println("\nThe range of your lottery picks is from " +

lowerBound + " to " + upperBound + ".");System.out.printf("Here are the lotto numbers:%4d %4d %4d %4d\n",

lotto1, lotto2, lotto3, lotto4);System.out.printf("Here are your picks :%4d %4d %4d %4d\n",

pick1, pick2, pick3, pick4);

if (pick1 == lotto1 && pick2 == lotto2 && pick3 == lotto3 && pick4 == lotto4)

System.out.println("Exact match! You win $10,000!");else {

int numMatches = getNumberOfMatchesBetween(pick1, pick2, pick3, pick4, lotto1, lotto2, lotto3, lotto4);

System.out.println("You had " + numMatches + " matches. " +"You win $" + numMatches + ",000!");

}

System.out.println("Enter 1 to play again, any other number to quit.");continueSentinel = keyboard.nextInt();

}while (continueSentinel == 1);//end of do-while loop to repeat programSystem.out.println("Program Chap05Basics is now terminating.");

}//end of method main(String[])

/** * Prompts the user for an integer, * and then performs input validation

Computer Science Notes Chapter 1 Page 56 of 83

* to ensure the integer is greater than some minimum value. * @param minValue is the minimum value * @param promptString contains the prompt for the user * @param keyboard is a Scanner object from which to get the user input * @return an integer greater than minValue */public static int getIntegerGreaterThan(int minValue, String promptString,

Scanner keyboard){

//Print the prompt string.System.out.println(promptString);int userInteger = keyboard.nextInt();//Perform input validation on userInteger //to make sure it is greater than the minimum value.while (userInteger <= minValue){

System.out.println("Invalid entry. Entry must be greater than " + minValue);

System.out.println(promptString);userInteger = keyboard.nextInt();

}return userInteger;

}//end method getIntegerGreaterThan(int, String, Scanner)

/** * Generates a random integer within a range of values * that does not duplicate three given numbers. * @param lowerBound is the lower bound of the range of numbers * @param upperBound is the upper bound of the range of numbers * @param n1 is the first number not to duplicate * @param n2 is the second number not to duplicate * @param n3 is the third number not to duplicate * @return a random integer between lowerBound and upperBound, inclusive, * that is not equal to n1 or n2 or n3 */public static int getRandomNonDuplicatingIntegerInRange(int lowerBound, int

upperBound, int n1, int n2, int n3){

//Generate a random number between lowerBound and upperBound.int randomNumber = (int)(Math.random()*(upperBound - lowerBound + 1)) + lowerBound;//Make sure that number does not duplicate n1, n2, or n3.while(randomNumber == n1 || randomNumber == n2 || randomNumber == n3) {

randomNumber = (int)(Math.random()*(upperBound - lowerBound + 1)) + lowerBound;

};return randomNumber;

}//end method getRandomNonDuplicatingIntegerInRange(int, int, int, int, int)

/** * Prompts the user for an integer, * and then performs input validation * to ensure the integer is within a range of values, * and does not duplicate three given numbers. * @param lowerBound is the lower bound of the range of numbers * @param upperBound is the upper bound of the range of numbers * @param n1 is the first number not to duplicate * @param n2 is the second number not to duplicate * @param n3 is the third number not to duplicate

Computer Science Notes Chapter 1 Page 57 of 83

* @param promptString contains the prompt for the user * @param keyboard is a Scanner object from which to get the user input * @return */public static int getValidNonDuplicatingIntegerInRange(int lowerBound,

int upperBound, int n1, int n2, int n3, String promptString, Scanner keyboard)

{int userInteger;do{

System.out.println(promptString);userInteger = keyboard.nextInt();if ( (userInteger < lowerBound || userInteger > upperBound))

System.out.println("Invalid entry. Entry must be between " + lowerBound + " and " + upperBound + ".");

if ( (userInteger == n1) || (userInteger == n2) || (userInteger == n3))System.out.println("Invalid entry. No duplicate picks allowed.");

}while( (userInteger < lowerBound || userInteger > upperBound) || (userInteger == n1) || (userInteger == n2) || (userInteger == n3));

return userInteger;}//end method getValidNonDuplicatingIntegerInRange(int, int, //int, int, int, String, Scanner)

/** * Counts how many matching numbers there are between two sets of * four numbers in each set * @param n1 is a number in the first set * @param n2 is a number in the first set * @param n3 is a number in the first set * @param n4 is a number in the first set * @param m1 is a number in the second set * @param m2 is a number in the second set * @param m3 is a number in the second set * @param m4 is a number in the second set * @return how many of the values in n1..n4 match values in m1..m4 */public static int getNumberOfMatchesBetween(int n1, int n2, int n3, int n4,

int m1, int m2, int m3, int m4){

//Thanks to Patrick Kirk for this efficient technique of counting //the number of matches!int numMatches = 0;if (n1 == m1 || n1 == m2 || n1 == m3 || n1 == m4) numMatches++;if (n2 == m1 || n2 == m2 || n2 == m3 || n2 == m4) numMatches++;if (n3 == m1 || n3 == m2 || n3 == m3 || n3 == m4) numMatches++;if (n4 == m1 || n4 == m2 || n4 == m3 || n4 == m4) numMatches++;

return numMatches;}//end method getNumberOfMatchesBetween(int, int, int, int, int, int, int, int)

}//end of class Chap05Basics

Section 5.1: Introduction

Section 5.2: Creating a MethodThe general syntax to create a method is:modifier(s) return_value_type method_name (list_of_parameters)

Computer Science Notes Chapter 1 Page 58 of 83

{ statements;

}

1. The modifiers we will use in this chapter will always be public static2. The return_value_type we will use in this chapter are int, double, float, String,

char, or void.3. method_name should always start with a lowercase letter.4. The list_of_parameters is a list of variables with their type that will store information we want

to send into the method. A single variable in the list is called an argument.5. We will also use the javadoc style of commenting our methods:

/** Verb phrase telling what the method does. * @param parameter_name and what it stores. * @param parameter_name (for each parameter in the list). * @return what the method returns as a result of its calculation.*/

Practice: Write a program that prompts the user for two integers and then computes and prints out the sum of integers from the lower integer to the upper integer. Use at least one method in your program.

Computer Science Notes Chapter 1 Page 59 of 83

Solution:

import java.util.Scanner;

/** The SumExample class implements an application that sums up all integers * between two bounds. * @author Kevin Mirus * */public class SumExample {

/**Prompts user for two integers, then add up all integers between them. * @param args is not used. */public static void main(String[] args) {

// Prompt the user for two integers.Scanner keyboard = new Scanner(System.in);System.out.println("This program sums integers.");System.out.println("Please enter an integer:");int number1 = keyboard.nextInt();

System.out.println("Please enter another integer:");int number2 = keyboard.nextInt();//Figure out which number is smaller and larger.

int lowerBound = min(number1, number2);int upperBound = max(number1, number2);

System.out.println("The sum of integers from " + lowerBound + " to " + upperBound + " = " + sumOfIntegersBetween(lowerBound, upperBound) );

}//end method main(String[])

/** * Finds the minimum of two integers. * @param n1 is the first integer * @param n2 is the second integer * @return the smaller of n1 and n2 */public static int min(int n1, int n2){

/*//assume that n1 is the smaller numberint minimum = n1;//change minimum if not trueif (n2 < minimum)

minimum = n2;return minimum;*/

/*//use a conditional operatorint minimum = (n1 < n2) ? n1 : n2;return minimum;*/

Computer Science Notes Chapter 1 Page 60 of 83

return (n1 < n2) ? n1 : n2;

}//end method min(int, int)

/** * Finds the maximum of two integers. * @param n1 is the first integer * @param n2 is the second integer * @return the larger of n1 and n2 */public static int max(int n1, int n2){

return (n1 > n2) ? n1 : n2;}//end method max(int, int)

/** * Computes the sum of integers between two bounds. * Precondition: low <= high * @param low is the lower bound of the range of numbers * @param high is the upper bound of the range of numbers * @return the sum of all integers from low to high */public static long sumOfIntegersBetween(int low, int high){

long sum = 0;for (int counter = low; counter <= high; counter++)

sum += counter;

return sum;}//end method sumOfIntegersBetween(int, int)

}//end class SumExample

Computer Science Notes Chapter 1 Page 61 of 83

Section 5.3: Calling a Method When you implement a method, you write the code that makes the method do what it is supposed to do. When you call or invoke a method, you write a line of code that uses the method you implemented. If the method returns a value, you usually invoke the method with an assignment statement:

double sqrt_5 = Math.sqrt(5); If the method does not return a value (i.e., it returns void) , you invoke the method as a statement

System.out.println(″Hi!″); The main method is just like any other method except that it is invoked by the JVM automatically when the program starts running. The main method’s header is always the same: public static void main(String[] args), where String[] is an array of String objects that are used when the program is run from the command line (see chapter 6 on Arrays). A return statement is required in any method that returns a value. Methods allow for code sharing and reuse. USE THEM!

Section 5.3.1: Call Stacks

Section 5.4: void Method Example A void method does not return any value, so it is invoked as a statement. The return statement can be used in a void method to terminate the method and return execution to the method’s caller.

Section 5.5: Passing Parameters by Values Parameter order association: when calling a method, the order in which you provide arguments must be in the same order as their respective parameters in the method specification. Having the same name of variables does not do the trick.

Section 5.6: Modularizing Code Methods can be used to reduce redundant code. Methods can be used to enable code reuse. Methods can be used to improve the quality of a program.

o The code becomes easier to read because problems are isolated into separate pieces.o Debugging becomes easier because you can debug one method at a time instead of the whole

program at once.

Section 5.7: Overloading Methods Method overloading: Implementing two methods with the same name but different parameter lists within one class. The Java compiler decides which method to use based on the method signature. Overloading methods can make programs clearer and more readable. Methods that perform similar tasks on slightly different data should be given the same name. Overloaded methods must have different parameter lists. You can’t overload methods based on return type or other modifiers. Ambiguous invocation: When a method invocation matches two or more methods. Net result: compiler error.

Computer Science Notes Chapter 1 Page 62 of 83

Section 5.8: The Scope of Variables Scope of a variable: the portion of a program where a variable can be referenced (i.e., which portion of the call stack is the variable in). Local variable: a variable defined in a method. Thus, its scope is only within that method. Sometimes you can use the same variable name within a block inside another block, but you really should avoid doing that…

Section 5.9: The Math Class Section 5.9.1: Trigonometric Methodsstatic double acos(double a) Returns the arc cosine of a value; the returned angle is in the range 0.0 through pi.static double asin(double a) Returns the arc sine of a value; the returned angle is in the range -pi/2 through pi/2.static double atan(double a) Returns the arc tangent of a value; the returned angle is in the range -pi/2 through pi/2.static double atan2(double y, double x) Returns the angle theta from the conversion of rectangular coordinates (x, y) to polar coordinates (r, theta).static double cos(double a) Returns the trigonometric cosine of an angle.static double hypot(double x, double y) Returns sqrt(x2 +y2) without intermediate overflow or underflow.static double sin(double a) Returns the trigonometric sine of an angle.static double tan(double a) Returns the trigonometric tangent of an angle.static double toDegrees(double angrad) Converts an angle measured in radians to an approximately equivalent angle measured in degrees.static double toRadians(double angdeg) Converts an angle measured in degrees to an approximately equivalent angle measured in radians.

Section 5.9.2: Exponent Methodsstatic double cbrt(double a) Returns the cube root of a double value.static double cosh(double x) Returns the hyperbolic cosine ( cosh(x) = (e^x + e^(-x)) / 2 ) of a double value.static double exp(double a) Returns Euler's number e raised to the power of a double value.static double expm1(double x) Returns e^x -1.static int getExponent(double d) Returns the unbiased exponent used in the representation of a double.static int getExponent(float f) Returns the unbiased exponent used in the representation of a float.static double log(double a) Returns the natural logarithm (base e) of a double value.static double log10(double a) Returns the base 10 logarithm of a double value.static double log1p(double x)

Computer Science Notes Chapter 1 Page 63 of 83

Returns the natural logarithm of the sum of the argument and 1.static double pow(double a, double b) Returns the value of the first argument raised to the power of the second argument.static double sinh(double x) Returns the hyperbolic sine ( sinh(x) = (e^x – e^(-x)) / 2 ) of a double value.static double sqrt(double a) Returns the correctly rounded positive square root of a double value.static double tanh(double x) Returns the hyperbolic tangent ( tanh(x) = sinh(x) / cosh(x) ) of a double value.

Section 5.9.3: The Rounding Methodsstatic double ceil(double a) Returns the smallest (closest to negative infinity) double value that is greater than or equal to the static double floor(double a) Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer.static double rint(double a) Returns the double value that is closest in value to the argument and is equal to a mathematical integer.static long round(double a) Returns the closest long to the argument.static int round(float a) Returns the closest int to the argument.

Section 5.9.4: The min , max , and abs Methods static double abs(double a) Returns the absolute value of a double value.static float abs(float a) Returns the absolute value of a float value.static int abs(int a) Returns the absolute value of an int value.static long abs(long a) Returns the absolute value of a long value.static double max(double a, double b) Returns the greater of two double values.static float max(float a, float b) Returns the greater of two float values.static int max(int a, int b) Returns the greater of two int values.static long max(long a, long b) Returns the greater of two long values.static double min(double a, double b) Returns the smaller of two double values.static float min(float a, float b) Returns the smaller of two float values.static int min(int a, int b) Returns the smaller of two int values.static long min(long a, long b) Returns the smaller of two long values.

Computer Science Notes Chapter 1 Page 64 of 83

Section 5.9.5: The random Method static double random() Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.

Section 5.10: Case Study: Generating Random Characters

Section 5.11: Method Abstraction and Stepwise Refinement

Section 5.11.1: Top-Down Design

Section 5.11.2: Top-Down or Bottom-Up Implementation

Section 5.11.3: Implementation Details

Computer Science Notes Chapter 1 Page 65 of 83

Chapter 6: Arrays

import java.util.Scanner;

/**The Chap06Basics class implements an application that * plays an n-number lottery game, and is meant to * illustrate the basics of arrays. * This is meant as an example of the material in Chapter 6 of the text * _Introduction to Java Programming: Brief Version_, 7th ed. by Y. D. Liang * @author Kevin Mirus */

public class Chap06Basics{

/** Run an n-pick lottery game (user's choice) with input validation. * Uses methods to avoid redundancy and enhance modularity. * Uses arrays to store all the picks and winning lottery numbers. * @param args is not used. */public static void main(String[] args){

// Tell the user what the program does.System.out.println("This program simulates a number lottery game.\n");

Scanner keyboard = new Scanner(System.in);int continueSentinel = 1;do{

//Prompt the user for how many numbers are in the lotto game.//Re-Use the getIntegerGreaterThan() method from Chap05Basics.//Note: having Chap05Basics.java in the same package as //Chap06Basics allows you to do this...String userPrompt = "\nPlease enter how many numbers are in the " +"lottery game:";int numPicks =

Chap05Basics.getIntegerGreaterThan(0, userPrompt, keyboard);

//Prompt the user for the range of numbers.userPrompt = "Please enter a positive lower bound for the " +

"lottery numbers:";int lowerBound =

Chap05Basics.getIntegerGreaterThan(0, userPrompt, keyboard);

userPrompt = "Please enter a positive upper bound for the lottery " +"numbers:";

int upperBound = Chap05Basics.getIntegerGreaterThan(lowerBound + numPicks - 2, userPrompt, keyboard);

//Generate the winning lottery numbers.int[] winningLottoNumbers = new int[numPicks];fillArray_UniqueRandomIntegersBetween

(winningLottoNumbers, lowerBound, upperBound);

//Let user decide to enter numbers by hand or let computer pick.int[] userPicks = new int[numPicks];System.out.println("Enter 1 if you want to make your own picks.");System.out.println("Enter 2 if you want the computer to make your " +

"picks.");

Computer Science Notes Chapter 1 Page 66 of 83

int whoMakesThePicksChoice = keyboard.nextInt();

switch (whoMakesThePicksChoice){

case 1: //User does own picksfillArray_UniqueUserIntegersBetween(userPicks, lowerBound, upperBound, keyboard);break;

case 2: //Computer does picks.fillArray_UniqueRandomIntegersBetween(userPicks, lowerBound, upperBound);break;

default: System.out.println("Invalid choice. Let's start over...");continue;

}

//Show the results:System.out.println("\nThe range of your lottery picks is from " +

lowerBound + " to " + upperBound + ".");System.out.print("Here are the lotto numbers: ");//Use a loop to print the array of winning lotto numbers.for (int i = 0; i < numPicks; i++)

System.out.printf("%4d ",winningLottoNumbers[i]);

System.out.print("\nHere are your picks : ");//Use a loop to print the array of picks.for (int i = 0; i < numPicks; i++)

System.out.printf("%4d ",userPicks[i]);System.out.println();

//Check to see if the picks are an exact match, including order.boolean exactMatch = true;for(int i = 0; i < numPicks; i++)

exactMatch = exactMatch && (userPicks[i] == winningLottoNumbers[i]);

//Compute the matches between the lotto numbers and the picks.int numMatches =

getNumberOfMatchesBetween(userPicks, winningLottoNumbers);

//Print out what the user wins.if (exactMatch)

System.out.println("Exact match! You win $100,000!");else if (numMatches > 0)

System.out.println("You had " + numMatches + " matches. " +"You win $" + numMatches + ",000!");

elseSystem.out.println("You had no matches. You win NOTHING!");

System.out.println("Enter 1 to play again, any other number to quit.");continueSentinel = keyboard.nextInt();

}while (continueSentinel == 1);//end of do-while loop to repeat programSystem.out.println("Program Chap06Basics is now terminating.");

}//end of method main(String[])

/** * Fills an integer array with random, non-duplicating numbers within * a range of numbers. * Precondition: the range of numbers must be large enough so as

Computer Science Notes Chapter 1 Page 67 of 83

* not to force duplication. * @param array is the integer array to fill with random numbers * @param low is the low end of the range of numbers * @param high is the high end of the range of numbers */public static void fillArray_UniqueRandomIntegersBetween(int[] array,

int low, int high){

//Fill the array with non-duplicating (sequential) numbers.fillArray_StartingAt(array, Integer.MIN_VALUE);

//Generate random numbers for each element of the array.for(int i = 0; i < array.length; i++){

//Verify the random number computed for the array element//does not duplicate other elements in the array.do{

array[i] = getRandomIntegerBetween(low, high);}while (arrayHasDuplicates(array));

}}//end method fillArray_UniqueRandomIntegersBetween(int[], int, int)

/** * Fills an integer array with numbers specified by a user * and enforces input validation to ensure no duplicates. * Precondition: the range of numbers must be large enough so as * not to force duplication. * @param array is the integer array to fill with user-specified numbers * @param low is the low end of the range of numbers * @param high is the high end of the range of numbers * @param keyboard is a Scanner object for reading in the numbers. */public static void fillArray_UniqueUserIntegersBetween(int[] array,

int low, int high, Scanner keyboard){

//fill the array with non-duplicating numbers outside the rangefillArray_StartingAt(array, Integer.MIN_VALUE);

for(int i = 0; i < array.length; i++){

do{

System.out.println("Please enter pick #" + (i+1) + ": ");array[i] = keyboard.nextInt();if (arrayHasDuplicates(array))

System.out.println("Invalid entry. It duplicates " +"a previous value.");

if (array[i] < low || array[i] > high)System.out.println("Invalid entry. Please enter a " +

"number between " + low + " and " + high + ".");

}while (arrayHasDuplicates(array) || array[i] < low || array[i] > high);

}}//end method fillArray_UniqueUserIntegersBetween(int[], int, int, Scanner)

/** * Fills an integer array with sequential integers starting * at a given value

Computer Science Notes Chapter 1 Page 68 of 83

* @param array is the integer array to fill with sequential integers * @param low is the starting value. */public static void fillArray_StartingAt(int[] array,

int low){

for(int i = 0; i < array.length; i++)array[i] = low + i;

}

/** * Determines if an integer array has elements with duplicate values. * @param array is the array to test for duplciate values. * @return true if array has one or more duplicate values. */public static boolean arrayHasDuplicates(int[] array){

return (getNumberOfMatchesBetween(array, array) > array.length);}//end method arrayHasDuplicates(int[])

/** * Generates a random integer within a range of numbers. * @param lowerBound is the lower bound of the range of numbers * @param upperBound is the upper bound of the range of numbers * @return a random integer between lowerBound and upperBound, inclusive */public static int getRandomIntegerBetween(int lowerBound, int upperBound){

//Generate a random number between lowerBound and upperBound.return (int)(Math.random()*(upperBound - lowerBound + 1)) + lowerBound;

}//end method getRandomIntegerBetween(int, int)

/** * Counts the number of common elements between two given integer arrays. * @param array1 is the first integer array * @param array2 is the second integer array * @return */public static int getNumberOfMatchesBetween(int[] array1, int[]array2){

int numMatches = 0;for(int i = 0; i < array1.length; i++)

for(int j = 0; j < array2.length; j++)if (array1[i] == array2[j]) numMatches++;

return numMatches;}//end method getNumberOfMatchesBetween(int[], int[])

}//end of class Chap06Basics

Computer Science Notes Chapter 1 Page 69 of 83

Section 6.1: IntroductionAn array is a fixed-size sequence of elements (or values) of the same type.

Section 6.2: Array Basics Since an array is a collection of variables of the same type, we can use an array to replace multiple individual variables that store data of the same type with a single “variable” with multiple slots in it. For example, instead of having 100 variables named number0, number1, number2, …, number99, we can just have one array named number that has 100 slots that can be accessed with an integer from 0 through 99: number[0], number[1], number[2], …, number[99]

Section 6.2.1: Declaring Array VariablesTo use an array, you must declare a variable to reference the array, and specify the type of data that will be stored in the array.Syntax to declare an array variable:

dataType[] arrayRefVariableExample:

int[] userPicks;

Section 6.2.2: Creating Arrays Declaring an array does not allocate memory space for the array. It only creates one location in memory that stores the reference (i.e., location in memory, written as a hexadecimal number) for the array. If the declaration of an array does not have any data associated with it, then the value of the variable is null. One way to actually create an array (i.e., set aside memory space for all the elements) is to use the new operator where you say how many array elements of what data type you want.

Syntax to create an array:arrayRefVariable = new dataType[arraySize];

Example: userPicks = new int[numPicks];

The above example sets aside enough memory for an integer array with numPicks elements, and also stores a number in userPicks that indicates the memory address of the first element of the array.

Declaring and creating arrays can be combined into one statement:Example: a

int[] userPicks = new int[numPicks];

To store values in the array elements, use this syntax:Syntax to assign a value to an element of an array:

arrayRefVariable [index] = value;Example:

userPicks[0] = 5;userPicks[1] = 7;

Computer Science Notes Chapter 1 Page 70 of 83

Section 6.2.3: Array Size and Default ValuesWhen memory space for an array is allocated, the array size must be given, and the size can’t be changed after that.When array is created, all values are initialized depending on the array type:

Numbers: 0 Boolean: false character: ’\u0000’ Object References: null

Section 6.2.4: Array Indexed Variables Array elements are accessed through the index (i.e., the number in the square brackets). To access the number of elements in an array, use: arrayRefVariable.length Array indexes run from 0 to arrayRefVariable.length - 1 You access a given element of an array by putting its index in square brackets after the arrayRefVariable.

Example:System.out.println(Array element 0 is: + userPicks [0]);

Section 6.2.5: Array Initializers You can declare, create, and initialize an array in one step using an “array initializer”: You can not initialize the array using the curly brackets after it has been declared; you must do it all in one line.Declaring, creating, and initializing an array “long hand”

Declaring, creating, and initializing an array using an “array initializer”

double[] dataSet;dataSet = new double[5];dataSet[0] = 3.3;dataSet[1] = 4.4;dataSet[2] = 5.5;dataSet[3] = 6.6;dataSet[4] = 7.7;

double[] dataSet = {3.3, 4.4, 5.5, 6.6, 7.7};

Computer Science Notes Chapter 1 Page 71 of 83

Section 6.2.6: Processing ArraysArrays are best processed using for loops because:

All the elements are of the same type, so you can process them in a similar fashion using a loop. Since the size of the array is known, it is natural to use a for loop.

Simple Array Algorithms: Initializing an array with random values

//Declare an array called dataSet.//Then fill it with random numbers.double[] dataSet = new double[5];for (int i = 0; i < dataSet.length; i++)

dataSet[i] = Math.random() * 100;

Simple Array Algorithms: Printing arrays (you have to print each element separately)

//Print the dataSet array.System.out.println("Here are the elements of dataSet:");for (int i = 0; i < dataSet.length; i++)

System.out.println(dataSet[i]);System.out.println("Here is the address of the dataSet array: " + dataSet);Here are the elements of dataSet:51.777962552408589.28096751149770726.5544221314965818.46024916817967638.90932520992977Here is the address of the dataSet array: [D@addbf1

Simple Array Algorithms: Summing arrays

//Compute the sum of all elements in the dataSet array double sum = 0.0;for (int i = 0; i < dataSet.length; i++)

sum += dataSet[i];

Simple Array Algorithms: Finding the average of an array (sum the elements and divide by length)

//Compute the average of all elements in the dataSet array double average = 0.0;for (int i = 0; i < dataSet.length; i++)

average += dataSet[i];average /= dataSet.length;

Computer Science Notes Chapter 1 Page 72 of 83

Simple Array Algorithms: Finding the Maximum or Minimum Value stored in an array Initialize a candidate with the starting element Compare candidate with remaining elements

Update it if you find a larger or smaller value //Find the minimum value in the dataSet array.double min = dataSet[0];for (int i = 1; i < dataSet.length; i++)

if (dataSet[i] < min)min = dataSet[i];

//Find the maximum value in the dataSet array.double max = dataSet[0];for (int i = 1; i < dataSet.length; i++)

if (dataSet[i] > max)max = dataSet[i];

Simple Array Algorithms: Finding the index of the Maximum or Minimum Value stored in an array Initialize a candidate with the starting element array index Compare candidate with remaining elements

Update the array index if you find a larger or smaller value //Find the index of the minimum value in the dataSet array.int indexOfMin = 0;for (int i = 1; i < dataSet.length; i++)

if (dataSet[i] < dataSet[indexOfMin])indexOfMin = i;

//Find the index of the maximum value in the dataSet array.int indexOfMax = 0;for (int i = 1; i < dataSet.length; i++)

if (dataSet[i] > dataSet[indexOfMax])indexOfMax = i;

Simple Array Algorithms: Counting MatchesCheck all elements and count the matches until you reach the end of the array list.

//Count the number of elements in the dataSet array that have a given value.double givenValue = 5.5;int numGivenValue = 0;for (int i = 0; i < dataSet.length; i++)

if (dataSet[i] == givenValue)numGivenValue ++;

System.out.println(numGivenValue);

Computer Science Notes Chapter 1 Page 73 of 83

Simple Array Algorithms: Finding the index of a matching ValueCheck all elements until you have found a match.

//Find the index of the element in the dataSet array that matches a given value.double givenValue = 5.5;int indexOfGivenValue = -1;for (int i = 0; i < dataSet.length; i++)

if (dataSet[i] == givenValue)indexOfGivenValue = i;

System.out.println(indexOfGivenValue);

Section 6.2.7: for-each Loops JDK 5 introduced a new for loop called the for-each loop (AKA the enhanced for loop) (AKA the generalized for loop) that enables you to traverse all the elements in an array without using an index variable. Syntax of the enhanced for loop:

for (dataType variableName: arrayReferenceVariable){

//Process the value of the current array element stored in variableName.}

Comparison example:

A traditional for loop to sum all the values in the dataSet array:

An for-each loop to sum all the values in the dataSet array:

//Compute the sum of all elements in the //dataSet array.double sum = 0.0;for (int i = 0; i < dataSet.length; i++)

sum += dataSet[i];

//Compute the sum of all elements in the //dataSet array using a for-each loop.double sum = 0.0;for (double dataSetValue: dataSet)

sum += dataSetValue;

Section 6.2.8: Problem: Analyzing Array Elements

Section 6.2.9: Problem: Assigning Grades

Section 6.3: Copying Arrays If you want to copy an array, you can not use the assignment operator (i.e., the = sign). If you do use = to try to copy an array, all you do is copy the memory location reference from one variable to another. The result is two array variables that reference the same array in memory. To copy an array to a new block of memory, you have three alternatives:

1) Use a loop to copy every individual element one at a time.

2) Use the arraycopy method in the java.lang.System classarraycopy(sourceArray, srcPos, targetArray, tarPos, length)

3) Use the clone() method (see chapter 10, “Inheritance and Polymorphism”)

Computer Science Notes Chapter 1 Page 74 of 83

Section 6.4: Passing Arrays to MethodsYou can pass an array to a method in the same way that you pass any other parameter, but you have to beware that when passing the array variable name, the value of that reference is copied, which means that the method can change the values in the array.

Repeat: changing an array in a method will result in a permanent change in the array outside of the method.

import java.util.Scanner;/**The SwapTest class shows how a method makes permanent changes to an array passed to it. */public class SwapTest {

public static void main(String[] argv) {

//Declare and create an array that holds two values.int[] shortList = new int[2];//Declare a Scanner object to read data from the keyboard.Scanner keyboard = new Scanner(System.in);

//Tell the user what the program does.System.out.println("This program swaps two values in an array.\n");

System.out.println("Please enter an integer:"); shortList[0] = keyboard.nextInt();

System.out.println("Please enter another integer:"); shortList[1] = keyboard.nextInt();

System.out.println("\nHere is your original list:");System.out.println(shortList[0] + "\n" + shortList[1]);

System.out.println("\nHere is your swapped list:");swap(shortList);System.out.println(shortList[0] + "\n" + shortList[1]);

System.out.println("\nProgram SwapTest has terminated.");}//end main(String[])

/** Swaps the first two values in an array. * @param list is the array to be changed */public static void swap(int[] list){

int temp = list[0];list[0] = list[1];list[1] = temp;

}//end method swap(int[])

}//end class SwapTest

Computer Science Notes Chapter 1 Page 75 of 83

An anonymous array is an array “created on the fly” as it is passed to a method. This is legal to do, but since there is no explicit reference variable for the array, you can not reference it outside of the method call.

public class AnonymousArrayExample {

public static void main(String[] argv) {

//Compute the average of the values stored in an anonymous array.double average = computeAverage(new double[]{1.1, 2.2, 3.3});

System.out.println("The average of the array = " + average);System.out.println("However, this program can no longer tell you " +

"what the array elements are.");}//end main(String[])

public static double computeAverage(double[] list){

double sum = 0.0;for (int i = 0; i < list.length; i++)

sum += list[i];if (list.length > 0)

return sum / list.length;else

return -1;}//end method computeAverage(double[])

}//end class AnonymousArrayExample

Java uses pass-by-value when passing arguments to methods.o When passing a primitive data type to a method, the value of the argument is copied into the

stack for the method.o When passing an array to a method, the reference to the array is copied into the stack for the

method, but the entire array is not copied. This means that a change to the array in the method affects the values in the array outside the method (i.e., the values of the array stored in the “heap”). Semantically, this is called pass-by-sharing (or pass-by-reference).

Section 6.4.1: Passing Array Arguments

Computer Science Notes Chapter 1 Page 76 of 83

Section 6.5: Returning Arrays from MethodsYou can return an array from a method in the same way that you return any other data type…

/**The ReturnedArrayExample shows how a method can return an array. */public class ReturnedArrayExample {

public static void main(String[] argv) {

//Declare and create an integer array.int[] numberList = new int[5];

//populate the array with random integers.randomlyPopulateArray(numberList);

//Print the array.System.out.println("Here is the original array:");printArray(numberList);

//Create a new array that holds the reverse of numberList.int[] numberList2 = reverseArray(numberList);

//Print the reversed array.System.out.println("Here is the reversed array:");printArray(numberList2);

System.out.println("\nProgram ReturnedArrayExample has terminated.");}//end main(String)

/** * Populates an integer array with random integers. * @param list is the array to be populated */public static void randomlyPopulateArray(int[] list){

for (int i = 0; i < list.length; i++)list[i] = (int) (Math.random() * 10);

}//end method randomlyPopulateArray(int[])

/** * Prints all elements of an integer array on one line. * @param list is the array to be printed */public static void printArray(int[] list){

for (int i = 0; i < list.length; i++)System.out.printf("%3d", list[i]);

System.out.println();}//end method printArray(int[])

/** * Reverses all the elements in an array. * @param list is the array to be reversed * @return an integer array that has all elements reversed from list */public static int[] reverseArray(int[] list){

int[] result = new int[list.length];

Computer Science Notes Chapter 1 Page 77 of 83

for (int i = 0; i < list.length; i++)result[i] = list[list.length - i - 1];

return result;}//end method reverseArray(int[])

}//end class ReturnedArrayExample

Section 6.5.1: Case Study: Counting the Occurences of Each Letter

Section 6.6: Variable Length Argument Lists If you don’t know how many input parameters will be needed for a method, specify the type followed by an ellipsis: … This has the result of creating an “array on the fly” for an argument called a variable length argument list. This variable-length parameter must be the last in the parameter list (and there can be only one variable length parameter.) The variable length parameter is treated like an array by the method.

/**The VarLenArrayListExample shows an example of a method with a * variable-length argument list. */public class VarLenArrayListExample {

public static void main(String[] argv) {

//Print four arbitrary numbers and their average//using the method computeAverage, which uses a variable//length argument list.System.out.println("The average of the numbers " +

"1.1, 2.2, 3.3, and 4.4 is:");System.out.println(computeAverage(1.1, 2.2, 3.3, 4.4));

//Print five arbitrary numbers and their average//using the same computeAverage method.System.out.println("The average of the numbers " +

"1.1, 2.2, 3.3, 4.4, and 5.5 is:");System.out.println(computeAverage(1.1, 2.2, 3.3, 4.4, 5.5));

System.out.println("\nProgram VarLenArrayListExample has terminated.");}//end main(String[])

/** * Computes the average of a list of numbers. * @param list is the variable length argument list array to be averaged * @return the average of all the numbers in list */public static double computeAverage(double... list){

double sum = 0.0;for (int i = 0; i < list.length; i++)

sum += list[i];return sum / list.length;

}//end method computeAverage(double...)

}//end class VarLenArrayListExample

Computer Science Notes Chapter 1 Page 78 of 83

Section 6.7: Searching Arrays Searching is the process of looking for a specific key value that may or may not be stored as one of the elements in the array. Searching is a very common programming task. There are two common approaches to searching: the linear search approach and the binary search approach.

Section 6.7.1: The Linear Search Approach A linear search compares the key value sequentially to each element in the array until a match is found or no match is found anywhere in the array. If a match is found, the index of the matching element is returned. If no match is found, a value of -1 is returned (because no array has an index of -1). See www.cs.armstrong.edu/liang/intro7e/book/LinearSeacrch.java

Section 6.7.2: The Binary Search Approach A binary search begins with an array where the elements are already sorted into ascending order. The key value is then compared to the value in the middle of the array.

o If the key value is less than the middle value, then the match, if there is one, must be in the first half of the array.

o If the key value is greater than the middle value, then the match, if there is one, must be in the second half of the array.

o If the key value is equal to the middle value, then the search ends with a match. Subsequent steps involve comparing the key value to the middle of the subarray determined by the previous step. If a match is found, the index of the matching element is returned. If no match is found, a value of –(insertionPoint + 1) is returned, where insertionPoint is where the key value would be inserted into the sorted array. This method is very fast compared to the linear search approach, because each step cuts down the possibilities by a factor of two, while each step of the linear search approach only cuts down the possibilities by one case. That is, to search a 1024-element array, the binary approach would only require 11 steps at most, while the linear search could require 1024 steps at most. The trade-off: the list has to be sorted ahead of time for the binary search to work, which takes time… See www.cs.armstrong.edu/liang/intro7e/book/BinarySeacrch.java

Section 6.8: Sorting Arrays Sorting an array is a very, very common programming task. In fact, some people estimate that sorting occupies more CPU cycles worldwide than any other computing task.

Section 6.8.1: Selection Sort A selection sort repeatedly selects the largest number remaining in the unsorted portion of the list and swaps it with the last number in the unsorted portion of the list. See www.cs.armstrong.edu/liang/intro7e/book/SelectionSort.javaSection 6.8.2: Insertion Sort An insertion sort repeatedly inserts the next unsorted number into the proper place in the already sorted sublist. See www.cs.armstrong.edu/liang/intro7e/book/InsertionSort.java

Section 6.9: The Arrays Class

Computer Science Notes Chapter 1 Page 79 of 83

The java.util.Arrays class has several static methods for sorting and searching arrays. Key methods include: binarySearch - returns the array index of the element that matches a key value copyOF - returns a copy of the array sent to it equals - checks if two given arrays are equal (i.e., each element in the first array equals the corresponding element in the second array) fill - fills a all or part of a given array with a given value or values. sort - sorts all or part of a given array toString - returns a string value that is a listing of all the values stored in the array.

Section 6.10: Two-Dimensional Arrays A two-dimensional array is used to store a matrix or a table of values, like the color of each pixel on a monitor, a table of distances between pairs of cities, or a tic-tac-toe board.

Section 6.10.1: Declaring Variables of Two-Dimensional Arrays and creating Two-Dimensional Arrays Syntax for declaring a two-dimensional array:

dataType[][] arrayRefVar;//Exampleint[][] matrix;

To create a two-dimensional array, use the new keyword with the dimension of the rows and columns://Examplematrix = new int[4][3];

[0] [1] [2][0] 0 0 0[1] 0 0 0[2] 0 0 0[3] 0 0 0

To assign a value to an element, use an index pair://Examplematrix[2][1] = 7;

[0] [1] [2][0] 0 0 0[1] 0 0 0[2] 0 7 0[3] 0 0 0

Computer Science Notes Chapter 1 Page 80 of 83

To declare, create, and initialize a two-dimensional array, use nested sets of values in {}://Exampleint[][] matrix = {{1, 2, 3}, {3, 2, 1}, {0, 0, 0}, {8, 5, 9}};

[0] [1] [2][0] 1 2 3[1] 3 2 1[2] 0 0 0[3] 8 5 9

Section 6.10.2: Obtaining the Length of Two-Dimensional Arrays A two-dimensional array is actually a one-dimensional array of one-dimensional arrays…

//ExampleSystem.out.println(matrix.length); //Prints 4 because there are 4 rows

System.out.println(matrix[0].length); //Prints 3 because there are 3 columns in the first row

System.out.println(matrix[1].length); //Prints 3 because there are 3 columns in the second row

System.out.println(matrix[2].length); //Prints 3 because there are 3 columns in the third row

System.out.println(matrix[3].length); //Prints 3 because there are 3 columns in the fourth row

Section 6.10.3: Ragged Arrays A ragged array is a two-dimensional array in which each row has a different number of elements.

//Exampleint[][] triangleArray = {{1, 2, 3}, {3, 2}, {0}};

[0] [1] [2][0] 1 2 3[1] 3 2 N/A[2] 0 N/A N/A

//ExampleSystem.out.println(matrix.length); //Prints 3 because there are 3 rows

System.out.println(matrix[0].length); //Prints 3 because there are 3 columns in the first row

System.out.println(matrix[1].length); //Prints 2 because there are 2 columns in the second row

System.out.println(matrix[2].length); //Prints 1 because there is 1 column in the third row

Computer Science Notes Chapter 1 Page 81 of 83

Section 6.10.4: Processing Two-Dimensional Arrays Use nested loops

Two-Dimensional Array Algorithms: Initializing a two-dimensional array with random values

int[][] matrix = new int[10][10];//Initialize the array with random numbers.for (int row = 0; row < matrix.length; row++)

for (int col = 0; col < matrix[row].length; col++)matrix[row][col] = (int)(Math.random() * 10);

Two-Dimensional Array Algorithms: Printing a two-dimensional array (you have to print each element separately)

int[][] matrix = new int[10][10];//Print the array.System.out.println("Here are the elements of the array");for (int row = 0; row < matrix.length; row++){

for (int col = 0; col < matrix[row].length; col++)System.out.print(matrix[row][col] + " ");

System.out.println();}Here are the elements of the array5 6 7 7 8 3 2 7 7 2 7 0 9 6 0 7 3 9 2 9 6 9 2 4 2 8 2 7 0 0 4 1 8 0 9 7 4 9 5 2 3 4 2 6 8 6 1 3 7 2 4 8 6 8 5 2 9 2 5 1 2 5 9 1 9 6 3 0 4 7 1 3 9 4 0 7 1 8 9 2 3 2 2 8 1 2 0 8 8 7 1 3 2 3 6 8 8 3 6 7

Two-Dimensional Array Algorithms: Summing a two-dimensional array

int[][] matrix = new int[10][10];//Compute the sum of all elements in the array.double sum = 0.0;for (int row = 0; row < matrix.length; row++)

for (int col = 0; col < matrix[row].length; col++)sum += matrix[row][col];

System.out.println(sum);465.0

Computer Science Notes Chapter 1 Page 82 of 83

Two-Dimensional Array Algorithms: Summing rows of a two-dimensional array

int[][] matrix = new int[10][10];double sum = 0.0;//Compute the sum of all elements in each row of the array.for (int row = 0; row < matrix.length; row++){

sum = 0.0;for (int col = 0; col < matrix[row].length; col++)

sum += matrix[row][col];System.out.println("The sum for row " + row + " = " + sum);

}The sum for row 0 = 54.0The sum for row 1 = 52.0The sum for row 2 = 40.0The sum for row 3 = 49.0The sum for row 4 = 42.0The sum for row 5 = 50.0The sum for row 6 = 46.0The sum for row 7 = 44.0The sum for row 8 = 41.0The sum for row 9 = 47.0

Two-Dimensional Array Algorithms: Summing columns of a two-dimensional array int[][] matrix = new int[10][10];double sum = 0.0;//Compute the sum of all elements in each column of the array.for (int col = 0; col < matrix[0].length; col++){

sum = 0.0;for (int row = 0; row < matrix.length; row++)

sum += matrix[row][col];System.out.println("The sum for column " + col + " = " + sum);

}The sum for column 0 = 36.0The sum for column 1 = 41.0The sum for column 2 = 56.0The sum for column 3 = 47.0The sum for column 4 = 48.0The sum for column 5 = 56.0The sum for column 6 = 33.0The sum for column 7 = 56.0The sum for column 8 = 53.0The sum for column 9 = 39.0

Section 6.10.5: Problem: Grading a Multiple-Choice Test

Computer Science Notes Chapter 1 Page 83 of 83

Section 6.10.6: Problem: Finding a Closest PairSection 6.10.7: Problem: Sudoku

Section 6.11: MultiDimensional Arrays6.11.1: Problem: Computing Student Scores

Section 6.11.2: Problem: Guessing Birth Dates