Topic include object oriented design (Inheritance, Interface, Abstract class)
Suppose you are on the design team for a new e-book reader. What are the primary classes and methods that the Java software for your reader will need? You should include an inheritance diagram for this code, but you don't need to write any actual code. Your software architecture should at least include ways for customers to buy new books, view their list of purchased books, and read their purchased books.
|
Object | EBookReader ├── Book │ ├── PurchasedBook │ └── NewBook ├── Customer │ ├── RegisteredCustomer │ └── GuestCustomer └── Payment ├── CreditCardPayment └── PayPalPayment Here
are some methods that the software should include:
|
|
Most modern Java compilers have optimizers that can detect simple cases when it is logically impossible for certain statements in a program to ever be executed. In such cases, the compiler warns the programmer about the useless code. Write a short Java method that contains code for which it is provably impossible for that code to ever be executed, yet the Java compiler does not detect this fact.
|
Here is an example
of a Java method that contains code that is provably impossible to execute,
yet the Java compiler does not detect this fact:
public static void main(String[] args) { if (false) { System.out.println("This code will never be
executed."); } } In this example, the if statement will never be true because
the condition is always false. However, the Java compiler does not detect
this fact and will still compile the code. |
Write a program that consists of three classes, A, B, and C, such that B extends A and that C extends B. Each class should define an instance variable named "x" (that is, each has its own variable named x). Describe a way for a method in C to access and set A's version of x to a given value, without changing B or C's version.
|
class A { protected int x; public void setX(int value) { this.x = value; } public int getX() { return this.x; } } class B extends A { protected int x; } class C extends B { public void setAVersionOfX(int value) { super.setX(value); } } |
public class A { protected int x; } public class B extends A { } public class C extends B { public void setXInA(int value) { A a = new A(); a.x = value; } } |
Explain why the Java dynamic dispatch algorithm, which looks for the method to invoke for a call obj.foo(), will never get into an infinite loop.
|
The Java dynamic dispatch algorithm will never get into an
infinite loop because it uses a process called “method lookup” to determine
which method to invoke for a given call. When a method is called on an
object, the Java runtime system looks up the method in the object’s class and
its superclasses until it finds the appropriate method to invoke. This
process is done at runtime and is based on the actual type of the object
being referred to, not the reference type. This means that even if there are multiple levels of
inheritance and overriding methods, the Java runtime system will always find
the appropriate method to invoke without getting into an infinite loop. |
Write a Java program that inputs a document and then outputs a bar-chart plot of the frequencies of each alphabet character that appears within that document.
|
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class CharacterFrequencyChart { public static void main(String[] args) { // Input the document Scanner scanner = new Scanner(System.in); System.out.print("Enter the document: "); String document = scanner.nextLine(); scanner.close(); // Calculate character frequencies Map<Character, Integer> frequencyMap = calculateCharacterFrequencies(document); // Generate and display the bar-chart displayBarChart(frequencyMap); } private static Map<Character, Integer> calculateCharacterFrequencies(String document) { Map<Character, Integer> frequencyMap = new HashMap<>(); // Convert the document to lowercase to ignore case sensitivity document = document.toLowerCase(); // Iterate over each character in the document for (char c : document.toCharArray()) { // Consider only alphabet characters if (Character.isAlphabetic(c)) { // Update the frequency count for the character frequencyMap.put(c, frequencyMap.getOrDefault(c, 0) + 1); } } return frequencyMap; } private static void displayBarChart(Map<Character, Integer> frequencyMap) { System.out.println("\nCharacter Frequency Bar Chart:"); // Iterate over each character and its frequency for (Map.Entry<Character, Integer> entry : frequencyMap.entrySet()) { char character = entry.getKey(); int frequency = entry.getValue(); // Display the character and its frequency as a bar chart System.out.print(character + ": "); for (int i = 0; i < frequency; i++) { System.out.print("*"); } System.out.println(); } } } |
Write a Java program that simulates a system that supports the functions of an e-book reader. You should include methods for users of your system to "buy" new books, view their list of purchased books, and read their purchased books. Your system should use actual books, which have expired copyrights and are available on the Internet, to populate your set of available books for users of your system to "purchase" and read.
|
Creating a fully functional e-book reader system that integrates with copyrighted books from the Internet is beyond the scope of a simple Java program. However, I can provide you with a simplified Java program that simulates some basic functions of an e-book reader system, such as buying books, viewing purchased books, and reading them. Please note that this program does not actually download or read copyrighted books, but rather simulates the functionality using placeholder data. |
|
import java.util.ArrayList; import java.util.List; import java.util.Scanner; class Book { private String title; private String author; private String content; public Book(String title, String author, String content) { this.title = title; this.author = author; this.content = content; } public String getTitle() { return title; } public String getAuthor() { return author; } public String getContent() { return content; } } class EbookReader { private List<Book> purchasedBooks; public EbookReader() { purchasedBooks = new ArrayList<>(); } public void buyBook(Book book) { purchasedBooks.add(book); System.out.println("Book purchased successfully: " + book.getTitle()); } public void viewPurchasedBooks() { if (purchasedBooks.isEmpty()) { System.out.println("No purchased books found."); } else { System.out.println("List of purchased books:"); for (Book book : purchasedBooks) { System.out.println(book.getTitle() + " by " + book.getAuthor()); } } } public void readBook(Book book) { System.out.println("Reading book: " + book.getTitle()); System.out.println("Author: " + book.getAuthor()); System.out.println("Content:\n" + book.getContent()); } } public class EbookReaderSystem { public static void main(String[] args) { EbookReader reader = new EbookReader(); Scanner scanner = new Scanner(System.in); // Placeholder data for demonstration purposes Book book1 = new Book("Book Title 1", "Author 1", "Book content 1"); Book book2 = new Book("Book Title 2", "Author 2", "Book content 2"); Book book3 = new Book("Book Title 3", "Author 3", "Book content 3"); // Simulating book purchase reader.buyBook(book1); reader.buyBook(book2); reader.buyBook(book3); // Simulating viewing purchased books reader.viewPurchasedBooks(); // Simulating reading a purchased book System.out.print("Enter the book number to read (1-" + reader.getPurchasedBooks().size() + "): "); int bookNumber = scanner.nextInt(); scanner.nextLine(); // Consume the newline character if (bookNumber >= 1 && bookNumber <= reader.getPurchasedBooks().size()) { Book selectedBook = reader.getPurchasedBooks().get(bookNumber - 1); reader.readBook(selectedBook); } else { System.out.println("Invalid book number."); } scanner.close(); } } |
Define a Polygon interface that has methods area() and perimeter(). Then implement classes for Triangle, Quadrilateral, Pentagon, Hexagon, and Octagon, which implement this interface, with the obvious meanings for the area() and perimeter() methods. Also implement classes, Isosceles Triangle, Equilateral- Triangle, Rectangle, and Square, which have the appropriate inheritance relationships. Finally, write a simple user interface, which allows users to create polygons of the various types, input their geometric dimensions, and then output their area and perimeter. For extra effort, allow users to input polygons by specifying their vertex coordinates and be able to test if two such polygons are similar.
|
import java.util.Scanner; interface Polygon { double area(); double perimeter(); } class Triangle implements Polygon { private double side1; private double side2; private double side3; public Triangle(double side1, double side2, double side3) { this.side1 = side1; this.side2 = side2; this.side3 = side3; } @Override public double area() { // Using Heron's formula to calculate the area of a triangle double s = (side1 + side2 + side3) / 2; return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3)); } @Override public double perimeter() { return side1 + side2 + side3; } } class Quadrilateral implements Polygon { private double side1; private double side2; private double side3; private double side4; public Quadrilateral(double side1, double side2, double side3, double side4) { this.side1 = side1; this.side2 = side2; this.side3 = side3; this.side4 = side4; } @Override public double area() { // Assuming the quadrilateral is not self-intersecting, // we can split it into two triangles and calculate the sum of their areas. double s1 = (side1 + side2 + side3) / 2; double s2 = (side1 + side4 + side3) / 2; double area1 = Math.sqrt(s1 * (s1 - side1) * (s1 - side2) * (s1 - side3)); double area2 = Math.sqrt(s2 * (s2 - side1) * (s2 - side4) * (s2 - side3)); return area1 + area2; } @Override public double perimeter() { return side1 + side2 + side3 + side4; } } class Pentagon implements Polygon { private double side; public Pentagon(double side) { this.side = side; } @Override public double area() { return (Math.sqrt(5 * (5 + 2 * Math.sqrt(5)))) / 4 * side * side; } @Override public double perimeter() { return 5 * side; } } class Hexagon implements Polygon { private double side; public Hexagon(double side) { this.side = side; } @Override public double area() { return (3 * Math.sqrt(3) * side * side) / 2; } @Override public double perimeter() { return 6 * side; } } class Octagon implements Polygon { private double side; public Octagon(double side) { this.side = side; } @Override public double area() { return 2 * (1 + Math.sqrt(2)) * side * side; } @Override public double perimeter() { return 8 * side; } } class IsoscelesTriangle extends Triangle { public IsoscelesTriangle(double base, double sides) { super(base, sides, sides); } } class EquilateralTriangle extends Triangle { public EquilateralTriangle(double side) { super(side, side, side); } } class Rectangle implements Polygon { private double length; private double width; public Rectangle(double length, double width) { this.length = length; this.width = width; } @Override public double area() { return length * width; } @Override public double perimeter() { return 2 * (length + width); } } class Square extends Rectangle { public Square(double side) { super(side, side); } } public class PolygonDemo { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Create polygons based on user input System.out.println("Enter the dimensions of the polygons:"); System.out.println("Triangle (base and two sides):"); double base = scanner.nextDouble(); double side1 = scanner.nextDouble(); double side2 = scanner.nextDouble(); Triangle triangle = new Triangle(base, side1, side2); System.out.println("Quadrilateral (four sides):"); double sideA = scanner.nextDouble(); double sideB = scanner.nextDouble(); double sideC = scanner.nextDouble(); double sideD = scanner.nextDouble(); Quadrilateral quadrilateral = new Quadrilateral(sideA, sideB, sideC, sideD); System.out.println("Pentagon (side length):"); double sidePentagon = scanner.nextDouble(); Pentagon pentagon = new Pentagon(sidePentagon); System.out.println("Hexagon (side length):"); double sideHexagon = scanner.nextDouble(); Hexagon hexagon = new Hexagon(sideHexagon); System.out.println("Octagon (side length):"); double sideOctagon = scanner.nextDouble(); Octagon octagon = new Octagon(sideOctagon); // Output the areas and perimeters of the polygons System.out.println("\nPolygon Details:"); System.out.println("Triangle - Area: " + triangle.area() + ", Perimeter: " + triangle.perimeter()); System.out.println("Quadrilateral - Area: " + quadrilateral.area() + ", Perimeter: " + quadrilateral.perimeter()); System.out.println("Pentagon - Area: " + pentagon.area() + ", Perimeter: " + pentagon.perimeter()); System.out.println("Hexagon - Area: " + hexagon.area() + ", Perimeter: " + hexagon.perimeter()); System.out.println("Octagon - Area: " + octagon.area() + ", Perimeter: " + octagon.perimeter()); scanner.close(); } } |
Write a Java program that inputs a list of words, separated by white-space, and outputs how many times each word appears in the list. You need not worry about efficiency at this point, however, as this topic is something that will be addressed later in this book.
|
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class WordFrequencyCounter { public static void main(String[] args) { // Input the list of words Scanner scanner = new Scanner(System.in); System.out.print("Enter a list of words separated by white-space: "); String input = scanner.nextLine(); scanner.close(); // Remove leading/trailing white-space and split the input into an array of words String[] words = input.trim().split("\\s+"); // Count the frequency of each word Map<String, Integer> frequencyMap = countWordFrequency(words); // Output the word frequencies System.out.println("Word Frequencies:"); for (Map.Entry<String, Integer> entry : frequencyMap.entrySet()) { String word = entry.getKey(); int frequency = entry.getValue(); System.out.println(word + ": " + frequency); } } private static Map<String, Integer> countWordFrequency(String[] words) { Map<String, Integer> frequencyMap = new HashMap<>(); // Iterate over each word in the array for (String word : words) { // Update the frequency count for the word frequencyMap.put(word, frequencyMap.getOrDefault(word, 0) + 1); } return frequencyMap; } } |
Write a Java program that can "make change." Your program should take two numbers as input, one that is a monetary amount charged and the other that is a monetary amount given. It should then return the number of each kind of bill and coin to give back as change for the difference between the amount given and the amount charged. The values assigned to the bills and coins can be based on the monetary system of any current or former government. Try to design your program so that it returns the fewest number of bills and coins as possible.
|
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class ChangeMaker { private static final Map<String, Integer> CURRENCY_MAP = new HashMap<>(); static { // Define the currency denominations and their values CURRENCY_MAP.put("100 bill", 10000); CURRENCY_MAP.put("50 bill", 5000); CURRENCY_MAP.put("20 bill", 2000); CURRENCY_MAP.put("10 bill", 1000); CURRENCY_MAP.put("5 bill", 500); CURRENCY_MAP.put("2 coin", 200); CURRENCY_MAP.put("1 coin", 100); CURRENCY_MAP.put("50 cent coin", 50); CURRENCY_MAP.put("20 cent coin", 20); CURRENCY_MAP.put("10 cent coin", 10); CURRENCY_MAP.put("5 cent coin", 5); CURRENCY_MAP.put("2 cent coin", 2); CURRENCY_MAP.put("1 cent coin", 1); } public static void main(String[] args) { // Input the amount charged and the amount given Scanner scanner = new Scanner(System.in); System.out.print("Enter the amount charged: $"); int amountCharged = (int) (scanner.nextDouble() * 100); // Convert to cents System.out.print("Enter the amount given: $"); int amountGiven = (int) (scanner.nextDouble() * 100); // Convert to cents scanner.close(); // Calculate the difference in amounts int changeAmount = amountGiven - amountCharged; // Make change using the fewest number of bills and coins Map<String, Integer> changeMap = makeChange(changeAmount); // Output the change denominations System.out.println("Change to give back:"); for (Map.Entry<String, Integer> entry : changeMap.entrySet()) { String denomination = entry.getKey(); int count = entry.getValue(); System.out.println(denomination + ": " + count); } } private static Map<String, Integer> makeChange(int changeAmount) { Map<String, Integer> changeMap = new HashMap<>(); // Iterate over each currency denomination in descending order for (Map.Entry<String, Integer> entry : CURRENCY_MAP.entrySet()) { String denomination = entry.getKey(); int value = entry.getValue(); // Calculate the number of bills/coins required for the denomination int count = changeAmount / value; // Update the change amount and changeMap if (count > 0) { changeAmount %= value; changeMap.put(denomination, count); } // If the remaining change amount is zero, break the loop if (changeAmount == 0) { break; } } return changeMap; } } |

0 Comments