This assignment can be completed either individual or by a group of 2 students, ensure to submit a zip file of all the .java files to canvas and name the zip file by your first and last name (example: Joe_Stuart.zip) and if you are a group of 2 make sure the zip file has both the students first and last name (example: Sally_Jones-Joe_Stuart.zip) (My first name Jin, last name Zheng.)(I NEED COMPLETE JAVA CODING PROGRAM NOT JUST Paragraph) Please flowing step by stepWrite a Java interface called Lockable that includes the following methods: setKey, lock, unlock, and locked. The setKey, lock and unlock methods take an integer parameter that represents the key. The setKey method establishes the key. The lock and unlock methods lock and unlock the object, but only if the key passed in is correct. The locked method returns a boolean that indicates whether or not the object is locked. A Lockable object represents an object whose regular methods are protected: if the object is locked, the methods cannot be invoked; if it is unlocked, they can be invoked. Write a version of the Coin class (call it Coin2) from Chapter 5 so that it is Lockable.//******************///Coin.java//flips a two sided coin//*******************public class CoinFlip{//—————————————————————–// Creates a Coin object, flips it, and prints the results.//—————————————————————–public static void main(String[] args){Coin myCoin = new Coin();myCoin.flip();System.out.println(myCoin);if (myCoin.isHeads())System.out.println(“You win.”);elseSystem.out.println(“Better luck next time.”);}}//********************************************************************// Coin.java Author: Lewis/Loftus//// Represents a coin with two sides that can be flipped.//********************************************************************public class Coin{private final int HEADS = 0;private final int TAILS = 1;private int face;//—————————————————————–// Sets up the coin by flipping it initially.//—————————————————————–public Coin(){flip();}//—————————————————————–// Flips the coin by randomly choosing a face value.//—————————————————————–public void flip(){face = (int) (Math.random() * 2);}//—————————————————————–// Returns true if the current face of the coin is heads.//—————————————————————–public boolean isHeads(){return (face == HEADS);}//—————————————————————–// Returns the current face of the coin as a string.//—————————————————————–public String toString(){String faceName;if (face == HEADS)faceName = “Heads”;elsefaceName = “Tails”;return faceName;}}**Then Use the following driver CoinFlipTest to test your Coin2 class and Lockable interface.public class CoinFlipTest {//———— // Flips a coin multiple times and counts the number of heads // and tails that result. Locks and unlocks coins //———————————————————- public static void main(String[] args) { Coin2 myCoin = new Coin2(); myCoin.setKey(1111); System.out.println(“Initial: ” + myCoin); myCoin.lock(1111); System.out.println(“After lock: ” + myCoin); myCoin.flip(); System.out.println(“After attempted flip: ” + myCoin); myCoin.unlock(1111); myCoin.flip(); System.out.println(“After unlock: ” + myCoin); }Output should look like the following: (Heads and Tails maybe different)Initial: TailsAfter lock: LOCKEDAfter attempted flip: LOCKEDAfter unlock: Tails
chap05__1_.pptx
Unformatted Attachment Preview
Chapter 5
Conditionals and Loops
Java Software Solutions
Foundations of Program Design
9th Edition
John Lewis
William Loftus
Copyright © 2017 Pearson Education, Inc.
Conditionals and Loops
Now we will examine programming statements
that allow us to:
make decisions
repeat processing steps in a loop
Chapter 5 focuses on:
boolean expressions
the if and if-else statements
comparing data
while loops
iterators
the ArrayList class
more GUI controls
Copyright © 2017 Pearson Education, Inc.
Outline
Boolean Expressions
The if Statement
Comparing Data
The while Statement
Iterators
The ArrayList Class
Determining Event Sources
Managing Fonts
Check Boxes and Radio Buttons
Copyright © 2017 Pearson Education, Inc.
Flow of Control
Unless specified otherwise, the order of statement
execution through a method is linear: one after
another
Some programming statements allow us to make
decisions and perform repetitions
These decisions are based on boolean expressions
(also called conditions) that evaluate to true or false
The order of statement execution is called the flow
of control
Copyright © 2017 Pearson Education, Inc.
Conditional Statements
A conditional statement lets us choose which
statement will be executed next
They are sometimes called selection statements
Conditional statements give us the power to make
basic decisions
The Java conditional statements are the:
if and if-else statement
switch statement
We’ll explore the switch statement in Chapter 6
Copyright © 2017 Pearson Education, Inc.
Boolean Expressions
A condition often uses one of Java’s equality
operators or relational operators, which all return
boolean results:
==
!=
<
>
<=
>=
equal to
not equal to
less than
greater than
less than or equal to
greater than or equal to
Note the difference between the equality operator
(==) and the assignment operator (=)
Copyright © 2017 Pearson Education, Inc.
Boolean Expressions
An if statement with its boolean condition:
if (sum > MAX)
delta = sum MAX;
First, the condition is evaluated: the value of sum is
either greater than the value of MAX, or it is not
If the condition is true, the assignment statement is
executed; if it isn’t, it is skipped
See Age.java
Copyright © 2017 Pearson Education, Inc.
//********************************************************************
// Age.java
Author: Lewis/Loftus
//
// Demonstrates the use of an if statement.
//********************************************************************
import java.util.Scanner;
public class Age
{
//—————————————————————-// Reads the user’s age and prints comments accordingly.
//—————————————————————-public static void main(String[] args)
{
final int MINOR = 21;
Scanner scan = new Scanner(System.in);
System.out.print(“Enter your age: “);
int age = scan.nextInt();
continue
Copyright © 2017 Pearson Education, Inc.
continue
System.out.println(“You entered: ” + age);
if (age < MINOR)
System.out.println("Youth is a wonderful thing. Enjoy.");
System.out.println("Age is a state of mind.");
}
}
Copyright © 2017 Pearson Education, Inc.
Sample Run
continue
Enter your age: 47
You entered: 47
Age is a state of mind.
System.out.println("You entered: " + age);
if (age < MINOR)
System.out.println("Youth is a wonderful thing. Enjoy.");
System.out.println("Age is a state of mind.");
}
}
Another Sample Run
Enter your age: 12
You entered: 12
Youth is a wonderful thing. Enjoy.
Age is a state of mind.
Copyright © 2017 Pearson Education, Inc.
Logical Operators
Boolean expressions can also use the following
logical operators:
!
&&
||
Logical NOT
Logical AND
Logical OR
They all take boolean operands and produce
boolean results
Logical NOT is a unary operator (it operates on one
operand)
Logical AND and logical OR are binary operators
(each operates on two operands)
Copyright © 2017 Pearson Education, Inc.
Logical NOT
The logical NOT operation is also called logical
negation or logical complement
If some boolean condition a is true, then !a is false;
if a is false, then !a is true
Logical expressions can be shown using a truth
table:
a
!a
true
false
false
true
Copyright © 2017 Pearson Education, Inc.
Logical AND and Logical OR
The logical AND expression
a && b
is true if both a and b are true, and false otherwise
The logical OR expression
a || b
is true if a or b or both are true, and false otherwise
Copyright © 2017 Pearson Education, Inc.
Logical AND and Logical OR
A truth table shows all possible true-false
combinations of the terms
Since && and || each have two operands, there
are four possible combinations of a and b
a
b
a && b
a || b
true
true
false
true
false
true
true
false
false
true
true
true
false
false
false
false
Copyright © 2017 Pearson Education, Inc.
Logical Operators
Expressions that use logical operators can form
complex conditions
if (total < MAX+5 && !found)
System.out.println("Processing
");
All logical operators have lower precedence than
the relational operators
The ! operator has higher precedence than && and
||
Copyright © 2017 Pearson Education, Inc.
Boolean Expressions
Specific expressions can be evaluated using truth
tables
total < MAX
found
!found
total < MAX && !found
false
false
true
false
false
true
true
true
false
true
false
true
false
false
true
false
Copyright © 2017 Pearson Education, Inc.
Short-Circuited Operators
The processing of && and || is short-circuited
If the left operand is sufficient to determine the
result, the right operand is not evaluated
if (count != 0 && total/count > MAX)
System.out.println(“Testing.”);
This type of processing should be used carefully
Copyright © 2017 Pearson Education, Inc.
Outline
Boolean Expressions
The if Statement
Comparing Data
The while Statement
Iterators
The ArrayList Class
Determining Event Sources
Managing Fonts
Check Boxes and Radio Buttons
Copyright © 2017 Pearson Education, Inc.
The if Statement
Let’s now look at the if statement in more detail
The if statement has the following syntax:
if is a Java
reserved word
The condition must be a
boolean expression. It must
evaluate to either true or false.
if ( condition )
statement;
If the condition is true, the statement is executed.
If it is false, the statement is skipped.
Copyright © 2017 Pearson Education, Inc.
Logic of an if statement
condition
evaluated
true
false
statement
Copyright © 2017 Pearson Education, Inc.
Indentation
The statement controlled by the if statement is
indented to indicate that relationship
The use of a consistent indentation style makes a
program easier to read and understand
The compiler ignores indentation, which can lead to
errors if the indentation is not correct
“Always code as if the person who ends up
maintaining your code will be a violent
psychopath who knows where you live.”
— Martin Golding
Copyright © 2017 Pearson Education, Inc.
Quick Check
What do the following statements do?
if (total != stock + warehouse)
inventoryError = true;
if (found || !done)
System.out.println(“Ok”);
Copyright © 2017 Pearson Education, Inc.
Quick Check
What do the following statements do?
if (total != stock + warehouse)
inventoryError = true;
Sets the boolean variable to true if the value of total
is not equal to the sum of stock and warehouse
if (found || !done)
System.out.println(“Ok”);
Prints “Ok” if found is true or done is false
Copyright © 2017 Pearson Education, Inc.
The if-else Statement
An else clause can be added to an if statement to
make an if-else statement
if ( condition )
statement1;
else
statement2;
If the condition is true, statement1 is executed; if
the condition is false, statement2 is executed
One or the other will be executed, but not both
See Wages.java
Copyright © 2017 Pearson Education, Inc.
//********************************************************************
// Wages.java
Author: Lewis/Loftus
//
// Demonstrates the use of an if-else statement.
//********************************************************************
import java.text.NumberFormat;
import java.util.Scanner;
public class Wages
{
//—————————————————————-// Reads the number of hours worked and calculates wages.
//—————————————————————-public static void main(String[] args)
{
final double RATE = 8.25; // regular pay rate
final int STANDARD = 40;
// standard hours in a work week
Scanner scan = new Scanner(System.in);
double pay = 0.0;
continue
Copyright © 2017 Pearson Education, Inc.
continue
System.out.print(“Enter the number of hours worked: “);
int hours = scan.nextInt();
System.out.println();
// Pay overtime at “time and a half”
if (hours > STANDARD)
pay = STANDARD * RATE + (hours-STANDARD) * (RATE * 1.5);
else
pay = hours * RATE;
NumberFormat fmt = NumberFormat.getCurrencyInstance();
System.out.println(“Gross earnings: ” + fmt.format(pay));
}
}
Copyright © 2017 Pearson Education, Inc.
continue
Sample Run
System.out.print(“Enter
the number
of hours
worked:
Enter the number
of hours
worked:
46 “);
int hours = scan.nextInt();
Gross earnings: $404.25
System.out.println();
// Pay overtime at “time and a half”
if (hours > STANDARD)
pay = STANDARD * RATE + (hours-STANDARD) * (RATE * 1.5);
else
pay = hours * RATE;
NumberFormat fmt = NumberFormat.getCurrencyInstance();
System.out.println(“Gross earnings: ” + fmt.format(pay));
}
}
Copyright © 2017 Pearson Education, Inc.
Logic of an if-else statement
condition
evaluated
true
false
statement1
statement2
Copyright © 2017 Pearson Education, Inc.
The Coin Class
Let’s look at an example that uses a class that
represents a coin that can be flipped
Instance data is used to indicate which face (heads
or tails) is currently showing
See CoinFlip.java
See Coin.java
Copyright © 2017 Pearson Education, Inc.
//********************************************************************
// CoinFlip.java
Author: Lewis/Loftus
//
// Demonstrates the use of an if-else statement.
//********************************************************************
public class CoinFlip
{
//—————————————————————-// Creates a Coin object, flips it, and prints the results.
//—————————————————————-public static void main(String[] args)
{
Coin myCoin = new Coin();
myCoin.flip();
System.out.println(myCoin);
if (myCoin.isHeads())
System.out.println(“You win.”);
else
System.out.println(“Better luck next time.”);
}
}
Copyright © 2017 Pearson Education, Inc.
Sample Run
//********************************************************************
// CoinFlip.java
Author: Lewis/Loftus
Tails
//
// Demonstrates the use
of anluck
if-else
Better
nextstatement.
time.
//********************************************************************
public class CoinFlip
{
//—————————————————————-// Creates a Coin object, flips it, and prints the results.
//—————————————————————-public static void main(String[] args)
{
Coin myCoin = new Coin();
myCoin.flip();
System.out.println(myCoin);
if (myCoin.isHeads())
System.out.println(“You win.”);
else
System.out.println(“Better luck next time.”);
}
}
Copyright © 2017 Pearson Education, Inc.
//********************************************************************
// Coin.java
Author: Lewis/Loftus
//
// Represents a coin with two sides that can be flipped.
//********************************************************************
public class Coin
{
private final int HEADS = 0;
private final int TAILS = 1;
private int face;
//—————————————————————-// Sets up the coin by flipping it initially.
//—————————————————————-public Coin()
{
flip();
}
continue
Copyright © 2017 Pearson Education, Inc.
continue
//—————————————————————-// Flips the coin by randomly choosing a face value.
//—————————————————————-public void flip()
{
face = (int) (Math.random() * 2);
}
//—————————————————————-// Returns true if the current face of the coin is heads.
//—————————————————————-public boolean isHeads()
{
return (face == HEADS);
}
continue
Copyright © 2017 Pearson Education, Inc.
continue
//—————————————————————-// Returns the current face of the coin as a string.
//—————————————————————-public String toString()
{
String faceName;
if (face == HEADS)
faceName = “Heads”;
else
faceName = “Tails”;
return faceName;
}
}
Copyright © 2017 Pearson Education, Inc.
Indentation Revisited
Remember that indentation is for the human
reader, and is ignored by the compiler
if (depth >= UPPER_LIMIT)
delta = 100;
else
System.out.println(“Reseting Delta”);
delta = 0;
Despite what the indentation implies, delta will be
set to 0 no matter what
Copyright © 2017 Pearson Education, Inc.
Block Statements
Several statements can be grouped together into a
block statement delimited by braces
A block statement can be used wherever a
statement is called for in the Java syntax rules
if (total > MAX)
{
System.out.println(“Error!!”);
errorCount++;
}
Copyright © 2017 Pearson Education, Inc.
Block Statements
The if clause, or the else clause, or both, could
govern block statements
if (total > MAX)
{
System.out.println(“Error!!”);
errorCount++;
}
else
{
System.out.println(“Total: ” + total);
current = total*2;
}
See Guessing.java
Copyright © 2017 Pearson Education, Inc.
//********************************************************************
// Guessing.java
Author: Lewis/Loftus
//
// Demonstrates the use of a block statement in an if-else.
//********************************************************************
import java.util.*;
public class Guessing
{
//—————————————————————-// Plays a simple guessing game with the user.
//—————————————————————-public static void main(String[] args)
{
final int MAX = 10;
int answer, guess;
Scanner scan = new Scanner(System.in);
Random generator = new Random();
answer = generator.nextInt(MAX) + 1;
continue
Copyright © 2017 Pearson Education, Inc.
continue
System.out.print(“I’m thinking of a number between 1 and ”
+ MAX + “. Guess what it is: “);
guess = scan.nextInt();
if (guess == answer)
System.out.println(“You got it! Good guessing!”);
else
{
System.out.println(“That is not correct, sorry.”);
System.out.println(“The number was ” + answer);
}
}
}
Copyright © 2017 Pearson Education, Inc.
continue
Sample
Run
System.out.print(“I’m
thinking of
a number
betweenwhat
1 andit” is: 6
I’m thinking
of a number between
1 and
10. Guess
+ MAX + “. Guess what it is: “);
That is not correct, sorry.
The number was 9
guess = scan.nextInt();
if (guess == answer)
System.out.println(“You got it! Good guessing!”);
else
{
System.out.println(“That is not correct, sorry.”);
System.out.println(“The number was ” + answer);
}
}
}
Copyright © 2017 Pearson Education, Inc.
Nested if Statements
The statement executed as a result of an if or
else clause could be another if statement
These are called nested if statements
An else clause is matched to the last unmatched
if (no matter what the indentation implies)
Braces can be used to specify the if statement to
which an else clause belongs
See MinOfThree.java
Copyright © 2017 Pearson Education, Inc.
//********************************************************************
// MinOfThree.java
Author: Lewis/Loftus
//
// Demonstrates the use of nested if statements.
//********************************************************************
import java.util.Scanner;
public class MinOfThree
{
//—————————————————————-// Reads three integers from the user and determines the smallest
// value.
//—————————————————————-public static void main(String[] args)
{
int num1, num2, num3, min = 0;
Scanner scan = new Scanner(System.in);
System.out.println(“Enter three integers: “);
num1 = scan.nextInt();
num2 = scan.nextInt();
num3 = scan.nextInt();
continue
Copyright © 2017 Pearson Education, Inc.
continue
if (num1 < num2)
if (num1 < num3)
min = num1;
else
min = num3;
else
if (num2 < num3)
min = num2;
else
min = num3;
System.out.println("Minimum value: " + min);
}
}
Copyright © 2017 Pearson Education, Inc.
continue
if (num1 < num2)
if (num1 < num3)
min = num1;
else
min = num3;
else
if (num2 < num3)
min = num2;
else
min = num3;
Sample Run
Enter three integers:
84 69 90
Minimum value: 69
System.out.println("Minimum value: " + min);
}
}
Copyright © 2017 Pearson Education, Inc.
Outline
Boolean Expressions
The if Statement
Comparing Data
The while Statement
Iterators
The ArrayList Class
Determining Event Sources
Managing Fonts
Check Boxes and Radio Buttons
Copyright © 2017 Pearson Education, Inc.
Comparing Data
When comparing data using boolean expressions,
it's important to understand the nuances of certain
data types
Let's examine some key situations:
Comparing floating point values for equality
Comparing characters
Comparing strings (alphabetical order)
Comparing object vs. comparing object references
Copyright © 2017 Pearson Education, Inc.
Comparing Float Values
You should rarely use the equality operator (==)
when comparing two floating point values (float
or double)
Two floating point values are equal only if their
underlying binary representations match exactly
Computations often result in slight differences that
may be irrelevant
In many situations, you might consider two floating
point numbers to be "close enough" even if they
aren't exactly equal
Copyright © 2017 Pearson Education, Inc.
Comparing Float Values
To determine the equality of two floats, use the
following technique:
if (Math.abs(f1 - f2) < TOLERANCE)
System.out.println("Essentially equal");
If the difference between the two floating point
values is less than the tolerance, they are
considered to be equal
The tolerance could be set to any appropriate level,
such as 0.000001
Copyright © 2017 Pearson Education, Inc.
Comparing Characters
As we've discussed, Java character data is based
on the Unicode character set
Unicode establishes a particular numeric value for
each character, and therefore an ordering
We can use relational operators on character data
based on this ordering
For example, the character '+' is less than the
character 'J' because it comes before it in the
Unicode character set
Appendix C provides an overview of Unicode
Copyright © 2017 Pearson Education, Inc.
Comparing Characters
In Unicode, the digit characters (0-9) are contiguous
and in order
Likewise, the uppercase letters (A-Z) and lowercase
letters (a-z) are contiguous and in order
Characters
09
AZ
az
Unicode Values
48 through 57
65 through 90
97 through 122
Copyright © 2017 Pearson Education, Inc.
Comparing Strings
Remember that in Java a character string is an
object
The equals method can be called with strings to
determine if two strings contain exactly the same
characters in the same order
The equals method returns a boolean result
if (name1.equals(name2))
System.out.println("Same name");
Copyright © 2017 Pearson Education, Inc.
Comparing Strings
We cannot use the relational oper ...
Purchase answer to see full
attachment
Why Work with Us
Top Quality and Well-Researched Papers
We always make sure that writers follow all your instructions precisely. You can choose your academic level: high school, college/university or professional, and we will assign a writer who has a respective degree.
Professional and Experienced Academic Writers
We have a team of professional writers with experience in academic and business writing. Many are native speakers and able to perform any task for which you need help.
Free Unlimited Revisions
If you think we missed something, send your order for a free revision. You have 10 days to submit the order for review after you have received the final document. You can do this yourself after logging into your personal account or by contacting our support.
Prompt Delivery and 100% Money-Back-Guarantee
All papers are always delivered on time. In case we need more time to master your paper, we may contact you regarding the deadline extension. In case you cannot provide us with more time, a 100% refund is guaranteed.
Original & Confidential
We use several writing tools checks to ensure that all documents you receive are free from plagiarism. Our editors carefully review all quotations in the text. We also promise maximum confidentiality in all of our services.
24/7 Customer Support
Our support agents are available 24 hours a day 7 days a week and committed to providing you with the best customer experience. Get in touch whenever you need any assistance.
Try it now!
How it works?
Follow these simple steps to get your paper done
Place your order
Fill in the order form and provide all details of your assignment.
Proceed with the payment
Choose the payment system that suits you most.
Receive the final file
Once your paper is ready, we will email it to you.
Our Services
No need to work on your paper at night. Sleep tight, we will cover your back. We offer all kinds of writing services.
Essays
No matter what kind of academic paper you need and how urgent you need it, you are welcome to choose your academic level and the type of your paper at an affordable price. We take care of all your paper needs and give a 24/7 customer care support system.
Admissions
Admission Essays & Business Writing Help
An admission essay is an essay or other written statement by a candidate, often a potential student enrolling in a college, university, or graduate school. You can be rest assurred that through our service we will write the best admission essay for you.
Reviews
Editing Support
Our academic writers and editors make the necessary changes to your paper so that it is polished. We also format your document by correctly quoting the sources and creating reference lists in the formats APA, Harvard, MLA, Chicago / Turabian.
Reviews
Revision Support
If you think your paper could be improved, you can request a review. In this case, your paper will be checked by the writer or assigned to an editor. You can use this option as many times as you see fit. This is free because we want you to be completely satisfied with the service offered.