Control Statements: Part 1

Similar documents
Introduction to Java Applications

Assignment Checklist. Prelab Activities. Lab Exercises. Labs Provided by Instructor. Postlab Activities. Section:

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Introduction to Classes and Objects

Arrays OBJECTIVES. In this chapter you will learn:

[Page 177 (continued)] a. if ( age >= 65 ); cout << "Age is greater than or equal to 65" << endl; else cout << "Age is less than 65 << endl";

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: if Single-Selection Statement CSC 209 JAVA I. week 3- Control Statements: Part I

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

download instant at

Introduction to Classes and Objects

Introduction to Java Applications

Programming with Java

Control Statements. Musa M. Ameen Computer Engineering Dept.

2.8. Decision Making: Equality and Relational Operators

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

In Fig. 3.5 and Fig. 3.7, we include some completely blank lines in the pseudocode for readability. programs into their various phases.

COMP 202 Java in one week

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Chapter 3 Structured Program Development

Lab 2: Structured Program Development in C

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Full file at

JavaScript: Control Statements I Pearson Education, Inc. All rights reserved.

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

CS111: PROGRAMMING LANGUAGE II

Java Coding 3. Over & over again!

Introduction to Java & Fundamental Data Types

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Fundamentals of Programming Session 7

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

CEN 414 Java Programming

Course Outline. Introduction to java

COMP 202. Java in one week

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

3 The L oop Control Structure

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

CS110D: PROGRAMMING LANGUAGE I

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

Introduction to Java Unit 1. Using BlueJ to Write Programs

Structured Program Development in C

Elementary Programming

Structured Program Development

Java Assignment 3: Loop Practice Ver 3.0 Last Updated: 12/1/2015 8:57 AM

LEC03: Decisions and Iterations

Instructor: Eng.Omar Al-Nahal

2.5 Another Application: Adding Integers

CSE123 LECTURE 3-1. Program Design and Control Structures Repetitions (Loops) 1-1

AP Computer Science Unit 1. Writing Programs Using BlueJ

Basic Problem solving Techniques Top Down stepwise refinement If & if else.. While.. Counter controlled and sentinel controlled repetition Usage of

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Fundamentals of Programming Data Types & Methods

Chapter 3 Structured Program Development in C Part II

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

AP Computer Science Unit 1. Programs

Section 2.2 Your First Program in Java: Printing a Line of Text

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

AP Computer Science Unit 1. Writing Programs Using BlueJ

Chapter 2. Elementary Programming

Object-Oriented Programming

CS141 Programming Assignment #6

COMP 202 Java in one week

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

Chapter Goals. Contents LOOPS

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Full file at

Chapter 3. Selections

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

St. Edmund Preparatory High School Brooklyn, NY

Exam 1. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 45 Obtained Marks:

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Object Oriented Programming. Java-Lecture 1

Mid Term Exam 1. Programming I (CPCS 202) Instructor: M. G. Abbas Malik Date: Sunday November 3, 2013 Total Marks: 50 Obtained Marks:

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

PRIMITIVE VARIABLES. CS302 Introduction to Programming University of Wisconsin Madison Lecture 3. By Matthew Bernstein

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

JavaScript: Control Statements I

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

Introduction to the Java Basics: Control Flow Statements

REPETITION CONTROL STRUCTURE LOGO

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Introduction to Java Applications; Input/Output and Operators

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Example: Monte Carlo Simulation 1

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1

Exam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks:

Unit 1 Lesson 4. Introduction to Control Statements

Data Conversion & Scanner Class

4 WORKING WITH DATA TYPES AND OPERATIONS

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

Supplementary Test 1

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

Transcription:

4 Let s all move one place on. Lewis Carroll Control Statements: Part 1 The wheel is come full circle. William Shakespeare How many apples fell on Newton s head before he took the hint! Robert Frost All the evolution we know of proceeds from the vague to the definite. Charles Sanders Peirce OBJECTIVES In this chapter you will learn: To use basic problem-solving techniques. To develop algorithms through the process of top-down, stepwise refinement. To use the if and if else selection statements to choose among alternative actions. To use the while repetition statement to execute statements in a program repeatedly. To use counter-controlled repetition and sentinel-controlled repetition. To use the assignment, increment and decrement operators.

Chapter 4 Control Statements: Part 1 99 Assignment Checklist Date: Section: Exercises Assigned: Circle assignments Date Due Prelab Activities Matching YES NO Fill in the Blank YES NO Short Answer YES NO Programming Output YES NO Correct the Code YES NO Lab Exercises Exercise 1 Credit YES NO Follow-Up Questions and Activities 1, 2 Exercise 2 Palindromes YES NO Follow-Up Question and Activity 1 Exercise 3 Largest Number YES NO Follow-Up Question and Activity 1 Debugging YES NO Postlab Activities Coding Exercises 1, 2, 3, 4, 5, 6 Programming Challenges 1, 2

Chapter 4 Control Statements: Part 1 101 Prelab Activities Matching Date: Section: After reading Chapter 4 of Java How to Program: Seventh Edition, answer the given questions. These questions are intended to test and reinforce your understanding of key Java concepts. You may answer these questions either before or during the lab. For each term in the left column, write the letter for the description that best matches the term from the right column. Term Description M I A K H O P C E Q G D B F J L N 1. -- 2. ++ 3.?: 4. algorithm 5. selection statement 6. sentinel-controlled repetition 7. ; 8. pseudocode 9. repetition statement 10. counter-controlled repetition 11. program control 12. top-down, stepwise refinement 13. if 14. if else 15. block 16. +=, -=, *=, /=, %= 17. primitive types a) Java s only ternary operator. b) A selection statement that executes an indicated action only when the condition is true. c) An artificial and informal language that helps programmers develop algorithms. d) A process for refining pseudocode by maintaining a complete program representation for each refinement. e) Allows the programmer to specify that an action is to be repeated while some condition remains true. f) A selection statement that specifies separate actions to execute when a condition is true and when a condition is false. g) Specifying the order in which statements are to be executed in a computer program. h) Chooses among alternative courses of action in a program. i) Increment operator. j) A set of statements contained within a pair of braces. k) A procedure for solving a problem in terms of the actions to execute and the order in which the actions should execute. l) Arithmetic assignment operators. m) Decrement operator. n) Building blocks for more complicated types in Java. o) Used when the number of repetitions is not known before the loop begins executing. p) Empty statement. q) Used when the number of repetitions is known before the loop begins executing.

Chapter 4 Control Statements: Part 1 103 Prelab Activities Fill in the Blank Fill in the Blank Date: Section: Fill in the blanks for each of the following statements: 18. Specifying the order in which statements execute in a computer program is called program control. 19. The if selection statement executes an indicated action only when the condition is true. 20. Top-down, stepwise refinement is a process for refining pseudocode by maintaining a complete representation of the program during each refinement. 21. Java requires all variables to have a type before they can be used in a program. For this reason, Java is referred to as a(n) strongly typed language. 22. Java uses internationally recognized standards for both characters and floating-point numbers. 23. A(n) declaration specifies the type and name of a variable. 24. The if else selection statement specifies separate actions to execute when the condition is true and when the condition is false. 25. The ++ operator and the -- operator increment and decrement a variable by 1, respectively. 26. Unary cast operator ( double ) creates a temporary double-precision, floating-point copy of its operand. 27. A value that contains a fractional part is referred to as a floating-point number and is represented by the types float or double.

Chapter 4 Control Statements: Part 1 105 Prelab Activities Short Answer Short Answer Date: Section: Answer the following questions in the space provided. Your answers should be concise; aim for two or three sentences. 28. Explain the purpose of a selection statement. Selection statements choose among alternative actions in a program. They check for certain conditions in a program, and perform different tasks if those conditions are met. 29. Use pseudocode or a UML activity diagram to give an example of sequence control statements. Add this grade into the running total Add one to the grade counter 30. Describe the term algorithm and why pseudocode can help programmers develop algorithms. An algorithm is a procedure for solving a problem in terms of the actions to execute and the order in which the actions should execute. Pseudocode helps in the development of algorithms because it forces you to think out a program during the design process, then you can translate the pseudocode into Java code. 31. Use pseudocode or a UML activity diagram to give an example of an if else selection statement. If student s grade is greater than or equal to 60 Print Passed Else Print Failed 32. Explain the difference between the if selection statement and the if else selection statement. The if selection statement performs an indicated action only when the given condition evaluates to true, otherwise the action is skipped. The if else selection statement allows an action to be performed when the condition is true, and a separate action if the condition is false. 33. Use pseudocode to give an example of a looping construct in which the number of repetitions is known in advance. While student counter is less than or equal to 10 Prompt the user to enter the next exam result

106 Control Statements: Part 1 Chapter4 Prelab Activities Short Answer Input the next exam result Add the grade to the running total Add one to student counter 34. Use pseudocode to give an example of a looping construct in which the number of repetitions is not known in advance. Prompt the user to enter the first grade Input the first grade (possibly the sentinel) While the user has not yet entered the sentinel Add this grade into the running total Add one to the grade counter Prompt the user to enter the next grade Input the next grade (possibly the sentinel) 35. Explain how repetition statements are used. Repetition statements specify that an action (or set of actions) should be performed repeatedly while a condition remains true. 36. Explain the difference between counter-controlled and sentinel-controlled repetition. Counter-controlled repetition is used when the number of repetitions is known in advance. Sentinel-controlled repetition is used when the number of repetitions is not known in advance. In this case, a sentinel value specifies when the repetition should terminate.

Chapter 4 Control Statements: Part 1 107 Prelab Activities Programming Output Programming Output Date: Section: For each of the given program segments, read the code and write the output in the space provided below each program. [ Note: Do not execute these programs on a computer.] For questions 37 39 assume the following class definition: 1 public class Test2 2 { 3 public static void main( String args[] ) 5 Scanner input = new Scanner(); 6 int number1; 7 8 System.out.println( "Enter an integer:" ); 9 number1 = input.nextint(); 10 11 if ( number1 % 2 == 0 ) 12 System.out.println( "%d is even\n", number1 ); 13 else 14 System.out.println( "%d is odd\n", number1 ); 15 } // end main 16 } // end class Test2 37. What will be output by lines 11 14 if the user enters the integer 2 at line 9? Your answer: 2 is even 38. What will be output by lines 11 14 if the user enters the integer 3 at line 9? Your answer: 3 is odd 39. What will be the output if the following code is placed at line 10 of the preceding class definition? Assume that the user enters 5. 1 number1 = number1 + 3 ;

108 Control Statements: Part 1 Chapter4 Prelab Activities Programming Output Your answer: 8 is even 40. What is output by the following program? 1 public class Grade 2 { 3 public static void main( String args[] ) 5 int grade1 = 65; 6 int grade2 = 50; 7 8 System.out.println( grade1 >= 60? "Passed." : "Failed." ); 9 System.out.println( grade2 >= 60? "Passed." : "Failed." ); 10 } // end main 11 } // end class Grade Your answer: Passed Failed For questions 41 43, assume the following class declaration: 1 public class Value 2 { 3 public static void main( String args[] ) 5 int x; 6 int xlimit; 7 8 /* assign values to x and xlimit here */ 9 10 while ( x <= xlimit ) 11 { 12 x++; 13 System.out.printf( "The value of x is %d\n", x ); 14 } // end while 15 16 System.out.printf( "The final value of x is %d\n", x ); 17 } // end main 18 } // end class Value

Chapter 4 Control Statements: Part 1 109 Prelab Activities Programming Output 41. What will be the output if the following code is placed at line 8 of the class? 1 x = 1 ; 2 xlimit = 5 ; Your answer: The value of x is 2 The value of x is 3 The value of x is 4 The value of x is 5 The value of x is 6 The final value of x is 6 42. What will be the output if the following code is placed at line 8 of the class? 1 x = 1 ; 2 xlimit = -2; Your answer: The final value of x is 1 43. What will be the output if the following code is placed at line 8 of the class? 1 x = 10; 2 xlimit = 5 ; Your answer: The final value of x is 10

110 Control Statements: Part 1 Chapter4 Prelab Activities Programming Output For questions 44 46, assume the following class declaration: 1 public class Value 2 { 3 public static void main( String args[] ) 5 int x; 6 int xlimit; 7 8 /* assign values to x and xlimit here */ 9 10 while ( x <= xlimit ) 11 { 12 x++; 13 14 if ( x % 2 == 0 ) 15 System.out.printf( "%d is even.\n", x ); 16 else 17 System.out.printf( "%d is odd.\n", x ); 18 } // end while 19 } // end main 20 } // end class Value 44. What will be the output if the following code is placed at line 8 of the class? 1 x = 0 ; 2 xlimit = 10; Your answer: 1 is odd. 2 is even. 3 is odd. 4 is even. 5 is odd. 6 is even. 7 is odd. 8 is even. 9 is odd. 10 is even. 11 is odd. 45. What will be the output if the following code is placed at line 8 of the class? 1 x = 0 2 xlimit = -2; Your answer: (no output)

Chapter 4 Control Statements: Part 1 111 Prelab Activities Programming Output 46. What will be the output if the following code is placed at line 8 of the class? 1 x = 10; 2 xlimit = 5 ; Your answer: (no output)

Chapter 4 Control Statements: Part 1 113 Prelab Activities Correct the Code Correct the Code Date: Section: Determine if there is an error in each of the following program segments. If there is an error, specify whether it is a logic error or a compilation error, circle the error in the program and write the corrected code in the space provided after each problem. If the code does not contain an error, write no error. [ Note: There may be more than one error in each program segment.] 47. The following segment of code should calculate whether a student has a passing grade. If so, the code should print "Passed." Otherwise, the code should print "Failed." and "You must take this course again." 1 if ( grade >= 60 ) 2 System.out.println( "Passed." ); 3 else 4 System.out.println( "Failed." ); 5 System.out.println( "You must take this course again." ); Your answer: 1 if ( grade >= 60 ) 2 System.out.println( "Passed." ); 3 else 5 System.out.println( "Failed." ); 6 System.out.println( "You must take this course again." ); 7 } Missing braces before line 4 and after line 5. Logic error. 48. The following while loop should compute the product of all the integers between 1 and 5, inclusive. 1 int i = 1 ; 2 int product = 1 ; 3 4 while ( i <= 5 ); 5 product *= i;

114 Control Statements: Part 1 Chapter4 Prelab Activities Correct the Code Your answer: 1 int i = 1 ; 2 int product = 1 ; 3 4 while ( i <= 5 ); 5 { 6 product *= i; 7 i++; 8 } The value of variable i is not incremented in the while loop. Logic error. The semicolon after the while loop s header must be removed. Logic error. 49. The following while loop should print all the even integers between 0 and 20, inclusive. 1 int i = 0 ; 2 3 while ( i <= 20 ) 4 5 if ( i % 2 = 0 ) 6 System.out.printf( "%d ", i ); 7 8 i++ Your answer: 1 int i = 0 ; 2 3 while ( i <= 20 ) 5 if ( i % 2 = 0 ) 6 System.out.printf( "%d ", i ); 7 8 i++ 9 } Missing braces on lines 4 and 9. Variable i must be incremented within the while loop or the program will enter an infinite loop. Logic error. 50. The following while loop should print the numbers 0 through 5, inclusive. 1 int i = 0 ; 2 3 while ( i < 5 ) 5 System.out.printf( "%d ", i ); 6 i++; 7 }

Chapter 4 Control Statements: Part 1 115 Prelab Activities Correct the Code Your answer: 1 int i = 0 ; 2 3 while ( i <= 5 ) 5 System.out.printf( "%d ", i ); 6 i++; 7 } The if statement on line 3 should use the <= operator. Otherwise, the loop will not print i when it is equal to 5. Logic error. 51. The following while loop should print the even numbers from 20 down through 0, inclusive. 1 int i = 20; 2 3 while ( i >= 0 ) 5 if ( i % 2 == 0 ) 6 System.out.printf( "%d ", i ); 7 8 i++; 9 } 10 Your answer: 1 int i = 20; 2 3 while ( i >= 0 ) 5 if ( i % 2 == 0 ) 6 System.out.printf( "%d ", i ); 7 8 i--; 9 } 10 Variable i should be decremented on line 8. If the value is incremented, the program will enter an infinite loop. Logic error.

116 Control Statements: Part 1 Chapter4 Prelab Activities Correct the Code 52. The following while loop should print the sum of the integers between 0 and 5, inclusive. 1 int sum = 0 ; 2 3 while ( i <= 5 ) 5 sum += i; 6 i++; 7 } 8 9 System.out.printf( "The sum is: %d\n", sum ); Your answer: 1 int sum = 0 ; 2 int i = 0 ; 3 4 while ( i <= 5 ) 5 { 6 sum += i; 7 i++; 8 } 9 10 System.out.printf( "The sum is: %d\n", sum ); Variable i must be declared and initialized on line 2. Compilation error. 53. The following while loop should print the sum of the odd integers between 0 and 15, inclusive. 1 int sum = 0, i = 0 ; 2 3 while ( i < 15 ) 5 if ( i % 2!= 0 ) 6 sum += i; 7 8 i++; 9 } 10 11 System.out.printf( "The sum is: %d\n", sum );

Chapter 4 Control Statements: Part 1 117 Prelab Activities Correct the Code Your answer: 1 int sum = 0, i = 0 ; 2 3 while ( i <= 15 ) 5 if ( i % 2!= 0 ) 6 sum += i; 7 8 i++; 9 } 10 11 System.out.printf( "The sum is: %d\n", sum ); The while loop should use the <= operator on line 3 so that the loop runs when i is equal to 15. Logic error. 54. The following while loop should print the product of the odd integers between 0 and 10, inclusive. 1 int product = 1, i = 0 ; 2 3 while ( i <= 10 ) 5 if ( i % 2!= 0 ) 6 i *= product; 7 8 product++; 9 } 10 11 System.out.printf( "The product is: %d\n", product ); Your answer: 1 int product = 1, i = 0 ; 2 3 while ( i <= 10 ) 5 if ( i % 2!= 0 ) 6 product *= i; 7 8 i++; 9 } 10 11 System.out.printf( "The product is: %d\n", product ); The program should multiply product by i during each iteration of the while loop. The while loop should then increment i. Logic error.

Chapter 4 Control Statements: Part 1 119 Lab Exercises Lab Exercise 1 Credit Date: Section: The following problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. The problem is divided into six parts: 1. Lab Objectives 2. Description of the Problem 3. Sample Output 4. Program Template (Fig. L 4.1 and Fig. L 4.2) 5. Problem-Solving Tips 6. Follow-Up Questions and Activities The program template represents a complete working Java program with one or more key lines of code replaced with comments. Read the problem description and examine the sample output, then study the template code. Using the problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute the program. Compare your output with the sample output provided. Then answer the follow-up questions. The source code for the template is available at www.deitel.com/books/jhtp7/ and www.prenhall.com/deitel. Lab Objectives This lab was designed to reinforce programming concepts from Chapter 4 of Java How to Program: Seventh Edition. In this lab, you will practice: Writing pseudocode. Using selection statements. The follow-up questions and activities also will give you practice: Using counter-controlled repetition. Description of the Problem Develop a Java application that will determine whether any of several department-store customers has exceeded the credit limit on a charge account. For each customer, the following facts are available: a) account number b) balance at the beginning of the month c) total of all items charged by the customer this month d) total of all credits applied to the customer s account this month e) allowed credit limit. The program should input all of these facts as integers, calculate the new balance ( = beginning balance + charges credits), display the new balance and determine whether the new balance exceeds the customer s credit limit. For those customers whose credit limit is exceeded, the program should display the message "Credit limit exceeded".

120 Control Statements: Part 1 Chapter4 Lab Exercises Lab Exercise 1 Credit Sample Output Enter Account Number (or -1 to quit): 1 Enter Balance: 100 Enter Charges: 80 Enter Credits: 25 Enter Credit Limit: 200 New balance is 155 Enter Account Number (or -1 to quit): 2 Enter Balance: 450 Enter Charges: 240 Enter Credits: 300 Enter Credit Limit: v New balance is 390 Enter Account Number (or -1 to quit): 3 Enter Balance: 500 Enter Charges: 300 Enter Credits: 125 Enter Credit Limit: 400 New balance is 675 Credit limit exceeded Enter Account Number (or -1 to quit): -1 Program Template 1 // Lab 1: Credit.java 2 // Program monitors accounts. 3 import java.util.scanner; 4 5 public class Credit 6 { 7 // calculates the balance on several credit accounts 8 public void calculatebalance() 9 { 10 Scanner input = new Scanner( System.in ); 11 12 int account; // account number 13 int oldbalance; // starting balance 14 int charges; // total charges 15 int credits; // total credits 16 int creditlimit; // allowed credit limit 17 int newbalance; // new balance 18 19 System.out.print( "Enter Account Number (or -1 to quit): " ); 20 /* write code to input an integer and store it in account */ 21 22 /* write code to loop while the account number is not -1 */ 23 24 /* write code to input the rest of the customer information. */ 25 26 /* write code to compute the new balance */ 27 Fig. L 4.1 Credit.java. (Part 1 of 2.)

Chapter 4 Control Statements: Part 1 121 Lab Exercises Lab Exercise 1 Credit 28 /* write code that will check if the new balance is greater than the 29 credit limit and output the proper information */ 30 31 /* write code to input a new account number and close the while loop. */ 32 33 } // end method calculatebalance 34 } // end class Credit Fig. L 4.1 Credit.java. (Part 2 of 2.) 1 // Lab 1: CreditTest.java 2 // Test application for class Credit 3 public class CreditTest 5 public static void main(string args[]) 6 { 7 Credit application = new Credit(); 8 application.calculatebalance(); 9 } // end main 10 } // end class CreditTest Fig. L 4.2 CreditTest.java Problem-Solving Tips Solution Top: 1. There are five input values required. But the account number must be input before the loop in order to test whether it is equal to the sentinel value. So there should be six input statements, five in the loop and one before it. 2. Use the formula given in the problem description to compute the new balance. 3. Use an if statement to determine whether newbalance is larger than the customer s creditlimit. If so, indicate that the credit limit was exceeded. 4. Write out your algorithms in pseudocode before writing any code. 5. Be sure to follow the spacing and indentation conventions mentioned in the text. 6. If you have any questions as you proceed, ask your lab instructor for assistance. Determine if each of an arbitrary number of department store customers has exceeded the credit limit on a charge account. First refinement: Input the account number, beginning balance, total charges, total credits, and credit limit for a customer, calculate the customer s new balance and determine if the balance exceeds the credit limit. Then process the next customer.

122 Control Statements: Part 1 Chapter4 Lab Exercises Lab Exercise 1 Credit Second refinement: Input the first customer s account number While the sentinel value (-1) has not been entered for the account number Input the customer s beginning balance Input the customer s total charges Input the customer s total credits Input the customer s credit limit Calculate the customer s new balance Print the new balance If the balance exceeds the credit limit Print "Credit Limit Exceeded" Input the next customer s account number 1 // Lab 1: Credit.java 2 // Program monitors accounts. 3 import java.util.scanner; 4 5 public class Credit 6 { 7 // calculates the balance on several credit accounts 8 public void calculatebalance() 9 { 10 Scanner input = new Scanner( System.in ); 11 12 int account; // account number 13 int oldbalance; // starting balance 14 int charges; // total charges 15 int credits; // total credits 16 int creditlimit; // allowed credit limit 17 int newbalance; // new balance 18 19 System.out.print( "Enter Account Number (or -1 to quit): " ); 20 account = input.nextint(); // read in account number 21 22 // exit if the input is -1 otherwise, proceed with the program 23 while ( account!= -1 ) 2 25 System.out.print( "Enter Balance: " ); 26 oldbalance = input.nextint(); // read in original balance 27 28 System.out.print( "Enter Charges: " ); 29 charges = input.nextint(); // read in charges 30 31 System.out.print( "Enter Credits: " ); 32 credits = input.nextint(); // read in credits 33 34 System.out.print( "Enter Credit Limit: " ); 35 creditlimit = input.nextint(); // read in credit limit 36 37 // calculate and display new balance 38 newbalance = oldbalance + charges - credits; 39 System.out.printf( "New balance is %d\n", newbalance );

Chapter 4 Control Statements: Part 1 123 Lab Exercises Lab Exercise 1 Credit 40 41 // display a warning if the user has exceed the credit limit 42 if ( newbalance > creditlimit ) 43 System.out.println( "Credit limit exceeded" ); 44 45 System.out.print( "\nenter Account Number (or -1 to quit): " ); 46 account = input.nextint(); // read in next account number 47 } // end while 48 } // end method calculatebalance 49 } // end class Credit 1 // Lab 1: CreditTest.java 2 // Test application for class Credit 3 public class CreditTest 5 public static void main(string args[]) 6 { 7 Credit application = new Credit(); 8 application.calculatebalance(); 9 } // end main 10 } // end class CreditTest Follow-Up Questions and Activities 1. Modify the program to use counter-controlled repetition to process 10 accounts. Solution 1 // Lab 1: Credit.java 2 // Program monitors accounts. 3 import java.util.scanner; 4 5 public class Credit 6 { 7 // calculates the balance on several credit accounts 8 public void calculatebalance() 9 { 10 Scanner input = new Scanner( System.in ); 11 12 int account; // account number 13 int oldbalance; // starting balance 14 int charges; // total charges 15 int credits; // total credits 16 int creditlimit; // allowed credit limit 17 int newbalance; // new balance 18 int count = 0 ; // number of accounts entered 19 20 // exit if the input is -1 otherwise, proceed with the program 21 while ( count < 10 ) 22 { 23 System.out.print( "\nenter Account Number: " ); 24 account = input.nextint(); // read in account number 25 26 System.out.print( "Enter Balance: " ); 27 oldbalance = input.nextint(); // read in original balance

124 Control Statements: Part 1 Chapter4 Lab Exercises Lab Exercise 1 Credit 28 29 System.out.print( "Enter Charges: " ); 30 charges = input.nextint(); // read in charges 31 32 System.out.print( "Enter Credits: " ); 33 credits = input.nextint(); // read in credits 34 35 System.out.print( "Enter Credit Limit: " ); 36 creditlimit = input.nextint(); // read in credit limit 37 38 // calculate and display new balance 39 newbalance = oldbalance + charges - credits; 40 System.out.printf( "New balance is %d\n", newbalance ); 41 42 // display a warning if the user has exceed the credit limit 43 if ( newbalance > creditlimit ) 44 System.out.println( "Credit limit exceeded" ); 45 46 count++; // increment number of accounts input 47 } // end while 48 } // end method calculatebalance 49 } // end class Credit 1 // Lab 1: CreditTest.java 2 // Test application for class Credit 3 public class CreditTest 5 public static void main(string args[]) 6 { 7 Credit application = new Credit(); 8 application.calculatebalance(); 9 } // end main 10 } // end class CreditTest

Chapter 4 Control Statements: Part 1 125 Lab Exercises Lab Exercise 1 Credit Enter Account Number: 1 Enter Balance: 100 Enter Charges: 80 Enter Credits: 25 Enter Credit Limit: 200 New balance is 155 Enter Account Number: 2 Enter Balance: 450 Enter Charges: 240 Enter Credits: 300 Enter Credit Limit: 600 New balance is 390 Enter Account Number: 3 Enter Balance: 500 Enter Charges: 300 Enter Credits: 125 Enter Credit Limit: 400 New balance is 675 Credit limit exceeded Enter Account Number: 4 Enter Balance: 0 Enter Charges: 350 Enter Credits: 0 Enter Credit Limit: 375 New balance is 350 Enter Account Number: 5 Enter Balance: 200 Enter Charges: 300 Enter Credits: 200 Enter Credit Limit: 250 New balance is 300 Credit limit exceeded Enter Account Number: 8 Enter Balance: 250 Enter Charges: 50 Enter Credits: 200 Enter Credit Limit: 250 New balance is 100 Enter Account Number: 9 Enter Balance: 500 Enter Charges: 100 Enter Credits: 300 Enter Credit Limit: 300 New balance is 300

126 Control Statements: Part 1 Chapter4 Lab Exercises Lab Exercise 1 Credit Enter Account Number: 10 Enter Balance: 75 Enter Charges: 240 Enter Credits: 125 Enter Credit Limit: 200 New balance is 190 2. Modify the program to use counter-controlled repetition to process the number of accounts specified by the user. The number of accounts should be input before processing any account information. Solution 1 // Lab 1: Credit.java 2 // Program monitors accounts. 3 import java.util.scanner; 4 5 public class Credit 6 { 7 // calculates the balance on several credit accounts 8 public void calculatebalance() 9 { 10 Scanner input = new Scanner( System.in ); 11 12 int account; // account number 13 int oldbalance; // starting balance 14 int charges; // total charges 15 int credits; // total credits 16 int creditlimit; // allowed credit limit 17 int newbalance; // new balance 18 int count = 0 ; // number of accounts entered 19 int number; // number of accounts for user to enter 20 21 System.out.print( "Enter Number of Accounts: " ); 22 account = input.nextint(); // read in number of accounts 23 24 // exit if the input is -1 otherwise, proceed with the program 25 while ( count < number ) 26 { 27 System.out.print( "Enter Account Number: " ); 28 account = input.nextint(); // read in account number 29 30 System.out.print( "Enter Balance: " ); 31 oldbalance = input.nextint(); // read in original balance 32 33 System.out.print( "Enter Charges: " ); 34 charges = input.nextint(); // read in charges 35 36 System.out.print( "Enter Credits: " ); 37 credits = input.nextint(); // read in credits 38 39 System.out.print( "Enter Credit Limit: " ); 40 creditlimit = input.nextint(); // read in credit limit 41 42 // calculate and display new balance

Chapter 4 Control Statements: Part 1 127 Lab Exercises Lab Exercise 1 Credit 43 newbalance = oldbalance + charges - credits; 44 System.out.printf( "New balance is %d\n", newbalance ); 45 46 // display a warning if the user has exceed the credit limit 47 if ( newbalance > creditlimit ) 48 System.out.println( "Credit limit exceeded" ); 49 50 count++; // increment number of accounts input 51 } // end while 52 } // end method calculatebalance 53 } // end class Credit 1 // Lab 1: CreditTest.java 2 // Test application for class Credit 3 public class CreditTest 5 public static void main(string args[]) 6 { 7 Credit application = new Credit(); 8 application.calculatebalance(); 9 } // end main 10 } // end class CreditTest Enter Number of Accounts: 3 Enter Account Number: 1 Enter Balance: 100 Enter Charges: 80 Enter Credits: 25 Enter Credit Limit: 200 New balance is 155 Enter Account Number: 2 Enter Balance: 450 Enter Charges: 240 Enter Credits: 300 Enter Credit Limit: 600 New balance is 390 Enter Account Number: 3 Enter Balance: 500 Enter Charges: 300 Enter Credits: 125 Enter Credit Limit: 400 New balance is 675 Credit limit exceeded

128 Control Statements: Part 1 Chapter4 Lab Exercises Lab Exercise 1 Credit

Chapter 4 Control Statements: Part 1 129 Lab Exercises Lab Exercise 2 Palindromes Lab Exercise 2 Palindromes Date: Section: The following problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. The problem is divided into six parts: 1. Lab Objectives 2. Description of the Problem 3. Sample Output 4. Program Template (Fig. L 4.3 and Fig. L 4.4) 5. Problem Solving Tips 6. Follow-Up Question and Activity The program template represents a complete working Java program with one or more key lines of code replaced with comments. Read the problem description and examine the sample output, then study the template code. Using the problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute the program. Compare your output with the sample output provided. Then answer the follow-up question. The source code for the template is available at www.deitel.com/books/jhtp7/ and www.prenhall.com/deitel. Lab Objectives This lab was designed to reinforce programming concepts from Chapter 4 of Java How to Program: Seventh Edition. In this lab you will practice: Using selection statements. Using sentinel-controlled repetition. Using if else selection statements. The follow-up question and activity will also give you practice: Modifying existing code to perform a similar task. Description of the Problem A palindrome is a sequence of characters that reads the same backward as forward. For example, each of the following five-digit integers is a palindrome: 12321, 55555, 45554 and 11611. Write an application that reads in a five-digit integer and determines whether it is a palindrome. If the number is not five digits long, display an error message and allow the user to enter a new value. Sample Output Enter a 5-digit number: 1234 Number must be 5 digits Enter a 5-digit number: 123456 Number must be 5 digits Enter a 5-digit number: 54345 54345 is a palindrome!!!

130 Control Statements: Part 1 Chapter4 Lab Exercises Lab Exercise 2 Palindromes Program Template 1 // Lab 2: Palindrome.java 2 // Program tests for a palindrome 3 import java.util.scanner; 4 5 public class Palindrome 6 { 7 // checks if a 5-digit number is a palindrome 8 public void checkpalindrome() 9 { 10 Scanner input = new Scanner( System.in ); 11 12 int number; // user input number 13 int digit1; // first digit 14 int digit2; // second digit 15 int digit4; // fourth digit 16 int digit5; // fifth digit 17 int digits; // number of digits in input 18 19 number = 0 ; 20 digits = 0 ; 21 22 /* Write code that inputs a five-digit number. Display an error message 23 if the number is not five digits. Loop until a valid input is received. */ 24 25 /* Write code that separates the digits in the five digit number. Use 26 division to isolate the left-most digit in the number, use a remainder 27 calculation to remove that digit from the number. Then repeat this 28 process. */ 29 30 /* Write code that determines whether the first and last digits are 31 identical and the second and Fourth digits are identical. Output 32 whether or not the original string is a palindrome. */ 33 34 } // end method checkpalindrome 35 } // end class Palindrome Fig. L 4.3 Palindrome.java. 1 // Lab 2: PalindromeTest.java 2 // Test application for class Palindrome 3 public class PalindromeTest 5 public static void main( String args[] ) 6 { 7 Palindrome application = new Palindrome(); 8 application.checkpalindrome(); 9 } // end main 10 } // end class PalindromeTest Fig. L 4.4 PalindromeTest.java

Chapter 4 Control Statements: Part 1 131 Lab Exercises Lab Exercise 2 Palindromes Solution 1 // Lab 2: Palindrome.java 2 // Program tests for a palindrome 3 import java.util.scanner; 4 5 public class Palindrome 6 { 7 // checks if a 5-digit number is a palindrome 8 public void checkpalindrome() 9 { 10 Scanner input = new Scanner( System.in ); 11 12 int number; // user input number 13 int digit1; // first digit 14 int digit2; // second digit 15 int digit4; // fourth digit 16 int digit5; // fifth digit 17 int digits; // number of digits in input 18 19 number = 0 ; 20 digits = 0 ; 21 22 // Ask for a number until it is five digits 23 while ( digits!= 5 ) 2 25 System.out.print( "Enter a 5-digit number: " ); 26 number = input.nextint(); 27 28 if ( number < 100000 ) 29 { 30 if ( number > 9999 ) 31 digits = 5 ; 32 else 33 System.out.println( "Number must be 5 digits" ); 34 } // end if 35 else 36 System.out.println( "Number must be 5 digits" ); 37 } // end while loop 38 39 // get the digits 40 digit1 = number / 10000; 41 digit2 = number % 10000 / 1000; 42 digit4 = number % 10000 % 1000 % 100 / 10; 43 digit5 = number % 10000 % 1000 % 100 % 10; 44 45 // print whether the number is a palindrome 46 System.out.print( number ); 47 48 if ( digit1 == digit5 ) 49 { 50 if ( digit2 == digit4 ) 51 System.out.println( " is a palindrome!!!" ); 52 else 53 System.out.println( " is not a palindrome." ); 54 }

132 Control Statements: Part 1 Chapter4 Lab Exercises Lab Exercise 2 Palindromes 55 else 56 System.out.println( " is not a palindrome." ); 57 } // end method checkpalindrome 58 } // end class Palindrome 1 // Lab 2: PalindromeTest.java 2 // Test application for class Palindrome 3 public class PalindromeTest 5 public static void main( String args[] ) 6 { 7 Palindrome application = new Palindrome(); 8 application.checkpalindrome(); 9 } // end main 10 } // end class PalindromeTest Problem-Solving Tips 1. Determine the number of digits in the value input by the user and assign the result to digits. Use a while loop to determine whether the user input contains the proper number of digits. In the condition, determine whether digits is equal to five. If not, input a new value from the user and determine whether the new value contains the proper number of digits. When the number of digits is five, the loop should terminate. 2. Use division and remainder calculations to obtain the separate digits. For a five-digit number to be a palindrome, the first and fifth digits must be the same and the second and fourth digits must be the same. 3. Be sure to follow the spacing and indentation conventions mentioned in the text. 4. If you have any questions as you proceed, ask your lab instructor for assistance. Follow-Up Question and Activity 1. Modify the program to determine whether a seven-digit number is a palindrome. Solution 1 // Lab 2: Palindrome.java 2 // Program tests for a palindrome 3 import java.util.scanner; 4 5 public class Palindrome 6 { 7 // checks if a 5-digit number is a palindrome 8 public void checkpalindrome() 9 { 10 Scanner input = new Scanner( System.in ); 11 12 int number; // user input number 13 int digit1; // first digit 14 int digit2; // second digit 15 int digit3; // third digit 16 int digit5; // fifth digit 17 int digit6; // sixth digit

Chapter 4 Control Statements: Part 1 133 Lab Exercises Lab Exercise 2 Palindromes 18 int digit7; // seventh digit 19 int digits; // number of digits in input 20 21 number = 0 ; 22 digits = 0 ; 23 24 // Ask for a number until it is seven digits 25 while ( digits!= 7 ) 26 { 27 System.out.print( "Enter a 7-digit number: " ); 28 number = input.nextint(); 29 30 if ( number < 10000000 ) 31 { 32 if ( number > 999999 ) 33 digits = 7 ; 34 else 35 System.out.println( "Number must be 7 digits" ); 36 } // end if 37 else 38 System.out.println( "Number must be 7 digits" ); 39 } // end while loop 40 41 // get the digits 42 digit1 = number / 1000000; 43 digit2 = number % 1000000 / 100000; 44 digit3 = number % 100000 / 10000; 45 digit5 = number % 1000 / 100; 46 digit6 = number % 100 / 10; 47 digit7 = number % 10; 48 49 // print whether the number is a palindrome 50 System.out.print( number ); 51 52 if ( digit1 == digit7 ) 53 { 54 if ( digit2 == digit6 ) 55 { 56 if ( digit3 == digit5 ) 57 System.out.println( " is a palindrome!!!" ); 58 else 59 System.out.println( " is not a palindrome." ); 60 } 61 else 62 System.out.println( " is not a palindrome." ); 63 } 64 else 65 System.out.println( " is not a palindrome." ); 66 } // end method checkpalindrome 67 } // end class Palindrome 1 // Lab 2: PalindromeTest.java 2 // Test application for class Palindrome 3 public class PalindromeTest 5 public static void main( String args[] ) 6 {

134 Control Statements: Part 1 Chapter4 Lab Exercises Lab Exercise 2 Palindromes 7 Palindrome application = new Palindrome(); 8 application.checkpalindrome(); 9 } // end main 10 } // end class PalindromeTest Enter a 7-digit number: 7654567 7654567 is a palindrome!!! Enter a 7-digit number: 7654321 7654321 is not a palindrome.

Chapter 4 Control Statements: Part 1 135 Lab Exercises Lab Exercise 3 Largest Number Lab Exercise 3 Largest Number Date: Section: The following problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. The problem is divided into six parts: 1. Lab Objectives 2. Description of the Problem 3. Sample Output 4. Program Template (Fig. L 4.5 and Fig. L 4.6) 5. Problem-Solving Tips 6. Follow-Up Question and Activity The program template represents a complete working Java program with one or more key lines of code replaced with comments. Read the problem description and examine the sample output, then study the template code. Using the problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute the program. Compare your output with the sample output provided. Then answer the follow-up question. The source code for the template is available at www.deitel.com/books/jhtp7/ and www.prenhall.com/deitel. Lab Objectives This lab was designed to reinforce programming concepts from Chapter 4 of Java How to Program: Seventh Edition. In this lab you will practice: Using while statements Using counter-controlled repetition Using if statements The follow-up question and activity also will give you practice: Using if else statements. Description of the Problem The process of finding the largest value (i.e., the maximum of a group of values) is used frequently in computer applications. For example, a program that determines the winner of a sales contest would input the number of units sold by each salesperson. The salesperson who sells the most units wins the contest. Write a pseudocode program and then a Java application that inputs a series of 10 integers and determines and prints the largest integer. Your program should use at least the following three variables: a) counter: A counter to count to 10 (i.e., to keep track of how many numbers have been input and to determine when all 10 numbers have been processed). b) number: The integer most recently input by the user. c) largest: The largest number found so far.

136 Control Statements: Part 1 Chapter4 Lab Exercises Lab Exercise 3 Largest Number Sample Output Enter number: 56 Enter number: -10 Enter number: 200 Enter number: 25 Enter number: 8 Enter number: 500 Enter number: -20 Enter number: 678 Enter number: 345 Enter number: 45 Largest number is 678 Program Template 1 // Lab 3: Largest.java 2 // Program determines and prints the largest of ten numbers. 3 import java.util.scanner; 4 5 public class Largest 6 { 7 // determine the largest of 10 numbers 8 public void determinelargest() 9 { 10 Scanner input = new Scanner( System.in ); 11 12 int largest; // largest number 13 int number; // user input 14 int counter; // number of values entered 15 16 /* write code to get the first integer and store it in variable largest */ 17 18 /* write code to initialize the number of integers entered */ 19 20 /* write code to loop until 10 numbers are entered */ 21 22 /* write code to prompt the user to enter a number and read tat number */ 23 24 /* write code to test whether the number entered is greater than the largest 25 if so, replace the value of largest with the entered number */ 26 27 /* write code to increment the number of integers entered */ 28 29 System.out.printf( "Largest number is %d\n", largest ); 30 } // end method determinelargest 31 } // end class Largest Fig. L 4.5 Largest.java

Chapter 4 Control Statements: Part 1 137 Lab Exercises Lab Exercise 3 Largest Number 1 // Lab 3: LargestTest.java 2 // Test application for class Largest 3 public class LargestTest 5 public static void main( String args[] ) 6 { 7 Largest application = new Largest(); 8 application.determinelargest(); 9 } // end main 10 } // end class LargestTest Fig. L 4.6 LargestTest.java Problem-Solving Tips Solution 1. Remember to initialize the count of the number of integers entered. 2. Use an if statement to test whether the number input from the user is larger than the largest number you have stored. 3. Be sure to follow the spacing and indentation conventions mentioned in the text. 4. If you have any questions as you proceed, ask your lab instructor for assistance. 1 // Lab 3: Largest.java 2 // Program determines and prints the largest of ten numbers. 3 import java.util.scanner; 4 5 public class Largest 6 { 7 // determine the largest of 10 numbers 8 public void determinelargest() 9 { 10 Scanner input = new Scanner( System.in ); 11 12 int largest; // largest number 13 int number; // user input 14 int counter; // number of values entered 15 16 / / get first number and assign it to variable largest 17 System.out.print( "Enter number: " ); 18 largest = input.nextint(); 19 20 counter = 1 ; 21 22 // get rest of the numbers and find the largest 23 while ( counter < 10 ) 2 25 System.out.print( "Enter number: " ); 26 number = input.nextint(); 27 28 if ( number > largest ) 29 largest = number; 30 31 counter++; 32 } // end while loop

138 Control Statements: Part 1 Chapter4 Lab Exercises Lab Exercise 3 Largest Number 33 34 System.out.printf( "Largest number is %d\n", largest ); 35 } // end method determinelargest 36 } // end class Largest 1 // Lab 3: LargestTest.java 2 // Test application for class Largest 3 public class LargestTest 5 public static void main( String args[] ) 6 { 7 Largest application = new Largest(); 8 application.determinelargest(); 9 } // end main 10 } // end class LargestTest Follow-Up Question and Activity 1. Modify the program to find the two largest values of the 10 values entered. Solution 1 // Lab 3: TwoLargest.java 2 // Program determines and prints the two largest of ten numbers. 3 import java.util.scanner; 4 5 public class TwoLargest 6 { 7 // determine the two largest of 10 integers 8 public void determinetwolargest() 9 { 10 Scanner input = new Scanner( System.in ); 11 12 int largest; // largest number 13 int nextlargest; // second largest number 14 int number; // user input 15 int counter; // number of values entered 16 17 // get first number and assign it to variable largest 18 System.out.print( "Enter number: " ); 19 largest = input.nextint(); 20 21 // get second number and compare it with first number 22 System.out.print( "Enter number: " ); 23 number = input.nextint(); 24 25 if ( number > largest ) 26 { 27 nextlargest = largest; 28 largest = number; 29 } // end if 30 else 31 nextlargest = number; 32

Chapter 4 Control Statements: Part 1 139 Lab Exercises Lab Exercise 3 Largest Number 33 counter = 2 ; 34 35 // get rest of the numbers and find the largest and nextlargest 36 while ( counter < 10 ) 37 { 38 System.out.print( "Enter number: " ); 39 number = input.nextint(); 40 41 if ( number > largest ) { 42 nextlargest = largest; 43 largest = number; 44 } // end if 45 else if ( number > nextlargest ) 46 nextlargest = number; 47 48 counter++; 49 } // end while loop 50 51 System.out.printf( "Largest number is %d\nsecond largest number is %d\n", 52 largest, nextlargest ); 53 } // end method determinetwolargest 54 } // end class TwoLargest 1 // Lab 3: TwoLargestTest.java 2 // Test application for class TwoLargest 3 public class TwoLargestTest 5 public static void main( String args[] ) 6 { 7 TwoLargest application = new TwoLargest(); 8 application.determinetwolargest(); 9 } // end main 10 } // end class TwoLargestTest Enter number: 56 Enter number: -10 Enter number: 200 Enter number: 25 Enter number: 8 Enter number: 500 Enter number: -20 Enter number: 678 Enter number: 345 Enter number: 45 Largest number is 678

Chapter 4 Control Statements: Part 1 141 Lab Exercises Debugging Debugging Date: Section: The program in this section does not run properly. Fix all the compilation errors, so that the program will compile successfully. Once the program compiles, compare the output to the sample output, and eliminate any logic errors that exist. The sample output demonstrates what the program s output should be once the program s code is corrected. The file is available at www.deitel.com/books/jhtp7/ and at www.prenhall.com/deitel. Sample Output 1 for Fahrenheit to Celsius 2 for Celsius to Fahrenheit 3 to quit: 1 Enter the degrees in Fahrenheit: 212 The temp in Celsius is 100 1 for Fahrenheit to Celsius 2 for Celsius to Fahrenheit 3 to quit: 2 Enter the degrees in Celsius: 100 The temp in Fahrenheit is 212 1 for Fahrenheit to Celsius 2 for Celsius to Fahrenheit 3 to quit: 3 Broken Code 1 // Chapter 4 of Java How To Program 2 // Debugging Problem 3 import java.util.scanner; 4 5 public class Temperature 6 { 7 public static void main( String args[] ) 8 { 9 int option; 10 int degree1; 11 int celsius1; 12 int fahrenheit1; 13 14 Scanner input = new Scanner( System.in ); 15 16 option = 0 ; 17 Fig. L 4.7 Temperature.java. (Part 1 of 2.)

142 Control Statements: Part 1 Chapter4 Lab Exercises Debugging 18 While ( option!= 3 ) 19 20 System.out.printf( "%s\n%s\n%s\n", "1 for Fahrenheit to Celsius", 21 "2 for Celsius to Fahrenheit", "3 to quit:" ); 22 option = input.nextdouble(); 23 24 System.out.println( "Enter the degrees in Fahrenheit: " ); 25 degree1 = input.nextdouble(); 26 27 celsius1 = ( degree1-32 ) * 5 / 9 ; 28 System.out.printf( "The temp in Celsius is %d\n", celsius1 ); 29 30 if ( option == 2 ); 31 32 System.out.println( "Enter the degrees in Celsius: " ); 33 degree1 = input.nextdouble(); 34 35 fahrenheit1 = ( degree1 * 9 / 5 ) + 32; 36 System.out.printf( "The temp in Fahrenheit is %d\n", fahrenheit1 ); 37 } // end while loop 38 } // end method Main 39 } // end class Temperature Fig. L 4.7 Temperature.java. (Part 2 of 2.) Solution 1 // Chapter 4 of Java How To Program 2 // Debugging Problem 3 import java.util.scanner; 4 5 public class Temperature 6 { 7 public static void main( String args[] ) 8 { 9 int option; 10 int degree1; 11 int celsius1; 12 int fahrenheit1; 13 14 Scanner input = new Scanner( System.in ); 15 16 option = 0 ; 17 18 while ( option!= 3 ) 19 { 20 System.out.printf( "%s\n%s\n%s\n", "1 for Fahrenheit to Celsius", 21 "2 for Celsius to Fahrenheit", "3 to quit:" ); 22 option = input. nextint() ; 23 24 25 26 if ( option == 1 ) { System.out.println( "Enter the degrees in Fahrenheit: " ); 27 degree1 = input. nextint() ; 28 29 celsius1 = ( degree1-32 ) * 5 / 9 ; 30 System.out.printf( "The temp in Celsius is %d\n", celsius1 ); 31 }

Chapter 4 Control Statements: Part 1 143 Lab Exercises Debugging 32 else if ( option == 2 ) 33 { 34 System.out.println( "Enter the degrees in Celsius: " ); 35 degree1 = input. nextint() ; 36 37 fahrenheit1 = ( degree1 * 9 / 5 ) + 32; 38 System.out.printf( "The temp in Fahrenheit is %d\n", fahrenheit1 ); 39 40 } } // end while loop 41 } // end method Main 42 } // end class Temperature List of Errors Keyword while is spelled with a an uppercase W on line 18, which is compilation error. The while statement is missing an opening brace on line 19. An if else statement testing for option equal to 1 is omitted. It has been added to line 24 and the else part has been added to the beginning of line 30. Opening (lines 23 and 31) and closing (lines 29 and 37) braces are left out in the if else statement which leads to either a compilation or logic error. The if statement (line 30) has a semicolon after the condition which leads to a logic error. The program should use Scanner method nextint instead of method nextdouble on lines 25 and 33 to input an integer from the user.

Chapter 4 Control Statements: Part 1 145 Postlab Activities Coding Exercises Date: Section: These coding exercises reinforce the lessons learned in the lab and provide additional programming experience outside the classroom and laboratory environment. They serve as a review after you have successfully completed the Prelab Activities and Lab Exercises. For each of the following problems, write a program or a program segment that performs the specified action. 1. Write a Java application that inputs an integer and uses an if statement to determine whether the integer is even and, if it is, prints that number. 1 public class Test2 2 { 3 public static void main( String args[] ) 5 Scanner input = new Scanner( System.in ); 6 int number1; 7 8 System.out.print( "Enter an integer: " ); 9 number1 = input.nextint(); 10 11 if ( number1 % 2 == 0 ) 12 System.out.println( number1 ); 13 } // end main 14 } // end class Test2 Enter an integer: 8 8 2. Write a Java application that inputs an integer and uses an if else statement to determine whether the integer is odd or even. If it is odd, print the number followed by "is odd"; if it is even, print the number followed by "is even". 1 public class Test2 2 { 3 public static void main( String args[] ) 5 Scanner input = new Scanner( System.in ); 6 int number1; 7 8 System.out.print( "Enter an integer: " ); 9 number1 = input.nextint(); 10 11 if ( number1 % 2 == 0 ) 12 System.out.printf( "%d is even\n", number1 ); 13 else 14 System.out.printf( "%d is odd\n", number1 ); 15 } // end main 16 } // end class Test2