Pages

Wednesday, 27 July 2016

Chapter 5 Exercise 6, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

5.6 (Conversion from miles to kilometers) Write a program that displays the following two tables side by side:



public class ProgrammingEx5_6 {
 
 public static void main(String[] args) {
  final int END = 10;
  final int MILES_START = 20;
 
  // printing table header
  System.out.printf("%-9s%15s", "Miles", "Kilometers");
  System.out.print("\t|\t");
  System.out.printf("%-9s%15s\n", "Kilometers", "Miles");
 
  for (int j = 0, i = 1; i <= END; i++, j += 5) {
   System.out.printf("%-9d%15.3f", i, i * 1.609);
   System.out.print("\t|\t");
   System.out.printf("%-9d%15.3f\n", MILES_START + j,
     (MILES_START + j) / 1.609);
 
  }
 
 }
}

Chapter 5 Exercise 5, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

5.5 (Conversion from kilograms to pounds and pounds to kilograms) Write a program that displays the following two tables side by side:

Kilograms Pounds | Pounds Kilograms
1 2.2 | 20 9.09
3 6.6 | 25 11.36
...
197 433.4 | 510 231.82
199 437.8 | 515 234.09

public class ProgrammingEx5_5 {
 public static void main(String[] args) {
  final int END = 199;
  final int POUND_START = 20;
 
  // printing table header
  System.out.printf("%-9s%15s","Kilograms","Pounds");
  System.out.print("\t|\t");
  System.out.printf("%-9s%15s\n","Pounds","Kilograms");
 
  for (int j=0, i = 1; i <= END; i+=2, j+=5) {
   System.out.printf("%-9d%15.1f", i, i * 2.2);
   System.out.print("\t|\t");
   System.out.printf("%-9d%15.1f\n",POUND_START+j,(POUND_START+j)/2.2);
 
  }
 }
}

Chapter 5 Exercise 4, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

5.4 (Conversion from miles to kilometers) Write a program that displays the following table (note that 1 mile is 1.609 kilometers):

Miles Kilometers
1 1.609
2 3.218
...
9 14.481
10 16.090

public class ProgrammingEx5_4 {
 
 public static void main(String[] args) {
  final int END = 10;
 
  // printing table header
  System.out.printf("%-9s%15s\n", "Miles", "Kilometers");
 
  for (int i = 1; i <= END; i++) {
   System.out.printf("%-9d%15.1f\n", i, i * 1.609);
 
  }
 
 }
 
}

Chapter 5 Exercise 3, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

5.3 (Conversion from kilograms to pounds) Write a program that displays the following table (note that 1 kilogram is 2.2 pounds):

Kilograms Pounds
1             2.2
3             6.6
...
197         433.4
199         437.8

public class ProgrammingEx5_3 {
 
 public static void main(String[] args) {
  final int END = 199;
   
  //printing table header
  System.out.printf("%9s%15s\n","Kilograms","Pounds");
   
  for(int i=1; i<=END;i++ ){
   System.out.printf("%-9d%15.1f\n",i,i*2.2);
    
  }
   
 
 }
 
}

Chapter 5 Exercise 2, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

5.2 (Repeat additions) Listing 5.4, SubtractionQuizLoop.java, generates five random subtraction questions. Revise the program to generate ten random addition questions for two integers between 1 and 15. Display the correct count and test time.

import java.util.Scanner;
 
public class ProgrammingEx5_2 {
 public static void main(String[] args) {
  final int NUMBER_OF_QUESTIONS = 10; // Number of questions
  int correctCount = 0; // Count the number of correct answers
  int count = 0; // Count the number of questions
  long startTime = System.currentTimeMillis();
  String output = ""; // output string is initially empty
  Scanner input = new Scanner(System.in);
 
  while (count < NUMBER_OF_QUESTIONS) {
   // 1. Generate two random single-digit integers
   int number1 = (int) (Math.random() * 16);
   int number2 = (int) (Math.random() * 16);
 
   // 3. Prompt the student to answer “What is number1 + number2?”
   System.out.print("What is " + number1 + " + " + number2 + "? ");
   int answer = input.nextInt();
 
   // 4. Grade the answer and display the result
   if (number1 + number2 == answer) {
    System.out.println("You are correct!");
    correctCount++;
   } else
    System.out.println("Your answer is wrong.\n" + number1 + " + "
      + number2 + " should be " + (number1 + number2));
 
   // Increase the count
   count++;
 
   output += "\n" + number1 + " + " + number2 + "=" + answer
     + ((number1 + number2 == answer) ? " correct" : " wrong");
  }
 
  long endTime = System.currentTimeMillis();
  long testTime = endTime - startTime;
 
  System.out.println("Correct count is " + correctCount
    + "\nTest time is " + testTime / 1000 + " seconds\n" + output);
 }
}

Chapter 5 Exercise 1, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

*5.1 (Count positive and negative numbers and compute the average of numbers) Write a program that reads an unspecified number of integers, determines how many positive and negative values have been read, and computes the total and average of the input values (not counting zeros). Your program ends with the input 0. Display the average as a floating-point number. Here is a sample run


Enter an integer, the input ends if it is 0: 1 2 -1 3 0
The number of positives is 3
The number of negatives is 1
The total is 5.0
The average is 1.25

Enter an integer, the input ends if it is 0: 0
No numbers are entered except 0

import java.util.Scanner;
 
public class ProgrammingEx5_1 {
 
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
  System.out.print("Enter an integer, the input ends if it is 0:");
  int n, countNeg = 0, countPos = 0;
  float sum = 0;
 
  while ((n = input.nextInt()) != 0) {
   sum = sum + n;
 
   if (n > 0) {
    countPos++;
   } else if (n < 0) {
    countNeg++;
   }
 
  }
 
  if (countPos + countNeg == 0) {
   System.out.println("No numbers are entered except 0");
   System.exit(0);
  }
 
  System.out.println("The number of positives is " + countPos);
  System.out.println("The number of negatives is " + countNeg);
  System.out.println("The total is " + sum);
  System.out.println("The average is " + (sum / (countPos + countNeg)));
 
 }
 
}

Chapter 4 Exercise 26, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

*4.26 (Financial application: monetary units) Rewrite Listing 2.10, ComputeChange. java, to fix the possible loss of accuracy when converting a float value to an int value. Read the input as a string such as "11.56". Your program should extract the dollar amount before the decimal point and the cents after the decimal amount using the indexOf and substring methods.

import java.util.Scanner;
 
public class ProgrammingEx4_26 {
  public static void main(String[] args) {   
    // Create a Scanner
    Scanner input = new Scanner(System.in);
 
    // Receive the amount 
    System.out.print(
      "Enter an amount in double, for example 11.56: ");
    String amount = input.next();
    int numberOfOneDollars = Integer.parseInt(amount.substring(0, amount.indexOf('.')));
    int numberOfCents = Integer.parseInt(amount.substring( amount.indexOf('.')+1));
 
 
 
    // Find the number of quarters in the remaining amount
    int numberOfQuarters = numberOfCents / 25;
    numberOfCents = numberOfCents % 25;
 
    // Find the number of dimes in the remaining amount
    int numberOfDimes = numberOfCents / 10;
    numberOfCents = numberOfCents % 10;
 
    // Find the number of nickels in the remaining amount
    int numberOfNickels = numberOfCents / 5;
    numberOfCents = numberOfCents % 5;
 
    // Find the number of pennies in the remaining amount
    int numberOfPennies = numberOfCents;
 
    // Display results
    System.out.println("Your amount " + amount + " consists of"); 
    System.out.println("    " + numberOfOneDollars + " dollars");
    System.out.println("    " + numberOfQuarters + " quarters ");
    System.out.println("    " + numberOfDimes + " dimes"); 
    System.out.println("    " + numberOfNickels + " nickels");
    System.out.println("    " + numberOfPennies + " pennies");
  }
}

Chapter 4 Exercise 25, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

*4.25 (Generate vehicle plate numbers) Assume a vehicle plate number consists of three uppercase letters followed by four digits. Write a program to generate a plate number.

public class ProgrammingEx4_25 {
 
 public static void main(String[] args) {
  //Randomly picking the letters 
  //ASCII code for A-Z is 65-90
  char letter1 = (char) ((int)(Math.random()*26+65));
  char letter2 = (char) ((int)(Math.random()*26+65));
  char letter3 = (char) ((int)(Math.random()*26+65));
   
  int numbers =  (int)(Math.random()*10000);
  //Zeros padding using format method
  String sNumbers = String.format("%04d" ,numbers );
   
  System.out.println("The plate number is " + letter1 + letter2 +letter3 + sNumbers);
   
 
 }
 
}

Chapter 4 Exercise 24, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

*4.24 (Order three cities) Write a program that prompts the user to enter three cities and displays them in ascending order. Here is a sample run:

    Enter the first city: Chicago
    Enter the second city: Los Angeles
    Enter the third city: Atlanta
    The three cities in alphabetical order are Atlanta Chicago Los Angeles

import java.util.Scanner;
 
public class ProgrammingEx4_24 {
 
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
  System.out.print("Enter the first city:");
  String first = input.nextLine();
  System.out.print("Enter the second city:");
  String second = input.nextLine();
  System.out.print("Enter the third city:");
  String third = input.nextLine();
  String temp = "";
 
  if (first.compareTo(second) > 0) {
   temp = second;
   second = first;
   first = temp;
 
  }
  if (second.compareTo(third) > 0) {
   temp = third;
   third = second;
   second = temp;
 
  }
  if (first.compareTo(second) > 0) {
   temp = second;
   second = first;
   first = temp;
 
  }
  System.out.println("The three cities in alphabetical order are "
    + first + " " + second + " " + third);
 }
 
}

Chapter 4 Exercise 23, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

*4.23 (Financial application: payroll) Write a program that reads the following information and prints a payroll statement:

Employee’s name (e.g., Smith)
Number of hours worked in a week (e.g., 10)
Hourly pay rate (e.g., 9.75)
Federal tax withholding rate (e.g., 20%)
State tax withholding rate (e.g., 9%)
A sample run is shown below:
Enter employee's name: Smith
Enter number of hours worked in a week: 10
Enter hourly pay rate: 9.75
Enter federal tax withholding rate: 0.20
Enter state tax withholding rate: 0.09
Employee Name: Smith
Hours Worked: 10.0
Pay Rate: $9.75
Gross Pay: $97.5
Deductions:
Federal Withholding (20.0%): $19.5
State Withholding (9.0%): $8.77
Total Deduction: $28.27
Net Pay: $69.22


import java.util.Scanner;
 
public class ProgrammingEx4_23 {
 
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
  System.out.print("Enter employee's name:");
  String name = input.nextLine();
 
  System.out.print("Enter number of hours worked in a week:");
  double hours = input.nextDouble();
 
  System.out.print("Enter hourly pay rate:");
  double rate = input.nextDouble();
 
  System.out.print("Enter federal tax withholding rate:");
  double ftax = input.nextDouble();
 
  System.out.print("Enter state tax withholding rate:");
  double stax = input.nextDouble();
 
  System.out.println("Employee Name:" + name);
  System.out.println("Hours Worked:" + hours);
  System.out.println("Pay Rate: $" + rate);
  System.out.println("Gross Pay: $" + rate * hours);
  System.out.println("Deduction:");
  System.out.printf("Federal Withholding (%.1f%%): $%.2f\n", ftax * 100,
    ftax * rate * hours);
  System.out.printf("State Withholding (%.1f%%): $%.2f\n", stax * 100,
    stax * rate * hours);
  System.out.printf("Total Deduction: $%.2f\n", (stax + ftax) * rate
    * hours);
  System.out.printf("Net Pay: $%.2f\n", (1 - stax - ftax) * rate * hours);
 
 }
 
}

Chapter 4 Exercise 22, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.





4.22 (Check substring) Write a program that prompts the user to enter two strings and reports whether the second string is a substring of the first string.

Enter string s1: ABCD
Enter string s2: BC
BC is a substring of ABCD

Enter string s1: ABCD
Enter string s2: BDC
BDC is not a substring of ABCD

import java.util.Scanner;
 
public class ProgrammingEx4_22 {
 
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
 
  System.out.print("Enter string s1:");
  String s1 = input.nextLine();
  System.out.print("Enter string s2:");
  String s2 = input.nextLine();
 
  if (s1.contains(s2)) {
   System.out.println(s2 + " is a substring of " + s1);
  } else {
   System.out.println(s2 + " is not a substring of " + s1);
  }
 
 }
 
}

Chapter 4 Exercise 21, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

*4.21 (Check SSN) Write a program that prompts the user to enter a Social Security number in the format DDD-DD-DDDD, where D is a digit. Your program should check whether the input is valid. Here are sample runs:

Enter a SSN: 232-23-5435
232-23-5435 is a valid social security number

Enter a SSN: 23-23-5435
23-23-5435 is an invalid social security number


import java.util.Scanner;
 
public class ProgrammingEx4_21 {
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
 
  System.out.print("Enter a SSN:");
  String s = input.nextLine();
 
  for (int i = 0; i < s.length(); i++) {
   if ((i == 3 || i == 6) && s.charAt(i) == '-') {
    continue;
   }
   if (!Character.isDigit(s.charAt(i))) {
    System.out.println(s + " is an invalid social security number");
    System.exit(0);
   }
  }
 
  System.out.println(s + " is a valid social security number");
 }
 
}

Chapter 4 Exercise 20, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

4.20 (Process a string) Write a program that prompts the user to enter a string and displays its length and its first character.

import java.util.Scanner;
 
public class ProgrammingEx4_20 {
 
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
 
  System.out.print("Enter some string:");
  String s = input.nextLine();
  System.out.println("The string length is " + s.length());
  System.out.println("The first character is " + s.charAt(0));
 
 }
 
}

Chapter 4 Exercise 19, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

4.19 (Business: check ISBN-10) Rewrite the Programming Exercise 3.9 by entering the ISBN number as a string.

import java.util.Scanner;
 
public class ProgrammingEx4_19 {
 
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
 
  System.out.print("Enter the first 9 digits of an ISBN as integer:");
  String isbn = input.next();
  //Ascii code for 0-9 is 48-57
  int d1 = (int)(isbn.charAt(0))-48;
  int d2 = (int)(isbn.charAt(1))-48;
  int d3 = (int)(isbn.charAt(2))-48;
  int d4 = (int)(isbn.charAt(3))-48;
  int d5 = (int)(isbn.charAt(4))-48;
  int d6 = (int)(isbn.charAt(5))-48;
  int d7 = (int)(isbn.charAt(6))-48;
  int d8 = (int)(isbn.charAt(7))-48;
  int d9 = (int)(isbn.charAt(8))-48;
 
  int d10 = (d1 * 1 + d2 * 2 + d3 * 3 + d4 * 4 + d5 * 5 + d6 * 6 + d7 * 7
    + d8 * 8 + d9 * 9) % 11;
 
  System.out.print("The ISBN-10 number is " + d1 + d2 + d3 + d4 + d5 + d6
    + d7 + d8 + d9);
 
  if (d10 == 10) {
   System.out.print('X');
  } else {
   System.out.print(d10);
  }
 
 }
 
}

Chapter 4 Exercise 18, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

*4.18 (Student major and status) Write a program that prompts the user to enter two characters and displays the major and status represented in the characters. The first character indicates the major and the second is number character 1, 2, 3, 4, which indicates whether a student is a freshman, sophomore, junior, or senior. Suppose the following characters are used to denote the majors:

M: Mathematics
C: Computer Science
I: Information Technology
Here is a sample run:

Enter two characters: M1
Mathematics Freshman
Enter two characters: C3
Computer Science Junior
Enter two characters: T3
Invalid input

import java.util.Scanner;
 
public class ProgrammingEx4_18 {
 
 public static void main(String[] args) {
 
  Scanner input = new Scanner(System.in);
  System.out.print("Enter two characters:");
  String in = input.nextLine();
 
  char major = in.charAt(0);
  char level = in.charAt(1);
 
  String sMajor = "";
  String sLevel = "";
 
  switch (major) {
  case 'M':
   sMajor = "Mathematics";
   break;
 
  case 'C':
   sMajor = "Computer Science";
   break;
 
  case 'I':
   sMajor = "Information Technology";
   break;
 
  default:
   System.out.println("Invalid input");
   System.exit(0);
   break;
  }
 
  switch (level) {
  case '1':
   sLevel = "freshman";
   break;
 
  case '2':
   sLevel = "sophomore";
   break;
 
  case '3':
   sLevel = "junior";
   break;
 
  case '4':
   sLevel = "senior";
   break;
 
  default:
   System.out.println("Invalid input");
   System.exit(0);
   break;
  }
  System.out.println(sMajor + " " + sLevel);
 }
}

Chapter 4 Exercise 17, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

*4.17 (Days of a month) Write a program that prompts the user to enter a year and the first three letters of a month name (with the first letter in uppercase) and displays the number of days in the month. Here is a sample run:

    Enter a year: 2001
    Enter a month: Jan
    Jan 2001 has 31 days
   
    Enter a year: 2016
    Enter a month: Feb
    Feb 2016 has 29 days

import java.util.Scanner;
 
public class ProgrammingEX4_17 {
 
 public static void main(String[] args) {
 
  Scanner input = new Scanner(System.in);
  System.out.print("Enter a year:");
  int year = input.nextInt();
 
  System.out.print("Enter a month:");
  String month = input.next();
 
  int days = 0;
 
  switch (month) {
  case "Feb":
   if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
    days = 29;
    break;
   }
   days = 28;
   break;
 
  case "Apr":
  case "Jun":
  case "Sep":
  case "Nov":
   days = 30;
   break;
 
  case "Jan":
  case "Mar":
  case "May":
  case "Jul":
  case "Aug":
  case "Oct":
  case "Dec":
   days = 31;
   break;
 
  default:
   System.out.println("Invalid month.");
   System.exit(0);
 
  }
 
  System.out.println(month + " " + year + " has " + days + " days");
 }
}