csis 2301 - programming principles iksuweb.kennesaw.edu/~jhiggins/cs1301-13/reviewnotes…  · web...

28
CS 1301 - Programming Principles I Final Exam Review Notes Java General Concepts: There are four programming language levels: Machine Language, Assembly Language, High-Level Language, and Fourth-Generation Language Java is a High-Level Language Compiled vs. Interpreted - Java is a mixture of both compiled and interpreted, Java compiles to Bytecodes which are Architecture Neutral (Machine Independent) Comments – 3 types: // /* */ /** A Javadoc Comment */ Javadoc comments can be used by the Javadoc utility to create HTML documentation that provides details on the program’s API (Application Programmer’s Interface) without requiring someone to view the code. The Java Reserved Words: Identifiers: Identifiers are names for things like classes, Page 1 of 28

Upload: others

Post on 09-May-2020

6 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CSIS 2301 - Programming Principles Iksuweb.kennesaw.edu/~jhiggins/cs1301-13/ReviewNotes…  · Web viewThe Java Reserved Words: Identifiers: Identifiers are names for things like

CS 1301 - Programming Principles IFinal Exam Review Notes

Java General Concepts:There are four programming language levels: Machine Language,

Assembly Language, High-Level Language, and Fourth-Generation Language

Java is a High-Level Language

Compiled vs. Interpreted- Java is a mixture of both compiled and interpreted, Java compiles to

Bytecodes which are Architecture Neutral (Machine Independent)

Comments – 3 types:///* *//** A Javadoc Comment */

Javadoc comments can be used by the Javadoc utility to create HTML documentation that provides details on the program’s API (Application Programmer’s Interface) without requiring someone to view the code.

The Java Reserved Words:

Identifiers: Identifiers are names for things like classes, methods and variables. The Rules for naming identifiers:

Names can be alphanumeric (alphabetical characters ordigits) and they can include _ (the underscore) and $ (thedollar sign), but they must not start with digit, and theymust not be a reserved word.

Names in Java is Case Sensitive!

Page 1 of 21

Page 2: CSIS 2301 - Programming Principles Iksuweb.kennesaw.edu/~jhiggins/cs1301-13/ReviewNotes…  · Web viewThe Java Reserved Words: Identifiers: Identifiers are names for things like

Types of Errors:Syntax Errors (Compile-Time Errors)Run-Time ErrorsLogical Errors

Java Object Oriented Concepts:● A Program is made up of one or more Classes● Classes contain one or more Methods● Methods contain Program Statements

Class Header / Class BodyMethod Header / Method Body

Programs are made up of:Program Data - variables, constants (final variables), literalsProgram Statements

Classes become objects that can interact with other objects when instantiated with the new command in a program

Algorithms:● A General Solution● A Logical Sequence of Steps

Program Data – Numbers, Characters:Variables - a named memory location with a data type

-Variable declaration ([Data Type] [Variable Name(s)])-Variable initialization ([Data Type] [Variable Name(s)] [= Optional Value(s)])-Variable assignment ([Variable Name] = Value)

Constant (also called final variables) -Must be declared and initialized, but cannot be changed after that -Capitalized by convention

Page 2 of 21

Page 3: CSIS 2301 - Programming Principles Iksuweb.kennesaw.edu/~jhiggins/cs1301-13/ReviewNotes…  · Web viewThe Java Reserved Words: Identifiers: Identifiers are names for things like

Primitive Data Types: Integer Types:

bytes (8 bits)short (16 bits)int (32 bits)long (64 bits)

Floating Point (Real) Types:float (32 bits/7 significant digits)double (64 bits/15 significant digits)

Character Type:char

Boolean Type:boolean

Strings are not Primitives, they are Objects:Strings are made up of zero or more characters in double quotesWhen you want to concatenation two Strings or a String with a primitive

data type, you use the plus sign +

Program Statements:Program Statements are made up of Expressions:- An expression is a combination of one or more operators and

operands

Arithmetic Operators: + (binary and unary) - (binary and unary) * (binary) / (binary) % (binary) - Remainder

Operator Precedence:Level 1: Unary +, Unary - [R to L]Level 2: * , /, % [L to R]Level 3: +, - [L to R]Level 4: = [R to L]

Increment / Decrement Operators (unary):++, - - (postfix and prefix form)

Combined Assignment Operators: +=, -=, /=, *=, %=

Scanner Class: -Use it by instantiating an object using "new"

Page 3 of 21

Page 4: CSIS 2301 - Programming Principles Iksuweb.kennesaw.edu/~jhiggins/cs1301-13/ReviewNotes…  · Web viewThe Java Reserved Words: Identifiers: Identifiers are names for things like

Scanner scan = new Scanner (System.in); -Methods:

String next() => returns next string/token String nextLine() => returns next lineboolean nextBoolean() => returns next boolean valuebyte nextByte() => returns next bytedouble nextDouble() => returns next doublefloat nextFloat() => returns next floatint nextInt() => returns next intlong nextLong() => returns next longshort nextShort() => returns next shortboolean hasNext() => return true if more on line

otherwise returns false

Libraries and Packages are included uses the "import" command.

A package is a collection of libraries in a particular path (in a directory)

Ex. of a Library: import java.util.Scanner;Ex. of a Package: import java.util.*;

Conditional Expressions / If Statements / Conditional Operators

Types of Conditional Statements:if statementif-else statement

Equality Operators (aka Relational Operators):== equal to!= not equal to< less than> greater than<= less than or equal to>= greater than or equal to

NOTE: Be careful to note the difference between the equality operator (==) and the assignment operator (=).

Logical Operators:! Logical NOT&& Logical AND

Page 4 of 21

Page 5: CSIS 2301 - Programming Principles Iksuweb.kennesaw.edu/~jhiggins/cs1301-13/ReviewNotes…  · Web viewThe Java Reserved Words: Identifiers: Identifiers are names for things like

|| Logical OR^ Logical Exclusive OR

Logical NOT Tablea !atrue falsefalse true

Logical AND and OR Tablea b a && b a || btrue true true truetrue false false truefalse true false truefalse false false false

Logical Exclusive OR Tablea b a ^ btrue true falsetrue false truefalse true truefalse false false

Page 5 of 21

Page 6: CSIS 2301 - Programming Principles Iksuweb.kennesaw.edu/~jhiggins/cs1301-13/ReviewNotes…  · Web viewThe Java Reserved Words: Identifiers: Identifiers are names for things like

Order of Precedence for Operators from Highest to Lowest : 1. The Unary Operators: + (positive sign), - (negative sign), ! (logical not), ++ (increment), - - (decrement)2. Math Operators-Part 1: * (multiply), / (divide), % (remainder)3. Math Operators-Part 2: + (addition), - (subtraction)4. Relational Operators: <, <=, >, >=, <> 5. Equality Operators: ==, != 6. Logical AND: &&7. Logical OR: ||8. The Conditional Operator: ? :9. The Assignment Operator: =

In both of the following examples the ANDs are done before the ORs. See if you can follow the logic if num is equal to a value like 8 or 14 in each case:

(num != 3 && num < 6 || num > 10 && num != 15) // if 8 false, 14 true(num < 3 || num > 6 && num < 10 || num == 15) // if 8 true, 14 false

Block Statement:Block statements are made up of groups of statements surrounded by braces:

if (total > MAX){ System.out.println ("Error!!"); errorCount++;}

Nested If Statements : A Nested If statement is an If (or If-Else) statement imbedded within another If (or If-Else) statement. The Else in such statements connects to the nearest unmatched If unless there are brackets between the Else and that If statement. For example:

if (a >= b) if (a == b) System.out.pringln("a and b are equal"); else System.out.println ("a is biggest");

orif (a >= b){ if (a == b) System.out.pringln("a and b are equal");}else System.out.println ("a is lowest");

Short-Circuited Operators:The processing of logical AND and logical OR is “short-circuited” if the left operand is sufficient to determine the result, the right operand is not

Page 6 of 21

Page 7: CSIS 2301 - Programming Principles Iksuweb.kennesaw.edu/~jhiggins/cs1301-13/ReviewNotes…  · Web viewThe Java Reserved Words: Identifiers: Identifiers are names for things like

evaluated. For example, the second part of the following conditional will not be evaluated if count is equal to zero, thus avoiding an error:

if (count != 0 && total/count > MAX)System.out.println ("Testing…");

Conditional Operator:The Conditional Operator evaluates a condition and then evaluates Statement 1 if it is True and Statement 2 if it is False:

variable = (condition) ? Statement1 : Statement2;

The Conditional Operator is equivalent to an If-Else statement. Ex:max = (num1 > num2) ? num1 : num2;

could also have been expressed as: If (num1 > num2)

max = num1; else

max = num2;

Switch Statements : They allow you to organize a lot of code that is involves matching specific values with blocks of code. But you must be careful to use the “break;” statement, or the flow of control from one case will move into the next case below it.

switch (switch-expression) { case value1: statement(s); break; case value2: statement(s); break; … case valueN: statement(s); break;

default: statement(s)-for-default;}

Page 7 of 21

Page 8: CSIS 2301 - Programming Principles Iksuweb.kennesaw.edu/~jhiggins/cs1301-13/ReviewNotes…  · Web viewThe Java Reserved Words: Identifiers: Identifiers are names for things like

Flow of Control when calling a Method:When a call is made from one method to another method, the method that is called gets the flow of control. When that method ends the flow of control returns to the calling method at the point immediately after the call:

doIt helpMe

helpMe();

doIt helpMe

helpMe();

doIt helpMe

helpMe();obj.doIt();

main

obj.doIt();

main

Method Header:

char calc (int num1, int num2, String message)

methodname

returntype

parameter list

The parameter list specifies the typeand name of each parameter

The name of a parameter in the methoddeclaration is called a formal parameter

Page 8 of 21

Page 9: CSIS 2301 - Programming Principles Iksuweb.kennesaw.edu/~jhiggins/cs1301-13/ReviewNotes…  · Web viewThe Java Reserved Words: Identifiers: Identifiers are names for things like

Method Body:{

int sum = num1 + num2;char result = message.charAt (sum);

return result;}

The return expressionmust be consistent withthe return type

sum and resultare local data

They are created each time the method is called, and are destroyed when it finishes executing

Method Parameters:

char calc (int num1, int num2, String message){

int sum = num1 + num2;char result = message.charAt (sum);

return result;}

char calc (int num1, int num2, String message){

int sum = num1 + num2;char result = message.charAt (sum);

return result;}

ch = obj.calc (25, count, "Hello");

NOTE: The Parameter list tells you how many arguments are expected when you call a particular method for a particular purpose.

Loops: the while loopthe for loop

While Loop:The While Loop evaluates a Pre-Condition and if it is True it then executes a statement or statement block, after which the Pre-Condition is re-evaluated and the statement or statement block will continue to be executed until the Pre-Condition evaluates to False:

Ex: while ( condition ) statement;

Do Loop : The Do Loop executes a statement or statement block and then evaluates a Post-Condition and the statement or statement block

Page 9 of 21

Page 10: CSIS 2301 - Programming Principles Iksuweb.kennesaw.edu/~jhiggins/cs1301-13/ReviewNotes…  · Web viewThe Java Reserved Words: Identifiers: Identifiers are names for things like

will continue to be executed until the Post-Condition evaluates to False.

Ex: Dostatement;

while ( condition )

While Loop / Do Loop Flow of Control:

statement

true false

conditionevaluated

The while Loop

statement

true

statementstatement

true falsefalse

conditionevaluatedconditionevaluatedconditionevaluated

The while Loop

true

conditionevaluated

statement

false

The do Loop

truetrue

conditionevaluatedconditionevaluated

statementstatement

falsefalse

The do Loop

For Loop:The For Loop is an expanded instance of the While Loop with a Pre-Condition that is preceded in the structure by initializations that are executed only once, and then followed in the structure with increment or decrement statements. This is usually the best loop to use when you know in advance how many iterations your loop will do and you have a counter to control the loop:

for ( initialization ; condition ; increment )statement;

The initializationis executed once

before the loop begins

The initializationis executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The statement isexecuted until the

condition becomes false

The increment portion is executed at the end of each iteration

The increment portion is executed at the end of each iteration

Page 10 of 21

Page 11: CSIS 2301 - Programming Principles Iksuweb.kennesaw.edu/~jhiggins/cs1301-13/ReviewNotes…  · Web viewThe Java Reserved Words: Identifiers: Identifiers are names for things like

For Loop Flow of Control:

statement

true

statement

true

conditionevaluatedconditionevaluatedconditionevaluated

falsefalse

incrementincrement

initializationinitializationinitialization

Ex: for (int count=1; count <= 5; count++) System.out.println (count);

This is equivalent to the following While loop:int count = 1;while (count <= 5) {

System.out.println (count);count++;

}

The Math Class: -Part of the java.lang package, so you don’t need to “import” it* -Contains static methods, so you don’t instantiate with "new" -Common Methods (but there are more): Math.abs(int n) => returns absolute value of n Math.round(double n) => returns n rounded to whole Math.ceil(double n) => returns smallest whole >= n Math.floor(double n) => returns largest whole <= n Math.pow(double n,double p) => returns n to power p Math.sqrt(double n) => returns square root of n Math.random() => returns random (0.0 to < 1.0) Math.cos(double n) => returns cosine of n Math.sin(double n) => returns sine of n Math.tan(double n) => returns tangent of n Math.acos(double n) => returns arc cosine of n Math.asin(double n) => returns arc sine of n Math.atan(double n) => returns arc tangent of n

Page 11 of 21

Page 12: CSIS 2301 - Programming Principles Iksuweb.kennesaw.edu/~jhiggins/cs1301-13/ReviewNotes…  · Web viewThe Java Reserved Words: Identifiers: Identifiers are names for things like

Math.log(double n) => returns the natural log of n Math.max(int n1, int n2) => returns greater of n1 or n2 Math.min(int n1, int n2) => returns lesser of n1 or n2

-Common Math Class Constants: Math.PI => the value of PI Math.E => the value of natural log base

Static Methods require that you use the name of the Class (which in this case is Math) when you call the method:

Ex: x = r * Math.cos(angle);y = Math.pow(x,3); // Same as: y = x3

y = Math.pow(x,1.0/5.0); // Same as: y = x1/5

*NOTE: The Math class is defined in the java.lang package, which is the standard Java class package imported by default for all Java programs. So you do not have to include an import statement for the Math class to use the methods defined in the Math class.

The Printf Method : The System.out.printf() method allows you to format a string through the use of a format string with format specifiers in it. A format specifier determines how an item should be displayed. An item may be a numeric value, character, boolean value, or a string. Each specifier begins with a percent sign. If you have multiple items for one System.out.printf() call, you must separate the items with commas. You use the method like so:

Example #1:

System.out.printf(“Hello %s\n”, nameString);

When the above Java statement is executed, the word Hello is printed followed by whatever name is stored in the nameString variable, followed by a newline character.

Page 12 of 21

Page 13: CSIS 2301 - Programming Principles Iksuweb.kennesaw.edu/~jhiggins/cs1301-13/ReviewNotes…  · Web viewThe Java Reserved Words: Identifiers: Identifiers are names for things like

Frequently used Format Specifiers:Specifier Output Example

%b a boolean value true or false%c a character 'a'%d a decimal integer 200%f a floating-point # 45.460000%e scientific notation 4.556000e+01%s a string "Java is cool”

Example #2:

The Number Format Class Methods:static NumberFormat getCurrencyInstance()

// Returns an object that formats numbers into the current locale’s currencystatic NumberFormat getPercentInstance()

// Returns an object that formats numbers to percentages in the current localeString format (double number)

// Returns a string containing the formatted number

NOTE: The first two are static methods that contain the format() method. You declare aliases of them so you don’t have to write long statements, for example:

double val1 = 25.5, val2 = 1.5;NumberFormat fmt1 = NumberFormat.getCurrencyInstance();NumberFormat fmt2 = NumberFormat.getPercentInstance();

System.out.println("In currency: " + fmt1.format(val1)); // formats to: $25.50System.out.println("In percent: " + fmt2.format(val2)); // formats to: 150 %

The Decimal Format Class Methods:DecimalFormat (String pattern)

// The Constructor creates a DecimalFormat object with the specified pattern String format (double number)

// Returns a string containing the number formatted according to the pattern

NOTE: DecimalFormat() is not a static method, so you declare it and instantiate it. It takes a pattern where to the right or left of the decimal place, 0’s represent

Page 13 of 21

Page 14: CSIS 2301 - Programming Principles Iksuweb.kennesaw.edu/~jhiggins/cs1301-13/ReviewNotes…  · Web viewThe Java Reserved Words: Identifiers: Identifiers are names for things like

where either a nonzero digit will go or a zero will go if no significant nonzero digit is there, and #’s represent places where only significant digits will go.

Example:double val = 44.44444;DecimalFormat fmt = new DecimalFormat("000.##");

System.out.println(fmt.format(val)); // Outputs: 044.44

ASCII Character Set:

The Character Class Methods:You can use the Character class methods to do certain special operations on characters: isLowerCase(), toLowerCase(), isUpperCase(), toUpperCase(), isDigit(), isLetterOrDigit(). For instance, if you have characters ch1 and ch2 with the following values:

char ch1 = 'b'; char ch2 = '9';

Then:Character.isLowerCase(ch1) returns trueCharacter.isLetterOrDigit(ch1) returns trueCharacter.isDigit(ch1) returns falseCharacter.isDigit(ch2) returns true

Page 14 of 21

Page 15: CSIS 2301 - Programming Principles Iksuweb.kennesaw.edu/~jhiggins/cs1301-13/ReviewNotes…  · Web viewThe Java Reserved Words: Identifiers: Identifiers are names for things like

Character.toUpperCase(ch) returns 'B'

The String Class Methods:String(String str) - The constructorchar charAt(int index)int compareTo(String str)String concat(String str)boolean equals(String str)boolean equalsIgnoreCase(String str)int length()String replace(char oldchar,char newchar)String substring(int offset, int endIndex)String toLowerCase()String toUpperCase()

Examples:String string1 = "Hello", string2 = "hello", string3 = "Hello There";

char ch = string.charAt(1); // ch gets 'e'int val = string1.compareTo(string2);

// val = 0 if string1 = string2, val < 0 if string1 is lexically // before string2, val > 0 if string1 is lexically after string2

string2 = string2.toUpperCase(); // string2 = "HELLO"

String Indexes:In the string "HELLO", character 'H' is at index 0, and character

'O' is at index 4The Escape Sequences:When you want to put special characters in a string, like the invisible characters of a newline or a tab, or if you want a double quote character in a string, you need to use the backslash as an escape sequence like so:

Special Character Escape Sequence:Newline \nTab \tBackspace \b Single Quote \'Double Quote \"Backslash \\

Because the backslash is used for these escape sequences, you can’t just get a backslash into a string unless you use a double backslash as its own escape sequence.

Page 15 of 21

Page 16: CSIS 2301 - Programming Principles Iksuweb.kennesaw.edu/~jhiggins/cs1301-13/ReviewNotes…  · Web viewThe Java Reserved Words: Identifiers: Identifiers are names for things like

Arrays:

Arrays are collections of data items:The items in an array are stored in a sequential list:Every item in an array has the same data type Each item is accessed by its index (position) in the arrayArrays have a length field storing the # of items in the arrayArray indexes start from 0 and go to the length - 1

The scores array could be declared as follows:

int[] scores = new int[10];

scores[2] refers to the value 94 (which is 3rd in the array)

scores.length refers to the number of elements in the array (10)

Declaring, creating, initializing in one step using shorthand notation:

double[] myList = {1.9, 2.9, 3.4, 3.5};

This shorthand notation is equivalent to the following statements:

double[] myList = new double[4];myList[0] = 1.9;myList[1] = 2.9;myList[2] = 3.4;myList[3] = 3.5;

Libraries and Packages are included uses the "import" command.A package is a collection of libraries in a particular path (in a

Page 16 of 21

Page 17: CSIS 2301 - Programming Principles Iksuweb.kennesaw.edu/~jhiggins/cs1301-13/ReviewNotes…  · Web viewThe Java Reserved Words: Identifiers: Identifiers are names for things like

directory)Ex. of a Library: import java.util.Scanner;Ex. of a Package: import java.util.*;

The Random Class Methods:Random() 'The Random # generator constructorfloat nextFloat() 'Returns # between 0.0 (inclusive) and 1.0 (exclusive)int nextInt() 'Returns positive or negative of any possible int valueint nextInt(int num) 'Returns a rnumber in the range 0 to num-1

Example:Random generator = new Random();int dicerole;dicerole = generator.nextInt(6) + 1;

Static Methods require that you use the name of the Class when you call the method:

Ex: y = Math.pow(x,1.0/5.0); // This is: y = x1/5

*NOTE: The Math class is defined in the java.lang package, which is the standard Java class package imported by default for all Java programs. So you do not have to include an import statement for the Math class to use the methods defined in the Math class. Encapsulation:

Making all field data (also called instance data) private and providing public methods to manage the field data:

Visibility modifiers => public / privateSetters and Getters (methods that Set or Get field data)Setters are Mutators (methods that mutate/change data)Getters are Accessors (methods that don't change data)Public methods are also called Service methods

Page 17 of 21

Page 18: CSIS 2301 - Programming Principles Iksuweb.kennesaw.edu/~jhiggins/cs1301-13/ReviewNotes…  · Web viewThe Java Reserved Words: Identifiers: Identifiers are names for things like

Object Oriented Programming (OOP)

The Constructor:The constructor is a special method used to set up an object when it is initially created. A constructor has the same name as the class. If a constructor has parameters, then arguments that match those parameters must be specified when you instantiate an object of the class: For example, if a Car class constructor takes has String values make and model as parameters, then those must be included when instantiating a Car object like so:

Ex: Car fancycar = new Car("Rolls-Royce","Phantom");

Accessors and Mutators:• Because instance data is private, a class usually provides methods to

access and modify data values• An accessor method returns the current value of a variable• A mutator method changes the value of a variable• The names of accessor and mutator methods take the form getX() and

setX(int value), respectively, where X is the name of the variable• They are sometimes called “getters” and “setters”• The use of mutators gives the class designer the ability to restrict a client’s

options to modify an object’s state• A mutator is often designed so that the values of variables can be set only

within particular limits• For example, the setFaceValue mutator of the Die class should restrict the

value to the valid range (1 to MAX)

Driver Programs:Driver programs are usually in the Class that contains the Main method from which you can make calls to the other Methods. A example of a simple class and it’s driver program are given in what follows:

Page 18 of 21

public private

Variables

Methods

Violateencapsulation

Enforceencapsulation

Provide servicesto clients

Support othermethods in the

class

Page 19: CSIS 2301 - Programming Principles Iksuweb.kennesaw.edu/~jhiggins/cs1301-13/ReviewNotes…  · Web viewThe Java Reserved Words: Identifiers: Identifiers are names for things like

An example of a Simple Class:

//*************************************************************************************************************// Pizza.java - A class for making and eating pizzas: all toppings are stored in one long string// where each topping is separated by a comma (ex: “cheese, pepperoni, onion”), // and how much has been eaten is stored in a double as a fraction from 0.0 to// 1.0 where 0.0 means 0% has been eaten and 1.0 means 100% has been eaten.////*************************************************************************************************************import java.text.NumberFormat;

public class Pizza{

private String toppings; // The toppings on the pizzaprivate double amountEaten; // What fraction of the pizza has been eaten

// The Constructor for this classpublic Pizza(String toppingsX){

toppings = toppingsX; // toppingsX is the initial toppings on the pizzaamountEaten = 0.0; // initially none has been eaten so amountEaten gets 0.0

}

// A Getter method (Accessor) to see what the toppings arepublic String getToppings(){

return toppings;}

// A Getter method (Accessor) to see how much has been eatenpublic double getAmountEaten(){

return amountEaten;}

// A Setter method (Mutator) to completely replace the old toppings with new toppingspublic void setTopping(String newToppings){

toppings = newToppings;}

// A Setter method (Mutator) to set a completely new amount that has been eatenpublic void setAmountEaten(double newAmountEaten){

// new value must be between 0.0 and 1.0if (newAmountEaten >= 0 && newAmountEaten <= 1.0)

amountEaten = newAmountEaten;}

// A Setter method (Mutator) to just add new toppings on the pizza without replacingpublic void addNewTopping(String addedToppings){

// put a comma between old and new toppings if neither is an empty stringif (!toppings.equals("") && !addedToppings.equals("")) toppings = toppings + ", ";toppings = toppings + addedToppings;

}

Page 19 of 21

Page 20: CSIS 2301 - Programming Principles Iksuweb.kennesaw.edu/~jhiggins/cs1301-13/ReviewNotes…  · Web viewThe Java Reserved Words: Identifiers: Identifiers are names for things like

// A Setter method (Mutator) to add to the amount eatenpublic void addToAmountEaten(double addedAmountEaten){

// new added value must be between 0.0 and 1.0if (addedAmountEaten >= 0 && addedAmountEaten <= 1.0) {

amountEaten = amountEaten + addedAmountEaten;if (amountEaten > 1) // Make sure its not higher than 1.0

amountEaten = 1.0;}

}

// The toString() method to format the Pizza Object’s output Stringpublic String toString(){

NumberFormat fmt = NumberFormat.getPercentInstance();String result;

result = "Your Pizza Toppings are: " + toppings + "\n";result += "The percentage that has been eaten is: " + fmt.format(amountEaten);return result;

}}

An example of a Driver Class for the Pizza Class Simple Class://*************************************************************************************************************// MakePizzaEatPizza.java - A Driver class for the Pizza Class.////*************************************************************************************************************

public class MakePizzaEatPizza{

public static void main (String[] args){

Pizza mypizza = new Pizza("Cheese");

System.out.println(mypizza);System.out.println();

mypizza.addNewTopping("Pepperoni, Pineapple");System.out.println(mypizza);System.out.println();

mypizza.addToAmountEaten(0.25);mypizza.addNewTopping("Pickles");System.out.println(mypizza);System.out.println();

mypizza.addToAmountEaten(1.0 / 2.0);System.out.println(mypizza);

}}

Page 20 of 21

Page 21: CSIS 2301 - Programming Principles Iksuweb.kennesaw.edu/~jhiggins/cs1301-13/ReviewNotes…  · Web viewThe Java Reserved Words: Identifiers: Identifiers are names for things like

The Output of the above Driver Class is:

Your Pizza Toppings are: CheeseThe percentage that has been eaten is: 0%

Your Pizza Toppings are: Cheese, Pepperoni, PineappleThe percentage that has been eaten is: 0%

Your Pizza Toppings are: Cheese, Pepperoni, Pineapple, PicklesThe percentage that has been eaten is: 25%

Your Pizza Toppings are: Cheese, Pepperoni, Pineapple, PicklesThe percentage that has been eaten is: 75%

Page 21 of 21