Download Com Sci Test #1 Review - Madison Area Technical College

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Computer Science Test #1 Review
Page 1 of 45
Chapter 1: Introduction to Computers, Programs, and Java
Programming Skills in a Nutshell:
At the end of this chapter you should have the following programming skills:
1. Copy and paste source code into an IDE (Integrated Development Environment) like eclipse.
2. Recognize that the basic shell into which you’ll place your source code involves a class definition and a
main method.
3. To get text to appear in a console window using the println method.
4. To get text to appear in a Dialog Box using the showMessageDialog method (see last page of notes).
5. Here is a template using the key programming skills you should have at this point:
/**
* 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
Computer Science Test #1 Review
Page 2 of 45
1.3: Programs

Programs (software) are instructions to the computer.
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.
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.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).
1.8: A Simple Java Program

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 ClassName
2. public static void main(String[] args)
3. //lots of comments
4. A method call (in this example, to the println method)
5. Nested sets of curly brackets { } to denote a block of code.
Computer Science Test #1 Review
Page 3 of 45
Chapter 2: Elementary Programming
Programming Skills in a Nutshell:
At the end of this chapter you should have the following programming skills:
1. Declare numeric variables to store numbers and perform calculations with those numeric variables.
2. Declare string and character variables to store text.
3. To get information from the user of a program.
4. To program with proper style.
5. To understand the fundamental flow of any program:
a. Tell the user what the program does.
b. Get any needed information, either from the user or from another input source.
c. Perform any needed calculations.
d. Report results as output to the monitor or other output source.
6. To understand how to translate a programming problem into code:
e. Decide what the program is supposed to do (unless someone tells you first).
f. Decide what information you’ll need, where you’ll get it, and where you’ll store it.
g. Write out how you would do the task yourself.
h. Translate that task into code using the programming techniques you have at your disposal.
7. Here is a template using the key programming skills you should have at this point:
Computer Science Test #1 Review
Page 4 of 45
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 does
System.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
legs
double legA, legB;
//Declare a String object to store the uer's name,
//and initalize that String to store the name Clyde
String userName = "Clyde";
//Create a Scanner object for reading in the user's input
Scanner keyboard = new Scanner(System.in);
//Prompt the user for his/her name, and store in userName
System.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 Test #1 Review
Page 5 of 45
// ********************************************************************
// 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 area
System.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
This program will calculate the hypotenuse, perimeter, and area of a right triangle given
the lengths of its legs.
Please enter your name:
Kevin
Please enter the length of the first leg of the right triangle:
3
Please enter the length of the second leg of the right triangle:
4
Okay, Kevin, the hypotenuse of your right triangle is: 5.0
The perimeter of your right triangle is: 12.0
The area of your right triangle is: 6.0
I hope you enjoyed your results.
Computer Science Test #1 Review
Page 6 of 45
Section 2.1: Introduction
This chapter will teach you how to use primitive data types, perform input and output, and execute simple
calculations.
Section 2.2: Writing Simple Programs
When you write a program:
1. Decide what information you’ll need and how you’ll store it (i.e., the data structures), and where you’ll
get the data (from disk or the user)
2. Write out how you would perform the computation yourself; i.e., outline your algorithm. An algorithm
is a statement of how to solve a problem in terms of the steps to execute, and the order of those steps.
3. Decide what kind of information you want your program to show when it is done computing and the
format of that information
4. Translate that task into code using the programming techniques you have at your disposal.
Variable: a piece of memory with a name used for storing data and computational results.

Choose descriptive names for variables. 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.

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: Identifiers
An 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 Test #1 Review
Page 7 of 45
Section 2.4: Variables
Variables are used to store data in a program. They can be reassigned new values as many times as you want.
Section 2.4.1: Declaring Variables
A 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;
Section 2.5: Assignment Statements and the Assignment Operator
An 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
System.out.println( x = 1);
i = j = k = 2;
Is equivalent to:
x = 1;
System.out.println(x);
k = 2;
j = k;
i = j;
Computer Science Test #1 Review
Page 8 of 45
Section 2.5: Declaring and Initializing Variables in One Step
The statement
int j = 5;
Is equaivalent to:
int j;
j = 5;
int j, k;
j = 5;
k = 7;
int j = 5, k = 7;
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.
Example: Declare a constant to store the value of pi.
final double PI = 3.1415927;

Note: you can access the value of pi to 15 digits using the constant for pi stored in the math class:
Math.PI
Section 2.7: Numeric Data Types and Operations
-- See table on page 7…
We’ll mostly use int and double this semester for numeric variables.
Section 2.7.1: Numeric Operators
Operator
+
Meaning
Addition
*
/
Subtraction
Multiplication
Division
%
Note: integer division
only keeps the quotient
and discards the
remainder
Remainder
(integers only)
Example
34 + 1
29.5 + 2.7E2
-88.2 + 5
34 – 0.1
300 * 30
1.0 / 2.0
24 / 2
1/2
Result
35
299.5
-83.2
33.9
9000
0.5
12
0
20 % 3
2
Example from the book, page34:
(Note: you can download all the source code in the book from
http://www.cs.armstrong.edu/liang/intro7e/DisplayTime.html)
public class DisplayTime {
public static void main(String[] args) {
int seconds = 500;
Computer Science Test #1 Review
Page 9 of 45
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 Literals
A literal is a constant value that appears in a program.
Section 2.7.3: Evaluating Java Expressions
Java follows standard mathematical order of operations
Section 2.7.4: Shorthand Operators
… can be used when the variable in the expression is stores the resulting answer…
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 0
System.out.println((float)i / (float)j);
//output is 0.333333333
Section 2.9: Character Data Type and Operations
The 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));
}
}
Section 2.9.1: Unicode and ASCII code

Character encoding is the process of converting a character to its binary representation.

How characters are encoded is called an encoding scheme.

ASCII is a 7-bit encoding scheme that was meant to display English uppercase and lowercase letters,
digits, and punctuation marks. There are 128 ASCII characters.

See http://www.asciitable.com/
Computer Science Test #1 Review
Page 10 of 45

Unicode is the encoding scheme used by Java, and Unicode was meant to display all written characters
in all the languages of the world using16 bits (2 bytes), which corresponds to 65,536 characters. This, however,
was not enough choices for all the characters in the world…
Section 2.9.2: Escape Sequences for Special Characters
Escape sequences are designed to display special characters in string literals.
Escape sequences are preceded by a backslash
\b
backspace
\t
tab
\n
linefeed
\f
formfeed
\r
carriage return
\\
backslash
\’
single quote
\”
double quote
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));
}
}
Computer Science Test #1 Review
Page 11 of 45
Section 2.11: Console Input Using the Scanner Class
Recall that Java uses System.out (i.e., a data field named out in the System class) to refer to the "standard"
output stream or device, which is a console displayed on the monitor. To perform console output, we saw that
we can use the println method with System.out (officially, println is a method of the PrintStream class, since
out is an object of type PrintStream).
Just as Java has a standard output device, it also has a standard input device. Java uses System.in (i.e., a data
field named in of the System class) to refer to the "standard" input stream or device, which is the keyboard. To
get access to the data flowing into the computer from the keyboard, we can use the Scanner class, which has
several methods for reading different types of input from the keyboard.
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.
Method
nextByte()
nextShort()
nextInt()
nextLong()
nextFloat()
nextDouble()
next()
nextLine()
Methods for Scanner objects
Description
Reads an integer of the byte type
Reads an integer of the short type
Reads an integer of the int type
Reads an integer of the long type
Reads a number of the float type
Reads a number of the double type
Reads a string that ends before a whitespace
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 Test #1 Review
Page 12 of 45
Section 2.12: Case Studies

See www.cs.armstrong.edu/liang/intro7e/book/ComputeLoan.java

See www.cs.armstrong.edu/liang/intro7e/book/ComputeChange.java

See www.cs.armstrong.edu/liang/intro7e/book/ShowCurrentTime.java
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.
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, { }.
Section 2.14: Programming Errors
Section 2.14.1: Syntax Errors
A syntax error is an error that occurs during program compilation.
Syntax errors result from errors in code construction, like mistyping a keyword, omitting necessary punctuation,
not declaring a variable before it is used, or having unmatched pairs of braces or parentheses.
Section 2.14.2: Runtime Errors
A runtime error is an error that occurs during program execution.
Runtime errors result when the program is supposed to perform an operation that is impossible to carry out, like
divide by zero, open a disk file that does not exist, or store a letter in a floating-point data type.
Section 2.14.3: Logic Errors
A logic error is an error that occurs because the code you wrote is not logically consistent with what you wanted
the program to do.
Logic errors can result when you type the wrong variable name, or do any one of ten million other bone-headed
things.
Computer Science Test #1 Review
Section 2.15: Debugging
Section 2.16: (GUI) Getting Input from Dialog Boxes
Section 2.16.1: Converting Strings to Numbers
Page 13 of 45
Computer Science Test #1 Review
Page 14 of 45
Chapter 3: Selections
Programming Skills in a Nutshell:
At the end of this chapter you should have the following programming skills:
1. Translate logical conditions into Boolean expressions.
2. Use simple if … else statements to control program flow.
3. Use nested if statements for multiple outcomes and conditions.
4. Use a switch statement for multiple outcomes and conditions that are based on a positive integer.
Section 3.1: Introduction
This chapter will teach you how to use if and switch statements, which are used to determine which lines of
code a program executes based on certain conditions like user input or the values stored in variables.
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.

The boolean data type contains one of two values: true or false.

Boolean variables hold Boolean variables.
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
More Boolean notes:

To test if a variable is within a range of numbers:
WRONG WAY TO TEST A NUMERICAL CORRECT WAY TO TEST A NUMERICAL RANGE
RANGE
int numberOfDaysInAMonth = 32;
if (1 <= numberOfDaysInAMonth <= 31)
...

int numberOfDaysInAMonth = 32;
if (1 <= numberOfDaysInAMonth &&
numberOfDaysInAMonth <= 31)
...
A Boolean data type can not be cast into other data types.
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
Computer Science Test #1 Review
Page 15 of 45
Section 3.3: if Statements
An if statement is used to force a program to execute certain lines of code based on the truth of a given
condition.
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;


When the condition is false, the program executes nextStatement right away, thus skipping
conditionTrueStatement(s),
but when the condition is true, the program executes conditionTrueStatement(s) first, and then
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 radius
System.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 Test #1 Review
Page 16 of 45
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;


When the condition is true, the program executes conditionTrueStatement(s) first, and then
nextStatement.
When the condition is false, the program executes conditionFalseStatement right away, and then
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 radius
System.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 Test #1 Review
Page 17 of 45
Section 3.3.3: Nested if Statements
Nested if statements are used when you want your program to execute one of many different statements based
on one of several different values.
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 Test #1 Review
Page 18 of 45
Section 3.3.4: Problem: An Improved Math Learning Tool

See www.cs.armstrong.edu/liang/intro7e/book/SubtractionQuiz.java

Notice the use of the Math.random() method.
Section 3.3.5: Problem: Lottery

See www.cs.armstrong.edu/liang/intro7e/book/Lottery.java
Section 3.3.6: Problem: Computing Body Mass Index

See www.cs.armstrong.edu/liang/intro7e/book/ComputeBMI.java
Section 3.3.7: Problem: Computing Taxes

See www.cs.armstrong.edu/liang/intro7e/book/ComputeTax.java

Notice the use of the System.exit(0) method.

This is a good example of using incremental development and testing.
Section 3.3.8: Problem: Guessing Birth Dates

See www.cs.armstrong.edu/liang/intro7e/book/ComputeTax.java
Section 3.4: switch Statements
switch statements are used when you want to force the program to execute one of many different statements
based on the integer values of a single integer expression.
Syntax of a simple if 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;




If the integerExpression evaluates to the number value1, the program executes statement(s)1, and
then skips to nextStatement when the break statement is encountered. If the break statement were
omitted by accident, the program would execute statement(s)2 next.
The same pattern follows for other values of integerExpression.
If integerExpression doesn’t evaluate to any of the values, then the statement(s)Default get executed.
Notice that parentheses for block statements are not needed after each case…
Computer Science Test #1 Review
Page 19 of 45
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 1
int 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.
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 2
if (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)
Computer Science Test #1 Review
Page 20 of 45
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);
}
}
Section 3.5: Conditional Expressions
 A shorthand way to assign one of two values to a variable based on a condition
 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 number
System.out.println("Enter a number:");
double x = keyboard.nextDouble();
double abs_x;
if (x < 0.0)
abs_x = -x;
else
abs_x = x;
Computer Science Test #1 Review
Page 21 of 45
System.out.println("|" + x + "| = " + abs_x);
}
}
Section 3.6: Formatting Console Output
Section 3.7: Operator Precedence and Associativity
Section 3.8: (GUI) Confirmation Dialogs

See www.cs.armstrong.edu/liang/intro7e/book/GuessBirthDateUsingConfirmationDialog.java
Computer Science Test #1 Review
Page 22 of 45
Chapter 4: Loops
Programming Skills in a Nutshell:
At the end of this chapter you should have the following programming skills:
8. Use a while loop to repeat a block of code.
9. Use a do-while loop to repeat a block of code.
10. Use a for loop to repeat a block of code.
11. Be able to translate from one type of loop to the other.
12. Know the advantages of one type of loop over the other
Section 4.1: Introduction
A loop is a structure that allows you to repeat a block of statements as many times as is desired or needed (or
more, if your program has an infinite loop).
Example: Print Welcome to Java! 100 times
Without loops
Using loops
// Print “Welcome to Java!” 100 times
System.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!”);
// Print “Welcome to Java!” 100 times
for (int count = 1; count <= 100; count++)
System.out.println("Welcome to Java!”);
//… 94 more println statements…
System.out.println("Welcome to Java!”);
Section 4.2: The while Loop
A while loop checks to see if a condition is true, executes a block of code if the condition is true, and then keeps
checking the condition and executing the block of code as long as the condition is true.
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 Test #1 Review
Page 23 of 45
}
}
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 radius
System.out.println("Enter the radius of a circle:");
double radius = keyboard.nextDouble();
// a loop that validates an input for a radius
while (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) + ".");
}
}
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 input
Scanner keyboard = new Scanner(System.in);
int compareAgain = 1;
while (compareAgain == 1)
{
Computer Science Test #1 Review
Page 24 of 45
//get the user's data
System.out.println("\nPlease enter a number:");
num1 = keyboard.nextDouble();
System.out.println("Please enter a second number:");
num2 = keyboard.nextDouble();
//Compare the numbers
System.out.println("Here is the
if (num1 < num2)
System.out.println(num1 +
else if (num1 > num2)
System.out.println(num1 +
else
System.out.println(num1 +
comparison:");
" < " + num2);
" > " + num2);
" = " + num2);
System.out.println("Enter 1 to continue or 0 to quit:");
compareAgain = keyboard.nextInt();
}
System.out.println("\nProgram Terminated.");
}
}
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.");
}
}
Section 4.2.1: Problem: Guessing Numbers

See www.cs.armstrong.edu/liang/intro7e/book/GuessNumberOneTime.java

See www.cs.armstrong.edu/liang/intro7e/book/GuessNumber.java
Section 4.2.2: Problem: An Advanced Math Learning Tool

See www.cs.armstrong.edu/liang/intro7e/book/SubtractionQuizLoop.java
Computer Science Test #1 Review
Page 25 of 45
Section 4.2.3: Controlling a Loop with a Sentinel Value
If you want the user of a program to decide when to end a loop, then another trick you can use is to give the user
a special input value to enter that does not make sense in terms of the other data being entered. When this
special input value is encountered, then the loop ends. This special input value is called a sentinel value.
Example: 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 input
Scanner keyboard = new Scanner(System.in);
while (dataEntry >= 0.0)
{
//get the user's data
System.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()
}
Section 4.3: The do-while Loop
A do-while loop executes the body of the loop before checking the condition. This can result in slightly more
efficient code when you know you want the loop to execute at least once.
Notice the semicolon after the while clause.
Syntax of a do-while statement:
do
{
Statement(s);
} while (condition);
Computer Science Test #1 Review
Page 26 of 45
nextStatement;


When the condition is true, the program goes back to the do and executes the Statement(s).
When the condition is false, the program executes nextStatement.
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!");
}
}
Section 4.4: for Loops
Loops that depend on the value of an incremented counter for the condition are so common that a new looping
structure called the for loop was created that makes this type loop more efficient:
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;





The initial_action is atatement that is usually used to declare and initialize a control variable for the
loop
As long as the loop_continuation_condition is true, the program executes the Statement(s).
When the loop_continuation_condition is false, the program executes nextStatement.
The action_after_each_iteration is a statement that executes after the last statement in the body of the
loop; it is usually used to adjust the control variable (usually by incrementing it or decrementing it).
Control variables declared inside the header of a loop can not be accessed by statements outside the
loop.
Computer Science Test #1 Review
Page 27 of 45
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 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.
Section 4.6: Nested Loops
A nested loop is a loop within another loop. Each time the outer loop iterates, the entire inner loop gets
executed. Nested loops are used when you have to process data that depends on two “dimensions”. One
common application is processing graphics, and another is processing any “two-dimensional” type of
information.
Example: Print a triangular shape as follows:
X
XX
XXX
XXXX
XXXXX
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();
}
Computer Science Test #1 Review
Page 28 of 45
}
}

See www.cs.armstrong.edu/liang/intro7e/book/MultiplicationTable.java
Section 4.7: Minimizing Numerical Errors
Section 4.8: Case Studies
Section 4.8.1: Problem: Finding the Greatest Common Divisor

See www.cs.armstrong.edu/liang/intro7e/book/GreatestCommonDivisor.java
Section 4.8.2: Problem: Finding the Sales Amount

See www.cs.armstrong.edu/liang/intro7e/book/FindSalesAmount.java
Section 4.8.3: Problem: Displaying a Pyramid of Numbers

See www.cs.armstrong.edu/liang/intro7e/book/PrintPyramid.java
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.

See www.cs.armstrong.edu/liang/intro7e/book/TestBreak.java

See www.cs.armstrong.edu/liang/intro7e/book/TestContinue.java

See www.cs.armstrong.edu/liang/intro7e/book/GuessNumberUsingBreak.java
Section 4.9.1: Problem: Displaying Prime Numbers

See www.cs.armstrong.edu/liang/intro7e/book/PrimeNumber.java
Section 4.10: Controlling a Loop with a Confirmation Dialog
Computer Science Test #1 Review
Page 29 of 45
Chapter 5: Methods
Programming Skills in a Nutshell:
At the end of this chapter you should have the following programming skills:
1. To recognize when a block of code should be placed in a method.
2. To write the method with correct input parameters and return type.
3. To understand how and when to overload methods.
Section 5.1: Introduction
A method is a block of code with a name that is designed to perform a specific function. The block of
code gets executed by calling the method, which means to type the name of the method as one of your
statements. Methods make coding more efficient because you don’t need to repeat blocks of code every time
you need them, because the name of the method is usually a good indication of what its functionality is, and
because their use makes reading a program easier.
Section 5.2: Creating a Method
The general syntax to create a method is:
modifier(s) return_value_type method_name (list_of_parameters)
{
statements;
}
The modifiers we will use in this chapter will always be public static
The return_value_type we will use in this chapter are int, double, float, String, char, or void.
method_name should always start with a lowercase letter.
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:
1.
2.
3.
4.
/** Verb phrase telling what the method does.
* @param parameter_name and what it stores.
* @param parameter_name and what it stores (do this for each parameter in the list).
* @return what the method returns as a result of its calculation.
*/
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
printPascalTriangle(n);

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
chaoter 6 on Arrays).

A return statement is required in any method that returns a value.
Computer Science Test #1 Review

Page 30 of 45
Methods allow for code sharing and reuse. USE THEM!
Section 5.3.1: Call Stacks
Section 5.4: void Method Example

See www.cs.armstrong.edu/liang/intro7e/book/TestVoidMethod.java

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

See www.cs.armstrong.edu/liang/intro7e/book/GreatestCommonDivisorMethod.java

See www.cs.armstrong.edu/liang/intro7e/book/PrimeNumberMethod.java
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.

See www.cs.armstrong.edu/liang/intro7e/book/TestMethodOverloading.java

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.
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…
Computer Science Test #1 Review
Page 31 of 45
Section 5.9: The Math Class
You can see all the math methods at http://java.sun.com/javase/6/docs/api/java/lang/Math.html
Section 5.9.1: Trigonometric Methods
You can see all the math methods at http://java.sun.com/javase/6/docs/api/java/lang/Math.html
Section 5.9.2: Exponent Methods
You can see all the math methods at http://java.sun.com/javase/6/docs/api/java/lang/Math.html
Section 5.9.3: The Rounding Methods
You can see all the math methods at http://java.sun.com/javase/6/docs/api/java/lang/Math.html
Section 5.9.4: The min, max, and abs Methods
You can see all the math methods at http://java.sun.com/javase/6/docs/api/java/lang/Math.html
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

See www.cs.armstrong.edu/liang/intro7e/book/RandomCharacter.java
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

See www.cs.armstrong.edu/liang/intro7e/book/PrintCalendar.java
Section 5.11.3: Implementation Details

See www.cs.armstrong.edu/liang/intro7e/book/PrintCalendar.java
Computer Science Test #1 Review
Page 32 of 45
Chapter 6: Arrays
Programming Skills in a Nutshell:
At the end of this chapter you should have the following programming skills:
13. To recognize when a block of information could best be stored as an array.
14. To manipulate the array correctly or perform calculations using the array using loops.
15. Here is a template that uses the key programming skills you should have at this point:
import java.util.Scanner;
/**The Chap06BasicsStatistics class implements an application that
* performs various statistical calculations on an array of
* double-precision numbers, and is meant to illustrate the basics of using arrays.
* This is meant as an example of the material in Chapter 7 of the text
* _Introduction to Java Programming: Brief Version_, 7th ed. by Y. D. Liang
* @author Kevin Mirus
*/
public class Chap06BasicsStatistics
{
/**Allows the user to enter an array of double precision numbers, and perform
* statistical calculations on that data set.
* @param argv is not used.
*/
public static void main(String[] argv)
{
//Declare an array to hold all the data.
double[] dataSet;
//Declare an integer which will store the number of values in the array.
int numUserElements;
//Declare an integer to control whether the program keeps looping.
int continueSentinel;
//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 calculates statistics for a data set\n");
//Loop for the entire program.
do
{
//Get the number of elements in the array.
System.out.println("Please enter how many elements you would like " +
"in your data set.");
numUserElements = keyboard.nextInt();
//Create the array with numUserElements elements.
dataSet = new double[numUserElements];
//Read data from the keyboard into every array element.
for (int i = 0; i < numUserElements; i++)
{
System.out.println("Enter datum #[" + i + "]");
dataSet[i] = keyboard.nextDouble();
}
//Echo the data back to the user
System.out.println("\nHere is your data set:");
for (int i = 0; i < numUserElements; i++)
Computer Science Test #1 Review
Page 33 of 45
{
System.out.println("Array element[" + i + "] = " + dataSet[i]);
}
//Find and print the minimum data value.
double min = dataSet[0];
for (int i = 1; i < numUserElements; i++)
{
if (dataSet[i] < min)
min = dataSet[i];
}
System.out.println("The minimum of your data is: " + min);
//Find and print the maximum data value.
double max = dataSet[0];
for (int i = 1; i < dataSet.length; i++)
{
if (dataSet[i] > max)
max = dataSet[i];
}
System.out.println("The maximum of your data is: " + max);
//Compute and print the average of the data.
double sum = 0.0;
for (int i = 0; i < dataSet.length; i++)
{
sum += dataSet[i];
}
double average = 0.0;
if (dataSet.length > 0)
{
average = sum / dataSet.length;
System.out.println("The average of your data is: " + average);
}
else
System.out.println("There is no data in your data set " +
"for computing an average.");
//Compute and print the standard deviation of the data.
sum = 0.0;
double standardDeviation;
if (dataSet.length > 1)
{
for (int i = 0; i < dataSet.length; i++)
sum += Math.pow(dataSet[i] - average, 2);
standardDeviation = Math.sqrt(sum / (dataSet.length - 1));
System.out.println("The standard deviation of your data is: " +
standardDeviation);
}
else
System.out.println("There is not enough data in your data set " +
"for computing a standard deviation.");
System.out.println("Enter 1 to analyze a new data set or 0 to quit.");
continueSentinel = keyboard.nextInt();
}while (continueSentinel == 1);
System.out.println("Program Chap06BasicsStatistics has terminated.");
}//end main(String)
Computer Science Test #1 Review
Page 34 of 45
}//end class Chap06BasicsStatistics
Section 6.1: Introduction
An array is a fixed-size sequence of elements (or values) of the same type.
Section 6.2: Array Basics
Section 6.2.1: Declaring Array Variables
Syntax to declare an array variable:
dataType[] variableName
Example:
double[ ] dataSet;
Section 6.2.2: Creating Arrays

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:
variableName = new dataType[arraySize];
Example:
dataSet = new double[ numUserElements];

Declaring and creating arrays can be combined into one statement:
Example: a
double[ ] dataset = new double[ numUserElements];

To store values in the array elements, use this syntax:
Syntax to assign a value to an element of an array:
variableName [index] = value;
Example:
dataset[0] = 2.5;
dataset[1] = 3.7;
Section 6.2.3: Array Size and Default Values
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).

Array indexes run from 0 to arraySize – 1.

You access a given element of an array by putting its index in square brackets after the variableName.
Section 6.2.5: Array Initializers

You can declare, create, and initialize an array in one step using an “array initializer”:
Declaring, creating, and initializing an array Declaring, creating, and initializing an array using an
“long hand”
“array initializer”
double[] dataSet;
double[] dataSet = {3.3, 4.4, 5.5, 6.6, 7.7};
Computer Science Test #1 Review
Page 35 of 45
dataSet = new double[5];
dataSet[0] = 3.3;
dataSet[1] = 4.4;
dataSet[2] = 5.5;
dataSet[3] = 6.6;
dataSet[4] = 7.7;
Section 6.2.6: Processing Arrays
Arrays 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
//Initialize the dataSet array with random numbers.
for (int i = 0; i < dataSet.length; i++)
dataSet[i] = Math.random() * 100;
Computer Science Test #1 Review
Page 36 of 45
Simple Array Algorithms: Printing arrays (you have to print each element separately)
//Print the dataSet array.
System.out.println("Here are the elements of the array");
for (int i = 0; i < dataSet.length; i++)
System.out.println(dataSet[i]);
System.out.println("Here is the address of the array: " + dataSet);
Here are the elements of the array
17.72099469520989
14.723838408786694
50.55653542589798
65.32803034718614
89.89020744652521
Here is the address of the 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 sum = 0.0;
for (int i = 0; i < dataSet.length; i++)
sum += dataSet[i];
double average = sum / dataSet.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 Test #1 Review
Page 37 of 45
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];
Computer Science Test #1 Review
Page 38 of 45
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 Matches
Check 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 Test #1 Review
Page 39 of 45
Simple Array Algorithms: Finding the index of a matching Value
Check 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
Section 6.2.8: Problem: Analyzing Array Elements

See www.cs.armstrong.edu/liang/intro7e/book/TestArray.java
Section 6.2.9: Problem: Assigning Grades

See www.cs.armstrong.edu/liang/intro7e/book/AssignGrade.java
Section 6.3: Copying Arrays
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 class
arraycopy(sourceArray, srcPos, targetArray, tarPos, length)
3) Use the clone method (see chapter 10, “Inheritance and Polymorphism”)
Section 6.4: Passing Arrays to Methods
You 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");
Computer Science Test #1 Review
Page 40 of 45
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
Section 6.4.1: Passing Array Arguments

See www.cs.armstrong.edu/liang/intro7e/book/TestPassArray.java
Section 6.5: Returning Arrays from Methods
You 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);
Computer Science Test #1 Review
Page 41 of 45
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];
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

See www.cs.armstrong.edu/liang/intro7e/book/CountLettersInArray.java
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: …
/**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.
Computer Science Test #1 Review
Page 42 of 45
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
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.
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.

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.

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.java
Section 6.8.2: Insertion Sort
Computer Science Test #1 Review
Page 43 of 45

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
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;
//Example
int[][] matrix;

To create a two-dimensional array, use the new keyword with the dimension of the rows and columns:
//Example
matrix = new int[3][2];
[0]
[1]
[2]
[3]

[0]
0
0
0
0
[1]
0
0
0
0
[2]
0
0
0
0
To assign a value to an element, use an index pair:
//Example
matrix[2][1] = 7;
[0]
[1]
[2]
[3]
[0]
0
0
0
0
[1]
0
0
7
0
[2]
0
0
0
0
Computer Science Test #1 Review

Page 44 of 45
To declare, create, and initialize a two-dimensional array, use nested sets of values in {}:
//Example
int[][] matrix = {{1, 2, 3}, {3, 2, 1}, {0, 0, 0}, {8, 5, 9}};
[0]
[1]
[2]
[3]
[0]
1
3
0
8
[1]
2
2
0
5
[2]
3
1
0
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…
//Example
System.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)
Section 6.10.3: Ragged Arrays
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();
}
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++)
Computer Science Test #1 Review
Page 45 of 45
sum += matrix[row][col];
System.out.println(sum);
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);
}
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);
}
Section 6.10.5: Problem: Grading a Multiple-Choice Test

See www.cs.armstrong.edu/liang/intro7e/book/GradeExam.java
Section 6.10.6: Problem: Finding a Closest Pair

See www.cs.armstrong.edu/liang/intro7e/book/FindNearestPoints.java
Section 6.10.7: Problem: Sudoku

See www.cs.armstrong.edu/liang/intro7e/book/Sudoku.java
Section 6.11: MultiDimensional Arrays

A multidimensional array is an array of arrays of one lower dimension.
Section 6.11.1: Problem: Computing Student Scores

See www.cs.armstrong.edu/liang/intro7e/book/TotalScore.java
Section 6.11.2: Problem: Guessing Birth Dates

See www.cs.armstrong.edu/liang/intro7e/book/GuessBirthDateUsingArray.java