Chapter 4

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

16. True or False: A conditionally executed statement should be indented one level from the if clause.

True

if-else statement format

if (BooleanExpression) statement or block else statement or block

if statement examples

if (average > 95) System.out.println("That's a great score!"); if (hours > 40) overTime = true;

flag example

if (average > 95) highScore = true; Later, the same program might use code similar to the following to test the highScore variable, in order to determine if a high score has been achieved: if (highScore) System.out.println("That's a high score!");

if-else-if statement format

if (expression_1) { statement statement etc. } else if (expression_2) { statement statement etc. } *Insert as many else if clauses as neccesary else { statement statement etc. }

9. This is an if statement that appears inside another if statement. A. nested if statement B. tiered if statement C. dislodged if statement D. structured if statement

A. nested if statement

3. >, <, and == are A. relational operators. B. logical operators. C. conditional operators. D. ternary operators.

A. relational operators

1. The if statement is an example of a A. sequence structure. B. decision structure. C. pathway structure. D. class structure.

A. sequence structure

10. An else clause always goes with which of the following? A. the closest previous if clause that doesn't already have its own else clause. B. the closest if clause. C. the if clause that is randomly selected by the compiler. D. none of these

A. the closest previous if clause that doesn't already have its own else clause.

5. This is an empty statement that does nothing. A. missing statement B. virtual statement C. null statement D. conditional statement

C. null statement

15. True or False: The = operator and the == operator perform the same operation.

False

switch statement format

switch (testExpression) { case value_1: statement; statement; etc. break; case value_2: statement; statement; etc. break; *Insert as many case sections as neccessary case value_N: statement; statement; etc. break; default: statement; statement; etc. break; }

if-else-if statement

tests a series of conditions until one is found to be true. It is often simpler to test a series of conditions with the if-else-if statement than with a set of nested if-else statements.

17. True or False: All lines in a conditionally executed block should be indented one level.

true

if statement

used to create a decision structure, which allows a program to have more than one path of execution. The if statement causes one or more statements to execute only when a boolean expression is true. ex. if (BooleanExpression) statement;

if-else statement

will execute one group of statements if its boolean expression is true, or another group if its boolean expression is false.

if-else-if statement example

→ if (score < 60) grade = 'F'; else if (score < 70) grade = 'D'; else if (score < 80) grade = 'C'; else if (score < 90) grade = 'B'; else grade = 'A';

11. When determining whether a number is inside a range, it's best to use this operator. A. && B. ! C. || D. ? :

A. &&

7. This is a boolean variable that signals when some condition exists in the program. A. flag B. signal C. sentinel D. siren

A. flag

12. This determines whether two different String objects contain the same string. A. the == operator B. the = operator C. the equals method D. the stringCompare method

C. the equals method

13. The conditional operator takes how many operands? A. one B. two C. three D. four

C. three

2. This type of expression has a value of either true or false. A. binary expression B. decision expression C. unconditional expression D. boolean expression

D. boolean expression

6. To create a block of statements, you enclose the statements in A. parentheses () B. square brackets [] C. angled brackets <> D. braces {}

D. braces

19. True or False: When an if statement is nested in the else clause of another statement, the only time the inner if statement is executed is when the boolean expression of the outer if statement is true.

False

nested if statement example

For example, consider a banking program that determines whether a bank customer qualifies for a special low interest rate on a loan. To qualify, two conditions must exist: (1) the customer's salary must be at least $50,000, and (2) the customer must have held his or her current job for at least 2 years. // Determine whether the user qualifies for the loan. if (salary >= 50000) { if (yearsOnJob >= 2) { System.out.println("You qualify for the loan."); } else { System.out.println("You must have been on your " + "current job for at least " "two years to qualify."); } } else { System.out.println("You must earn at least " + "$50,000 per year to qualify."); } } }

!

NOT, The ! operator reverses the truth of a boolean expression. If it is applied to an expression that is true, the operator returns false. If it is applied to an expression that is false, the operator returns true.

||

OR, Connects two boolean expressions into one. One or both expressions must be true for the overall expression to be true. It is only necessary for one to be true, and it does not matter which one.

Ignore case in string comparisons

The String class provides the equalsIgnoreCase and compareToIgnoreCase methods. These methods work like the equals and compareTo methods, except the case of the characters in the strings is ignored.

Relational Operators

Used to compare two values. Operators include ==,<,>,<=,>=,<>, !=

Generating Random Numbers with the Random Class

You create an object from the Random class with a statement such as this: Random randomNumbers = new Random();

Comparing String Objects

You should not use relational operators to compare String objects. Instead, you should use an appropriate String method. To determine whether two String objects are equal, you should use the String class's equals method. The general form of the method is StringReference1.equals(StringReference2) StringReference1 is a variable that references a String object, and StringReference2 is another variable that references a String object. The method returns true if the two strings are equal, or false if they are not equal. Here is an example: if (name1.equals(name2)) Assuming that name1 and name2 reference String objects, the expression in the if statement will return true if they are the same, or false if they are not the same.

Payroll class UML diagram

[Payroll] [ -hoursWorked : double -payRate : double ] [ +Payroll ( ) +setHoursWorked (hours : double) : void +set PayRate (rate : double) : void +getHoursWorked( ) : double +getPayRate( ) : double +getGrossPay ( ) : double ]

flag

a boolean variable that signals when some condition exists in the program

example of random number generator returned integer can be between -50 and 49

number = randomNumbers.nextInt(100) - 50;

example of random number generator returned integer can be between 1-10

number = randomNumbers.nextInt(10) + 1;

switch statement example

switch (month) { case 1: System.out.println("January"); break; case 2: System.out.println("February"); break; case 3: System.out.println("March"); break; default: System.out.println("Error: Invalid month"); break; }

Random class's methods

-*nextDouble()* Returns the next random number as a double. The number will be within the range of 0.0 and 1.0. -*nextFloat()* Returns the next random number as a float. The number will be within the range of 0.0 and 1.0. -*nextInt()* Returns the next random number as an int. The number will be within the range of an int, which is -2,147,483,648 to +2,147,483,647. -*nextInt(intn)* This method accepts an integer argument, n. It returns a random number as an int. The number will be within the range of 0 to n, not including n. -*nextLong()* Returns the next random number as a long. The number will be within the range of a long, which is -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807.

Common errors to avoid

-Using = instead of == to compare primitive values. Remember, = is the assignment operator and == tests for equality. -Using == instead of the equals method to compare String objects. You cannot use the == operator to compare the contents of a String object with another string. Instead, you must use the equals or compareTo methods. -Forgetting to enclose an if statement's boolean expression in parentheses. Java requires that the boolean expression being tested by an if statement be enclosed in a set of parentheses. An error will result if you omit the parentheses or use any other grouping characters. -Writing a semicolon at the end of an if clause. When you write a semicolon at the end of an if clause, Java assumes that the conditionally executed statement is a null or empty statement. -Forgetting to enclose multiple conditionally executed statements in braces. Normally the if statement conditionally executes only one statement. To conditionally execute more than one statement, you must enclose them in braces. -Omitting the trailing else in an if-else-if statement. This is not a syntax error, but can lead to logical errors. If you omit the trailing else from an if-else-if statement, no code will be executed if none of the statement's boolean expressions are true. -Not writing complete boolean expressions on both sides of a logical && or || operator. You must write a complete boolean expression on both sides of a logical && or || operator. For example, the expression x > 0 && < 10 is not valid because < 10 is not a complete expression. The expression should be written as x > 0 && x < 10. -Trying to perform case-insensitive string comparisons with the String class's equals and compareTo methods. To perform case-insensitive string comparisons, use the String class's equalsIgnoreCase and compareToIgnoreCase methods. -Using an invalid testExpression in a switch statement. The switch statement can evaluate char, byte, short, int, or String expressions. -Forgetting to write a colon at the end of a case statement. A colon must appear after the CaseExpression in each case statement. -Forgetting to write a break statement in a case section. This is not a syntax error, but it can lead to logical errors. The program does not branch out of a switch statement until it reaches a break statement or the end of the switch statement. -Forgetting to write a default section in a switch statement. This is not a syntax error, but can lead to a logical error. If you omit the default section, no code will be executed if none of the case values match the testExpression. -Reversing the ? and the : when using the conditional operator. When using the conditional operator, the ? character appears first in the conditional expression, then the : character.

Payroll.java

/** * This class holds values for hours worked and the * hourly pay rate. It calculates the gross pay and * adds additional pay for overtime. */ public class Payroll { private double hoursWorked; // Number of hours worked private double payRate; // The hourly pay rate /** * The constructor initializes the hoursWorked and * payRate fields to 0.0. */ public Payroll() { hoursWorked = 0.0; payRate = 0.0; } /** * The setHoursWorked method accepts an argument * that is stored in the hoursWorked field. */ public void setHoursWorked(double hours) { hoursWorked = hours; } /** * The setPayRate method accepts an argument that * is stored in the payRate field. */ public void setPayRate(double rate) { payRate = rate; } /** * The getHoursWorked method returns the hoursWorked * field. */ public double getHoursWorked() { return hoursWorked } /** *The getPayRate method returns the payRate field. */ public double getPayRate() { return payRate; } /** * The getGrossPay method calculates and returns the * gross pay. Overtime pay is also included. */ public double getGrossPay() { double grossPay, // Holds the gross pay overtimePay; // Holds pay for overtime // Determine whether the employee worked more // than 40 hours. if (hoursWorked > 40) { // Calculate regular pay for the first 40 hours. grossPay = 40 * payRate; // Calculate overtime pay at 1.5 times the regular // hourly pay rate. overtimePay = (hoursWorked − 40) * (payRate * 1.5); // Add the overtime pay to the regular pay. grossPay += overtimePay; } else { // No overtime worked. grossPay = payRate * hoursWorked; } return grossPay; } }

example of random number generator returned integer can be between −2,147,483,648 and +2,147,483,647.

// Declare an int variable. int number; // Create a Random object. Random randomNumbers = new Random(); // Get a random integer and assign it to number. number = randomNumbers.nextInt();

if-else statement example

// Determine whether division by zero will occur. if (number2 == 0) { // Error − division by zero. System.out.println("Division by zero is not possible."); System.out.println("Please run the program again and "); System.out.println("enter a number other than zero."); } else { // Perform the division and display the quotient. quotient = (double) number1 / number2; System.out.print("The quotient of " + number1); System.out.print(" divided by " + number2); System.out.println(" is " + quotient); }

&&

AND , Connects two boolean expressions into one. Both expressions must be true for the overall expression to be true.

8. How does the character "A" compare to the character "B"? A. "A" is greater than "B" B. "A" is less than "B" C. "A" is equal to "B" D. You cannot compare characters.

B. "A" is less than "B"

14. This section of a switch statement is branched to if none of the case values match the testExpression. A. else B. default C. case D. otherwise

B. default

4. &&, ||, and ! are A. relational operators. B. logical operators. C. conditional operators. D. ternary operators.

B. logical operators

Conditional operator

The conditional operator is powerful and unique. Because it takes three operands, it is considered a ternary operator. The conditional operator provides a shorthand method of expressing a simple if-else statement. The operator consists of the question mark (?) and the colon (:). You use the operator to write a conditional expression in the following format: BooleanExpresion ? Value1 : Value2; The BooleanExpression is like the boolean expression in the parentheses of an if statement. If the BooleanExpression is true, then the value of the conditional expression is Value1. Otherwise, the value of the conditional expression is Value2. Here is an example of a statement using the conditional operator: y = x < 0 ? 10 : 20; This preceding statement performs the same operation as the following ifelse statement: if (x < 0) y = 10; else y = 20;

The Switch Statement

The switch statement is a multiple alternative decision structure. It allows you to test the value of a variable or an expression, then use that value to determine which statement or set of statements to execute.

Random randomNumbers = new Random();

This statement does the following: -It declares a variable named randomNumbers. The data type is the Random class. -The expression new Random() creates an instance of the Random class. -The equal sign assigns the address of the Random class to the randomNumbers variable.

Nested if statements

To test more than one condition, an if statement can be nested inside another if statement.

18. True or False: When an if statement is nested in the if clause of another statement, the only time the inner if statement is executed is when the boolean expression of the outer if statement is true.

True

20. True or False: The scope of a variable is limited to the block in which it is defined.

True

GrossPay.java

import java.util.Scanner; // Needed for the Scanner class /** * This program uses the Payroll class to * calculate an employee's gross pay. */ public class GrossPay { public static void main(String[] args) { double hours, // To hold hours worked rate; // To hold the hourly pay rate // Create a Scanner object to read input. Scanner keyboard = new Scanner(System.in); // Create a Payroll object. Payroll employee = new Payroll(); // Get the number of hours worked. System.out.print("How many hours did the " + "employee work? "); hours = keyboard.nextDouble(); // Get the hourly pay rate. System.out.print("What is the employee's " + "hourly pay rate? "); rate = keyboard.nextDouble(); // Store the data. employee.setHoursWorked(hours); employee.setPayRate(rate); // Display the gross pay. System.out.println("The employee's gross pay " + "is $" + employee.getGrossPay());


Set pelajaran terkait

AP Human Geography Midterm MC Questions Unit 1-3

View Set

When was the Constitution written ?

View Set

Business Life Cycle, Business Registration in the Philippines, Forms of Business Organization and Advantages and Disadvantages of Different Forms of Business Organization Source of Capitalization for Agricultural Entrepreneur

View Set

What Is So Special About a Leaf?

View Set

MKT304 Principles of Selling Exam 1

View Set

Nursing Process and Critical Thinking Chapter 4

View Set

zzzzs) Powerpoint Nervous system Parts 1 - 3

View Set