1. Write an application that counts by five from 5 through 500 inclusive, and that starts a new line after every multiple of 50 (50, 100, 150, and so on). Save the file as CountByFives.java.

      public class CountByFives { public static void main (String args[]) { final int START = 5; final int STOP = 500; final int NUMBER_PER_LINE = 50; for(int i = START; i <= STOP; i += START) { System.out.print(i + " "); if(i % NUMBER_PER_LINE == 0) System.out.println(); } } }
    2. Modify the CountByFives application so that the user enters the value to count by. Start each new line after 10 values have been displayed. Save the file as CountByAnything.java.

      import java.util.Scanner; public class CountByAnything { public static void main (String args[]) { final int STOP = 500; final int NUMBER_PER_LINE; Scanner keyboard = new Scanner(System.in); int stepValue; System.out.print("Enter number to count by >> "); stepValue = keyboard.nextInt(); NUMBER_PER_LINE = stepValue * 10; for(int i = stepValue; i <= STOP; i += stepValue) { System.out.print(i + " "); if(i % NUMBER_PER_LINE == 0) System.out.println(); } } }
  1. Write an application that asks a user to type an even number or the sentinel value 999 to stop. When the user types an even number, display the message “Good job!” and then ask for another input. When the user types an odd number, display an error message and then ask for another input. When the user types the sentinel value 999, end the program. Save the file as EvenEntryLoop.java.

    import javax.swing.*; public class EvenEntryLoop { public static void main (String args[]) { int number; String entry, message; final int QUIT = 999; entry = JOptionPane.showInputDialog(null, "Enter an even number or " + QUIT + " to quit"); number = Integer.parseInt(entry); while(number != QUIT) { if(number % 2 == 0) message = "Good job!"; else message = number + " is not an even number"; JOptionPane.showMessageDialog(null,message); entry = JOptionPane.showInputDialog(null, "Enter an even number or " + QUIT + " to quit"); number = Integer.parseInt(entry); } } }
  2. Write an application that displays the factorial for every integer value from 1 to 10. A factorial of a number is the product of that number multiplied by each positive integer lower than it. For example, 4 factorial is 4 * 3 * 2 * 1, or 24. Save the file as Factorials.java.

    public class Factorials { public static void main (String args[]) { final int MAX = 10; int factorial; for (int i = 1; i <= MAX; i++) { factorial = i; for(int j = i - 1; j > 0; --j) factorial = factorial * j; System.out.println("The factorial of " + i + " is " + factorial); } } }
  3. Write an application that prompts a user for two integers and displays every integer between them. Display a message if there are no integers between the entered values. Make sure the program works regardless of which entered value is larger. Save the file as Inbetween.java

    import java.util.Scanner; public class Inbetween { public static void main (String args[]) { Scanner kb = new Scanner(System.in); int num1; int num2; int diff; int x; System.out.print("Enter an integer >> "); num1 = kb.nextInt(); System.out.print("Enter another integer >> "); num2 = kb.nextInt(); diff = num1 - num2; if(diff >= -1 && diff <= 1) System.out.println("There are no integers between " + num1 + " and " + num2); else { System.out.print("The numbers between " + num1 + " and " + num2 + " include:"); if(num1 > num2) for(x = num2 + 1; x < num1; ++x) System.out.print(" " + x); else for(x = num1 + 1; x < num2; ++x) System.out.print(" " + x); System.out.println(); } } }
  4. Write an application that displays every perfect number from 1 through 1,000. A perfect number is one that equals the sum of all the numbers that divide evenly into it. For example, 6 is perfect because 1, 2, and 3 divide evenly into it, and their sum is 6; however, 12 is not a perfect number because 1, 2, 3, 4, and 6 divide evenly into it, and their sum is greater than 12. Save the file as Perfect.java.

    public class Perfect { public static void main (String args[]) { final int MAX = 1000; for(int i = 2; i <= MAX; i++) if(perfect(i) == true) System.out.println("The number " + i + " is perfect"); } public static boolean perfect(int n) { int sum = 1; boolean result = false; for (int j = 2; j <= n/2; j++) if (n % j == 0) sum += j; if (sum == n) result = true; return result; } }
  5. Write an application that uses a loop to create the pattern of Os shown in Figure 6-32, in which each O is displayed one additional space to the right. Save the file as DiagonalOs.java.

    public class DiagonalOs { public static void main(String[] args) { final char O_CHAR = 'O'; final char SPACE = ' '; final int ROWS = 10; int spaces = 0; int a, b; for(a = 0; a < ROWS; ++a) { for(b = 0; b < spaces; ++b) System.out.print(SPACE); System.out.println(O_CHAR); ++spaces; } } }
  6. In Chapter 1 you created a program named Triangle in which you displayed a seven-line triangle pattern like the one in Figure 6-33 by using a series of println() statements. Now, using your knowledge of loops, revise the program so that it contains no more than three output statements. Save the file as TriangleWithLoops.java.

    public class TriangleWithLoops { public static void main(String[] args) { final int LINES = 8; int lines; int spaces = 8; int letters = -1; int x; for(lines = 0; lines < LINES; ++lines) { for(x = 0; x < spaces; ++x) System.out.print(" "); for(x = 0; x < letters; ++x) System.out.print("T"); System.out.println(); spaces--; letters += 2; } } }
  7. Write an application that allows a user to enter any number of student quiz scores until the user enters 99. If the score entered is less than 0 or more than 10, display an appropriate message and do not use the score. After all the scores have been entered, display the number of scores entered, the highest score, the lowest score, and the arithmetic average. Save the file as QuizScoreStatistics.java.

    import java.util.*; public class QuizScoreStatistics { public static void main (String args[]) { int score; int total = 0; int count = 0; int highest; int lowest; final int QUIT = 99; final int MIN = 0; final int MAX = 10; Scanner input = new Scanner(System.in); System.out.print("Enter a score >> "); score = input.nextInt(); highest = score; lowest = score; while(score != QUIT) { if(score >= MIN && score <= MAX) { ++count; total += score; if(score > highest) highest = score; if(score < lowest) lowest = score; } else System.out.print("Score must be between " + MAX + " and " + MIN + " "); System.out.print("Enter another score or " + QUIT + " to quit >> "); score = input.nextInt(); } System.out.println(count + " valid scores were entered"); System.out.println("Highest was " + highest); System.out.println("Lowest was " + lowest); System.out.println("Average was " + (total * 1.0 / count)); } }
  8. The Freemont Automobile Factory has discovered that the longer a worker has been on the job, the more parts the worker can produce. Write an application that computes and displays a worker’s anticipated output each month for 24 months assuming the worker starts by producing 4,000 parts and increases production by 6 percent each month. Also display the month in which production exceeds 7,000 parts (when the worker deserves a raise!). Save the file as IncreasedProduction.java.

    public class IncreasedProduction { public static void main (String[] args) { int month; int monthMetGoal = 0; double production = 4_000; double netProfit; final double PRODUCTION_INCREASE = 0.06; final double GOAL = 7_000; final int MONTHS = 24; boolean isGoalMet = false; for(month = 1; month <= MONTHS; ++month) { production += production * PRODUCTION_INCREASE; if(production > GOAL && !isGoalMet) { monthMetGoal = month; isGoalMet = true; } System.out.println("Month " + month + " Predicted production is " + production); } System.out.println("\nThe month in which production exceeds " + GOAL + " is month " + monthMetGoal); } }
    1. Write an application that prompts a user for the number of years the user has until retirement and the amount of money the user can save annually. If the user enters 0 or a negative number for either value, reprompt the user until valid entries are made. Assume that no interest is earned on the money. Display the amount of money the user will have at retirement. Save the file as RetirementGoal.java.

      import java.util.Scanner; public class RetirementGoal { public static void main (String[] args) { Scanner input = new Scanner(System.in); int years; int saveAmount; int total; System.out.print("How many years until retirement? >> "); years = input.nextInt(); while(years <= 0) { System.out.println("Years cannot be 0 or negative"); System.out.print("Please renter years >> "); years = input.nextInt(); } System.out.print("How much can you save annually? >> "); saveAmount = input.nextInt(); while(saveAmount <= 0) { System.out.println("Amount cannot be 0 or negative"); System.out.print("Please renter amount to save annually >> "); saveAmount = input.nextInt(); } total = saveAmount * years; System.out.print("If you save $" + saveAmount + " for " + years + " years, you will have $" + total); } }
    2. Modify the RetirementGoal application to display the amount of money the user will have if the user earns 4% interest on the balance every year. Save the file as RetirementGoal2.java.

      import java.util.Scanner; public class RetirementGoal2 { public static void main (String[] args) { Scanner input = new Scanner(System.in); int years; int saveAmount; int total; final double RATE = 0.04; System.out.print("How many years until retirement? >> "); years = input.nextInt(); while(years <= 0) { System.out.println("Years cannot be 0 or negative"); System.out.print("Please renter years >> "); years = input.nextInt(); } System.out.print("How much can you save annually? >> "); saveAmount = input.nextInt(); while(saveAmount <= 0) { System.out.println("Amount cannot be 0 or negative"); System.out.print("Please renter amount to save annually >> "); saveAmount = input.nextInt(); } total = saveAmount * years; System.out.println("If you save $" + saveAmount + " for " + years + " years without interest, you will have $" + total); double total2 = 0; for(int y = 0; y < years; ++y) { total2 += saveAmount; total2 = total2 + total2 * RATE; } System.out.println("If you save $" + saveAmount + " for " + years + " years, with " + (RATE * 100) + "% interest, you will have $" + total2); } }
  9. Each week, the Pickering Trucking Company randomly selects one of its 30 employees to take a drug test. Write an application that determines which employee will be selected each week for the next 52 weeks. Use the Math. random() function explained in Appendix D to generate an employee number between 1 and 30; you use a statement similar to: testedEmployee = 1 + (int) (Math.random() * 30); After each selection, display the number of the employee to test. Display four employee numbers on each line. It is important to note that if testing is random, some employees will be tested multiple times, and others might never be tested. Run the application several times until you are confident that the selection is random. Save the file as DrugTests.java.

    public class DrugTests { public static void main(String[] args) { int testedEmployee; int week; final int WEEKS = 52; final int EMPLOYEES = 30; for(week = 1; week <= WEEKS; ++week) { testedEmployee = 1 + (int) (Math.random() * EMPLOYEES); System.out.print("week " + week + " Emp # " + testedEmployee + " "); if(week % 4 == 0) System.out.println(); } } }
  10. Assume that the population of Mexico is 128 million and that the population increases 1.01 percent annually. Assume that the population of the United States is 323 million and that the population is reduced 0.15 percent annually. Write an application that displays the populations for the two countries every year until the population of Mexico exceeds that of the United States, and display the number of years it took. Save the file as Population.java.

    public class Population { public static void main(String[] args) { double mexicoPop = 128; double usPop = 323; final double MEXICO_RATE = .0101; final double US_RATE = .0015; int year = 0; System.out.println(" " + "Mexico population U.S. Population"); while(usPop > mexicoPop) { mexicoPop = mexicoPop + mexicoPop * MEXICO_RATE; usPop = usPop - usPop * US_RATE; ++year; System.out.println(year + " " + mexicoPop + " million " + usPop + " million"); } System.out.println("The population of Mexico will exceed the U.S. population in " + year + " years"); System.out.println("The population of Mexico will be " + mexicoPop + " million"); System.out.println("and the population of the U.S. will be " + usPop + " million"); } }
  11. The Huntington High School basketball team has five players named Art, Bob, Cal, Dan, and Eli. Accept the number of points scored by each player in a game and create a bar chart that illustrates the points scored by displaying an asterisk for each point. The output looks similar to the chart in Figure 6-34. Save the file as BarChart.java

    import java.util.Scanner; public class BarChart { public static void main (String[] args) { Scanner input = new Scanner(System.in); int artPoints; int bobPoints; int calPoints; int danPoints; int eliPoints; System.out.print("Enter points earned by Art >> "); artPoints = input.nextInt(); System.out.print("Enter points earned by Bob >> "); bobPoints = input.nextInt(); System.out.print("Enter points earned by Cal >> "); calPoints = input.nextInt(); System.out.print("Enter points earned by Dan >> "); danPoints = input.nextInt(); System.out.print("Enter points earned by Eli >> "); eliPoints = input.nextInt(); System.out.println("\nPoints for Game\n"); drawChart("Art", artPoints); drawChart("Bob", bobPoints); drawChart("Cal", calPoints); drawChart("Dan", danPoints); drawChart("Eli", eliPoints); } public static void drawChart(String name, int points) { System.out.print(name + " "); for(int x = 0; x < points; ++x) System.out.print("*"); System.out.println(); } }
  12. Modify the BarChart program to accept the number of points scored by each player in a season. The bar chart displays one asterisk for each 10 points scored by a player. For example, if a player has scored 48 points, then display four asterisks. Save the program as BarChart2.java.

    import java.util.Scanner; public class BarChart2 { public static void main (String[] args) { Scanner input = new Scanner(System.in); int artPoints; int bobPoints; int calPoints; int danPoints; int eliPoints; final int AMT_EACH_ASTERISK = 10; System.out.println("Enterpoints earned for the season"); System.out.print(" by Art >> "); artPoints = input.nextInt(); System.out.print(" by Bob >> "); bobPoints = input.nextInt(); System.out.print(" by Cal >> "); calPoints = input.nextInt(); System.out.print(" by Dan >> "); danPoints = input.nextInt(); System.out.print(" by Eli >> "); eliPoints = input.nextInt(); System.out.println("\nPoints for Season (each asterisk represents " + AMT_EACH_ASTERISK + " points)\n"); drawChart("Art", artPoints, AMT_EACH_ASTERISK); drawChart("Bob", bobPoints, AMT_EACH_ASTERISK); drawChart("Cal", calPoints, AMT_EACH_ASTERISK); drawChart("Dan", danPoints, AMT_EACH_ASTERISK); drawChart("Eli", eliPoints, AMT_EACH_ASTERISK); } public static void drawChart(String name, int points, int amt_each) { System.out.print(name + " "); for(int x = 0; x < points / amt_each; ++x) System.out.print("*"); System.out.println(); } }
    1. Create a class named Purchase. Each Purchase contains an invoice number, amount of sale, and amount of sales tax. Include set methods for the invoice number and sale amount. Within the set() method for the sale amount, calculate the sales tax as 5% of the sale amount. Also include a display method that displays a purchase’s details. Save the file as Purchase.java.

      public class Purchase { private int invoiceNumber; private double saleAmount; private double tax; private static final double RATE = 0.05; public void setInvoiceNumber(int num) { invoiceNumber = num; } public void setSaleAmount(double amt) { saleAmount = amt; tax = saleAmount * RATE; } public double getSaleAmount() { return saleAmount; } public int getInvoiceNumber() { return invoiceNumber; } public void display() { System.out.println("Invoice #" + invoiceNumber + " Amount of sale: $" + saleAmount + " Tax: $" + tax); } }
    2. Create an application that declares a Purchase object and prompts the user for purchase details. When you prompt for an invoice number, do not let the user proceed until a number between 1,000 and 8,000 has been entered. When you prompt for a sale amount, do not proceed until the user has entered a nonnegative value. After a valid Purchase object has been created, display the object’s invoice number, sale amount, and sales tax. Save the file as CreatePurchase.java.

      import javax.swing.*; public class CreatePurchase { public static void main(String[] args) { Purchase purch = new Purchase(); int num; double amount; String entry; final int LOW = 1000, HIGH = 8000; entry = JOptionPane.showInputDialog(null, "Enter invoice number"); num = Integer.parseInt(entry); while(num <= LOW || num >= HIGH) { entry = JOptionPane.showInputDialog(null, "Invoice number must be between " + LOW + " and " + HIGH + "\nEnter invoice number"); num = Integer.parseInt(entry); } entry = JOptionPane.showInputDialog(null, "Enter sale amount"); amount = Double.parseDouble(entry); while(amount < 0) { entry = JOptionPane.showInputDialog(null, "Enter sale amount"); amount = Double.parseDouble(entry); } purch.setInvoiceNumber(num); purch.setSaleAmount(amount); purch.display(); } }