Eager to Code, Enjoy to Debug ~ Embark into Each Stage with Your Heart

August 18, 2008

Chapter 4: Control Statements Part I (Exercise 4.27)

/* Exercise 4.27
* 1. A palindrome is a sequence of characters that reads the same backward as forward.
* 2. Example: 12321, 55555, 45554, 11611
* 3. Reads a five-digit integer
* 4. Determines whether it is a palindrome
* 5. If the number is not five digits long, display an error message and allow the user to enter a new value.
*/

package Exercises;
import java.util.Scanner;

public class Palindromes {
public static void main(String []args)
{
// initialization phase
int number;
Scanner input=new Scanner(System.in);

// prompts for user input and read the input
System.out.println(”Please enter a number in five digits: “);
number=input.nextInt();

// validate whether the input is in five digits
while((String.valueOf(number).length()!=5))
{
System.out.println(”The number is not in five digits. Please enter the number again in five digits:”);
number=input.nextInt();
}

// Check whether the first digit is equal to the last digit:(number/10000==number%10)
// Check whether the second digit is equal to the fourth digit:((number%100)/10==(number%10000/1000))

if((number/10000==number%10)&&((number%100)/10==(number%10000/1000)))
{
System.out.printf(”The entered number %d is a palindrome”,number);
}
else
{
System.out.printf(”The entered number %d is not a palindrome”,number);
}

} // end main
} // end class Palindromes

August 13, 2008

Chapter 4: Control Statements Part I (Exercise 4.26)

I use the following methods to figure out the solutions for the Question 4.26:-

1. Algorithm

2. Replacing the asterisks with the number in the loop to understand the loop process

* Note: If the entered size is 1 or 2, the hollow square cannot be created although the question requires the size range from 1 to 20.

Algorithm

Hollow Square Example

Hollow Square Example

while i less than or equal to 5
print R1C1
// doing last row
if i reaches to R5C1
initialize j to 1
while j less than 5
print R5C2 (*Note: print R5C2 to R5C5 after each increment of j)
increment j to 1
end while
end if
// end of doing last row

// doing first row
while j less than 4
print R1C2 (*Note: print R1C2 to R1C4 after each increment of j)
increment j to 1
if j more than 3 (*Note: start looping from R1C2, when j more than R1C4)
print R1C5
end if
end while
// end of doing first row

// doing middle row
if i more than R1C1 and i less than 5
reset j to 1

while j less than or equal to 3
print the empty space
increment 1 to j
if j equals to C5
print R2C5 (*Note: Print R2C5 to R4C5 when each row reach C5)
end if
end while
end if
// end of doing middle row

increase 1 to i
go to next row
end while


package Exercises;
import java.util.Scanner;

public class HollowSquare {

public static void main(String[] args) {

int size;
int i = 1;
int j = 1;

Scanner input = new Scanner(System.in);
System.out.println(”Enter the side of a square between 3 to 20: “);
size = input.nextInt();

while (i <= size) {
System.out.print(”i:”+i);

if (i == size) {
j = 1;
while (j < size) {
System.out.print(”j:”+j);
j++;
}
}

while (j size - 2) {
System.out.print(”j:”+j);
}
}

if (i > 1 && (i < size)) {
j = 1;
while (j <= size - 2) {
System.out.print(”j:”+j);
j++;
if (j == size - 1) {
System.out.print(”j:”+j);
}
}
}
i++;
System.out.println();
}
}
}

Results:

Enter the side of a square between 3 to 20:
5
i:1j:1j:2j:3j:4
i:2j:1j:2j:3j:4
i:3j:1j:2j:3j:4
i:4j:1j:2j:3j:4
i:5j:1j:2j:3j:4


/* Exercise 4.26
* 1. Prompts the user to enter the size of the side of a square.
* 2. Display a hollow square of that size made of asterisks.
* 3. It should work for squares of all side lengths between 1 and 20.
*/

package Exercises;
import java.util.Scanner;
public class HollowSquare {
public static void main(String[] args) {

// initializing variables in declarations
int size;
int i = 1;
int j = 1;

// create Scanner to obtain input from command window
Scanner input = new Scanner(System.in);

// prompt for input and read the value
System.out.println(”Enter the side of a square between 3 to 20: “);
size = input.nextInt();

/* Input validation
* if input size is less than 3, negative number, or more than 20
* prompt for input again until the input is valid
*/

while ((size < 3) || (size > 20)) {
System.out.println(”Invalid size.Please enter the size between 3 to 20: “);
size = input.nextInt();
}

//while row not reaches the size
while (i <= size) {
/* 1. print ‘*’
* 2. increase 1 to i
* 3. go to next row
*/

System.out.print(”*”);

// when last row = size
if (i == size) {

// reset j to 1
j = 1;

/* when j less than size
* print “*”
* increment 1 to j
* last row, start print from second column
*/

while (j < size) {
System.out.print(”*”);
j++;

} // end while

} // end if

/* first row, start print from second column
* print “*”
* increment 1 to j
*/

while (j < size - 1) {
System.out.print(”*”);
j++;

/* first row, last column
* minus 2 asterisks of the first row (excluded the first row, first column)
* once more than size, print “*”
*/

if (j > size - 2) {
System.out.print(”*”);
} // end if
} // end while

// when reach second row and still less than the size
if (i > 1 && (i < size)) {

// reset j to 1
j = 1;

/* while column less than (size -2)
* minus 2 asterisks from the first column and last column
* display ” “
* increment 1 to j
*/

while (j <= size - 2) {
System.out.print(” “);
j++;

/* when column reaches the size
* minus the first column
* print “*” for last column
*/

if (j == size - 1) {
System.out.print(”j”);
} // end if
} // end while

} // end if

// increment 1 after first row
i++;

// go to next line
System.out.println();

} // end while

} // end main
} // end class

August 12, 2008

Chapter 4: Control Statements Part I (Exercise 4.23)

/*
* Exercise 4.23
* If the value entered is other than 1 or 2, keep looping until the user enters a correct value.
*/

package Exercises;
import java.util.Scanner;

public class ValidateNum {

public static void main(String[] args) {
// create Scanner to obtain input from command window
Scanner input = new Scanner(System.in);

// initializing variables in declarations
int num = 0;

// prompt for input and read the value
System.out.print(”Enter a number: “);
num = input.nextInt();

// process the input validation
while ((num != 1 && num != 2)) {
System.out.println(”You entered a wrong number”);

// prompt user for input and obtain value from user
System.out.print(”Enter a number: “);
num = input.nextInt();

} // end while

// termination phase; prepare and display results
System.out.printf(”You entered a correct number”);

} // end main
} // end class ValidateNum

August 10, 2008

Chapter 4: Control Statements Part I (Exercise 4.22)

/* Exercise 4.22
* Find the two largest value of the 10 values entered
*/

package Exercises;
import java.util.Scanner;

public class CalcTwoLargestNum {
public static void main(String[] args) {
int counter = 0;
int number;
int largest = 0;
int largest2 = 0;
Scanner input = new Scanner(System.in);

while (counter < 10) {
System.out.println(”Enter a number:”);
number = input.nextInt();
if (number > largest) {
largest2 = largest;
largest = number;

} else if (number > largest2)
largest2 = number;

counter = counter + 1;

} // end while

System.out.printf(”The two largest number is %d and %d”, largest, largest2);
} // end main
} // end class CalcLargestNum

Chapter 4: Control Statements Part I (Exercise 4.21)

package Exercises;

public class LoopMultiply {
public static void main(String []args)
{
// initialize phase
int num=0;

// display the table header
System.out.println(”N\t10*N\t100*N\t1000*N”);

// while number is less then five
while(num<5)
{
num=num+1; // increment the number

// display the multiplication table
System.out.printf(”%d\t%d\t%d\t%d”,num,num*10,num*100,num*1000);

// display the next value in a new line
System.out.println();

} // end while
} // end main
} // end class LoopMultiply

/* Output
N 10*N 100*N 1000*N
1    10   100     1000
2    20   200     2000
3    30   300     3000
4    40   400     4000
5    50   500     5000
*/

Chapter 4: Control Statements Part I (Exercise 4.20)

Pseudocode
Initialize counter to zero
Initialize largest to zero

While the counter is less than ten
Add one to the counter
Prompt the user to enter a number
Input the number
If the number is larger than the last input
Store the number into the variable largest

Print the largest number


package Exercises;

import java.util.Scanner;

/* Exercise 4.20
* Purpose: Finding the largest value
* 1. A pseudocode program, A Java application
* 2. Inputs a series of 10 integers
* 3. Determines and prints the largest integer
* 4. Three variables: counter, number, largest
*/

public class CalcLargestNum {

public static void main(String[] args) {
int counter = 0;
int number;
int largest = 0;

Scanner input = new Scanner(System.in);

while (counter < 10) {
counter = counter + 1;

System.out.println(”Enter a number: “);
number = input.nextInt();
if (number > largest) {
largest = number;
} // end if
} // end while

System.out.printf(”The largest number is %d”, largest);
} // end main
} // end class CalcLargestNum

Chapter 4: Control Statements Part I (Exercise 4.19)

/* Exercise 4.19
* Purpose: determine the gross pay for each of three employees.
* 1. Pays straight time for the first 40 hours worked by each employee and time
* 2. Pays a half for all hours worked in excess of 40 hours
* 3. Input the employee id, employee name, number of hours each employee worked, hourly rate for each employee.
* 4. Determine and display the employee’s gross pay
*/

package Exercises;
import java.util.Scanner;
public class CalcEmployeePay {
private String calcName; // name of calculation this CalcEmployeePay represents

// constructor initializes calcName
public CalcEmployeePay(String name)
{
calcName=name; // initializes calcName
} // end constructor

// method to set the name of this calculation
public void setCalcEmployeePay(String name)
{
calcName=name; // store the application name
} // end method setCalcName

// method to retrieve the application name
public String getCalcEmployeePay()
{
return calcName;
} // end method getCalcName

// display a welcome message to the CalcEmployeePay user
public void displayMessage()
{
//getCalcName gets the name of this calculation
System.out.printf(”Welcome to the %s\n\n”,getCalcEmployeePay());
} // end method displayMessage

// calculate the employee gross pay
public void determineEmployeePay(){

// create Scanner to obtain input from command window
Scanner input = new Scanner(System.in);

// initialization phase
int empId; // employee ID value
double workedHours = 0.0; // employee’s working hours
double hourRate = 0.0; // hour rate for the working hour

int empCounter = 0; // number of employee
double empSal; // employee gross pay

// processing phase
// prompts for input and read employee id from the user

System.out.print(”Please enter the employee ID or -1 to quit: “);
empId = input.nextInt();

// loop until sentinel value read from user
// if employee id is not sentinel value, prompt for next input
// else get out of the loop

while (empId != -1) {
empCounter = empCounter + 1; // increment counter

// prompt for input and read working hours from the user
System.out.print(”Please enter the working hours: “);
workedHours = input.nextDouble();

// prompt for input and read hour rate from the user
System.out.print(”Please enter the hour rate: “);
hourRate = input.nextDouble();

// calculate gross pay of the employee
if (workedHours <= 40)
empSal = workedHours * hourRate;
else
empSal = (workedHours * hourRate) + ((workedHours - 40) * 0.5);

// display the calculated gross pay
System.out.printf(”Total gross pay is %.2f\n”, empSal);

// prompt and read for the next employee id
System.out.print(”Please enter the employee ID or -1 to quit: “);
empId = input.nextInt();
}

// termination phase
// if user entered at least one employee…

if (empCounter != 0)

// display the total entered employee
System.out.printf(”Total of entered employee is %d\n”, empCounter);

else // no employee is entered, so output approprate message
System.out.println(”No employee entered”);

}
}


********** CalcEmployeePayTest. java **********

package Exercises;

public class CalcEmployeePayTest {
public static void main(String []args)
{
// create CalcEmployeePay object myCalcEmployeePay and
// pass program name to constructor

CalcEmployeePay myCalcEmployeePay=new CalcEmployeePay(”Employee Gross Pay Calculation”);
myCalcEmployeePay.displayMessage(); // display welcome message
myCalcEmployeePay.determineEmployeePay(); // calculate employee gross pay
}
}

Chapter 4: Control Statements Part I (Exercise 4.18)

/* Exercise 4.18
* Purpose: Calculate the salesperson’s earnings
* 1. Receive $200 per week + 9% of their gross sales for that week
* 2. Input one salesperson’s items sold for last week
* 3. Calculates and displays that salesperson’s earnings
* 4. No limit to the number of items that can be sold by a salesperson
*/

package Exercises;
import java.util.Scanner;
public class CalcSalesEarning {
private String calcName; // name of calculation this CalcCreditLimit represents

// constructor initializes calcName
public CalcSalesEarning(String name) {
calcName = name; // initializes calcName
} // end constructor

// method to set the name of this calculation
public void setCalcSalesEarning(String name) {
calcName = name; // store the application name
} // end method setCalcName

// method to retrieve the application name
public String getCalcSalesEarning() {
return calcName;
} // end method getCalcName

// display a welcome message to the CalcSalesEarning user
public void displayMessage() {
//getCalcName gets the name of this calculation
System.out.printf(”Welcome to the %s\n\n”, getCalcSalesEarning());
} // end method displayMessage

// calculate the earning of a salesperson per week, based on the total items sold
public void determineSalesEarning() {

// create Scanner to obtain input from command window
Scanner input = new Scanner(System.in);

// initialization phase
int item; // item value
double priceItem; // value of the item
int totalItem = 0; // total entered item
double totalPriceItem = 0.0; // total price of the entered item
double totalEarning; // total earnings based from the sales

int itemCounter = 0; // number of items

// processing phase
// prompt for input and read item number from user

System.out.println(”Please enter the item no. or -1 to quit: “);
item = input.nextInt();

// loop until sentinel value read from user
// if item number is not sentinel value, prompt for next input
// else get out of the loop

while (item != -1) {

itemCounter = itemCounter + 1; // increment counter

// prompt for input and read the price of the item
System.out.println(”Please enter the price: “);
priceItem = input.nextInt();

// total entered item
totalItem = totalItem + item;

// total price of the entered item
totalPriceItem = totalPriceItem + priceItem;

// prompt input and read for next item
System.out.println(”Please enter the item no. or -1 to quit: “);
item = input.nextInt();
}

// termination phase
// if user entered at least one item…

if (itemCounter != 0) {

// display total items sold
System.out.printf(”Total items sold is %d\n”, itemCounter);

// display total price of the items sold
System.out.printf(”Total price of items sold is %.2f\n”, totalPriceItem);

// calculate the earning per week
totalEarning = 200 + (0.09 * totalPriceItem);

// display the earnings of a salesperson per week
System.out.printf(”The earnings is %.2f\n”, totalEarning);
} //end if
else // no item entered, so output appropriate message
{
System.out.println(”No item entered”);
}
} // end of method determineSalesEarning()
} // end class CalcSalesEarning


********** CalcSalesEarningTest. java **********

package Exercises;

public class CalcSalesEarningTest {
public static void main(String []args)
{
// create CalcSalesEarning object myCalcSalesEarning and
// pass application name to constructor

CalcSalesEarning myCalcSalesEarning=new CalcSalesEarning(”Sales Earning Calculation”);
myCalcSalesEarning.displayMessage(); // display welcome message
myCalcSalesEarning.determineSalesEarning(); // calculate the sales earning of a salesperson
}

Chapter 4: Control Statements Part I (Exercise 4.17)

/* Exercise 4.17
* Purpose: determine whether customers has exceeded the credit limit on a charge account
* 1. Input the following as intgers:-
* 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
* 2. Calculate the new balance (=beginning balance + charges - credits)
* 3. Display the new balance
* 4. If credit limit is exceeded, display the message “Credit limit exceeded”
*/

package Exercises;

import java.util.Scanner;
public class CalcCreditLimit {

private String calcName; // name of calculation this CalcCreditLimit represents

// constructor initializes calcName
public CalcCreditLimit(String name) {
calcName = name; // initializes calcName
} // end constructor

// method to set the name of this calculation
public void setCalcCreditLimit(String name) {
calcName = name; // store the application name
} // end method setCalcName

// method to retrieve the application name
public String getCalcCreditLimit() {
return calcName;
} // end method getCalcName

// display a welcome message to the CalcCreditLimit user
public void displayMessage() {
//getCalcName gets the name of this calculation
System.out.printf(”Welcome to the %s\n\n”, getCalcCreditLimit());
} // end method displayMessage

// determine whether the customer has exceeded the credit limit
public void determineCreditLimit() {

// create Scanner to obtain input from command window
Scanner input = new Scanner(System.in);

// initialization phase
int accNumber; // account number value
int beginBalance; // balance beginning of the month
int totalChargedItems; // sum of charged items in the month
int totalCredits; // sum of all credits to the customer in this month
int allowCreditLimit; // allow credit limit in the customer’s account

int custCounter = 0; // number of customers entered
int newBalance; // new balance

// processing phase
// prompt for input and read customer account number from user

System.out.println(”Please enter the customer’s account number or -1 to quit: “);
accNumber = input.nextInt();

// loop until sentinel value read from user
// if account number is not sentinel value, prompt for next input
// else get out of the loop

while (accNumber != -1) {

custCounter = custCounter + 1; // increment counter

// prompt for input and read the value of balance at the beginning of the month from user
System.out.println(”Balance at the beginning of the month: “);
beginBalance = input.nextInt();

// prompt for input and read total items charged by the customer in this month from user
System.out.println(”Total items charged by the customer this month: “);
totalChargedItems = input.nextInt();

// prompt for input and read total credits of the account in this month from user
System.out.println(”Total of credits of the customer’s account this month: “);
totalCredits = input.nextInt();

// prompt for input and read allowed credit limit in the account from user
System.out.println(”Allowed credit limit: “);
allowCreditLimit = input.nextInt();

// calculate new balance
newBalance = beginBalance + totalChargedItems - totalCredits;

// display new balance value
System.out.println(”New Balance: $” + newBalance);

// if the new balance is exceed the credit limit, print the message
if (newBalance > allowCreditLimit) {
System.out.println(”Credit limit exceeded”);
}

// prompt for input to read next customer’s account number if no sentinel value being read
System.out.println(”Please enter the customer’s account number or -1 to quit: “);
accNumber = input.nextInt();

} // end while

// termination phase
// if user entered at least one account number…

if (custCounter != 0) {

// calculate total account number or customers entered
System.out.printf(”\nTotal of the customers is %d\n”, custCounter);

} // end if
else // no account number entered, so output appropriate message
System.out.println(”No customers account number entered”);

} // end method determineCreditLimit()
} // end class CalcCreditLimit


********** CalcCreditLimitTest.java **********

package Exercises;
public class CalcCreditLimitTest {

public static void main(String []args)
{
// create CalcCreditLimit object myCalcCreditLimit and
// pass application name to constructor

CalcCreditLimit myCalcCreditLimit=new CalcCreditLimit(”Customer Credit Limit Calculation”);
myCalcCreditLimit.displayMessage(); // display welcome message
myCalcCreditLimit.determineCreditLimit(); // calculate whether exceed credit limit
}
}

Chapter 4: Control Statements Part I (Exercise 4.16)

/* Exercise 4.16
* 1. Input the miles driven and gallons used (both as integers) for each tankful.
* 2. Calculate and display the miles per gallon obtained for each tankful.
* 3. Print the combined miles per gallon obtained for all tankfuls up to this point.
* 4. All averaging calculations should produce floating-point results.
* 5. Use class Scanner and sentinel-controlled repetition to obtain the data from the user.
*
*/

package Exercises;

import java.util.Scanner; // program uses class Scanner

public class CalcMiles {
private String calcName; // name of calculation this CalcMiles represents

// constructor initializes calcName
public CalcMiles(String name)
{
calcName=name; // initializes calcName
} // end constructor

// method to set the name of this calculation
public void setCalcName(String name)
{
calcName=name; // store the application name
} // end method setCalcName

// method to retrieve the application name
public String getCalcName()
{
return calcName;
} // end method getCalcName

// display a welcome message to the CalcMiles user
public void displayMessage()
{
//getCalcName gets the name of this calculation
System.out.printf(”Welcome to the calculation for %s\n\n”,getCalcName());
} // end method displayMessage

// determine the average of the miles/gallons
public void determineMileageAverage()
{

// create Scanner to obtain input from command window
Scanner input = new Scanner(System.in);

// initialization phase
int miles; // miles value
int gallons; // gallons value
int totalMiles = 0; // sum of miles
int totalGallons = 0; // sum of gallons
int milesCounter = 0; // number of miles entered
double averageTotal = 0; // number with decimal point for total miles/gallons
double average = 0; // number with decimal point for each miles/gallons

// processing phase
// prompt for input and read miles and gallons from user

System.out.print(”Please enter the miles driven or -1 to quit: “);
miles = input.nextInt();

System.out.print(”Please enter the gallons used or -1 to quit: “);
gallons = input.nextInt();

// loop until sentinel value read from user
while (miles != -1) {

// if not sentinel value (-1)
// calculate average for each input of miles and gallons entered
// *Note: if average place after the input in the loop, sentinel value will be calculated in the average

average = miles / gallons;
System.out.printf(”The average miles per gallon obtained for the tank: %.2f\n”, average);

totalMiles = totalMiles + miles; // add miles to total
totalGallons = totalGallons + gallons; // add gallons to total
milesCounter = milesCounter + 1; // increment counter

// prompt for input and read next miles and gallons from user
System.out.print(”Please enter the miles driven or -1 to quit: “);
miles = input.nextInt();

System.out.print(”Please enter the gallons used or -1 to quit: “);
gallons = input.nextInt();

} // end while

// termination phase
// if user entered at least one grade…

if (milesCounter != 0) {

// calculate average of all miles/gallons entered
averageTotal = totalMiles / totalGallons;

// display total and average (with two digits of precision)
System.out.printf(”\nTotal of the %d miles is %d\n”, milesCounter, totalMiles);
System.out.printf(”\nTotal of the %d gallons is %d\n”, milesCounter, totalGallons);
System.out.printf(”\nAverage of total miles/gallons is %.2f\n”, averageTotal);
} // end if
else // no miles were entered, so output appropriate message
System.out.println(”No miles and gallons entered”);

} // end method determineMileageAverage()
} // end class CalcMiles


********** CalcMilesTest.java **********

package Exercises;
import Exercises.CalcMiles;

public class CalcMilesTest {
public static void main(String []args)
{
// create CalcMiles object myCalcMiles and
// pass program name to constructor

CalcMiles myCalcMiles=new CalcMiles(”Mileage”);
myCalcMiles.displayMessage(); // display welcome message
myCalcMiles.determineMileageAverage(); // find average miles/gallon
} // end main
} // end class CalcMilesTest

Next Page »

Blog at WordPress.com.