Question

Java -Create an interface and implement it In the murach.db package, create an interface named IProductDB....

Java -Create an interface and implement it

  1. In the murach.db package, create an interface named IProductDB. This interface should specify this abstract method:

public abstract Product get(String productCode);

  1. Modify the ProductDB class so it implements the IProductDB interface. Write the code for the new ‘get’ method. Then remove the getProductByCode method.
  2. In the Main class, modify the code so it works with the new ProductDB class. This code should create an instance of the IProductDB interface like this:

IProductDB db = new ProductDB();

This shows that the ProductDB class implements the IProductDB interface.

  1. Run the application to make sure it works correctly.

Modify another class so it implements the interface

  1. In the ProductDB2 class, modify the code so it implements the IProductDB interface. Write the code for the new get method. Remove the getProduct method.
  2. In the Main class, modify the code so it uses ProductDB2, not ProductDB. This should be easy since both classes implement the IProductDB interface.
  3. Run the application to make sure it works correctly.

Create an interface that contains constants and use it

  1. In the murach.db package, add an interface named IProductConstants that contains the three constants that are currently in the Main class. To do that, you can move the code that declares and initializes the constants from the Main class to the interface. In the Main class, make sure to remove the code that declares and initializes the three constants.
  2. Attempt to compile the application. This should display an error message that indicates that constants aren’t available to the Main class.
  3. In the Main class, implement the IProductConstants interface. This should make the constants available to the Main class.
  4. Run the application to make sure that it works correctly.

package murach.ui;

import murach.db.ProductDB;
import murach.business.Product;

public class Main {

public static void main(String args[]) {
ProductDB db = new ProductDB();
System.out.println("Welcome to the Product Lister\n");
  
final int CODE_WIDTH = 10;
final int DESC_WIDTH = 34;
final int PRICE_WIDTH = 10;
  
// set up display string
StringBuilder list = new StringBuilder();
list.append(StringUtil.pad("Code", CODE_WIDTH));
list.append(StringUtil.pad("Description", DESC_WIDTH));
list.append(StringUtil.pad("Price", PRICE_WIDTH));
list.append("\n");

list.append(
StringUtil.pad("=========", CODE_WIDTH));
list.append(
StringUtil.pad("=================================", DESC_WIDTH));
list.append(
StringUtil.pad("=========", PRICE_WIDTH));
list.append("\n");
  
String choice = "y";
while (choice.equalsIgnoreCase("y")) {
// get the input from the user
String productCode = Console.getString("Enter product code: ");

Product product = db.getProductByCode(productCode);
  
list.append(
StringUtil.pad(product.getCode(), CODE_WIDTH));
list.append(
StringUtil.pad(product.getDescription(), DESC_WIDTH));
list.append(
StringUtil.pad(product.getPriceFormatted(), PRICE_WIDTH));
list.append("\n");

// see if the user wants to continue
choice = Console.getString("Another product? (y/n): ");
System.out.println();
}
System.out.println(list);
}
}

----------

package murach.business;

import java.text.NumberFormat;

public class Product {

private String code;
private String description;
private double price;

public Product() {
code = "";
description = "";
price = 0;
}

public Product(String code, String description, double price) {
this.code = code;
this.description = description;
this.price = price;
}

public void setCode(String code) {
this.code = code;
}

public String getCode() {
return code;
}

public void setDescription(String description) {
this.description = description;
}

public String getDescription() {
return description;
}

public void setPrice(double price) {
this.price = price;
}

public double getPrice() {
return price;
}

public String getPriceFormatted() {
NumberFormat currency = NumberFormat.getCurrencyInstance();
return currency.format(price);
}

}

--------

package murach.db;

import murach.business.Product;


public class ProductDB {

public Product getProductByCode(String productCode) {
// In a more realistic application, this code would
// get the data for the product from a file or database
// For now, this code just uses if/else statements
// to return the correct product

// create the Product object
Product product = new Product();

// fill the Product object with data
product.setCode(productCode);
if (productCode.equalsIgnoreCase("java")) {
product.setDescription("Murach's Java Programming");
product.setPrice(57.50);
} else if (productCode.equalsIgnoreCase("jsp")) {
product.setDescription("Murach's Java Servlets and JSP");
product.setPrice(57.50);
} else if (productCode.equalsIgnoreCase("mysql")) {
product.setDescription("Murach's MySQL");
product.setPrice(54.50);
} else {
product.setDescription("Unknown");
}
return product;
}
}

-----

package murach.ui;

import java.util.Scanner;

public class Console {

private static Scanner sc = new Scanner(System.in);
  
public static void displayLine() {
System.out.println();
}

public static void displayLine(String s) {
System.out.println(s);
}

public static String getString(String prompt) {
System.out.print(prompt);
String s = sc.nextLine();
return s;
}

public static int getInt(String prompt) {
int i = 0;
while (true) {
System.out.print(prompt);
try {
i = Integer.parseInt(sc.nextLine());
break;
} catch (NumberFormatException e) {
System.out.println("Error! Invalid integer. Try again.");
}
}
return i;
}

public static double getDouble(String prompt) {
double d = 0;
while (true) {
System.out.print(prompt);
try {
d = Double.parseDouble(sc.nextLine());
break;
} catch (NumberFormatException e) {
System.out.println("Error! Invalid decimal. Try again.");
}
}
return d;
}
}

----

package murach.ui;

public class StringUtil {

public static String pad(String s, int length) {
if (s.length() < length) {
StringBuilder sb = new StringBuilder(s);
while (sb.length() < length) {
sb.append(" ");
}
return sb.toString();
} else {
return s.substring(0, length);
}
}
}

-----

package murach.db;

import murach.business.Product;

public class ProductDB2 {
  
private String[][] productsArray = {
{"java", "Murach's Java Programming", "57.50"},
{"jsp", "Murach's Java Servlets and JSP", "57.50"},
{"android", "Murach's Android Programming", "57.50"},
{"mysql", "Murach's MySQL", "54.50"}
};
  
public Product getProduct(String productCode) {
for (String[] row : productsArray) {
String code = row[0];
if (productCode.equals(code)) {
String description = row[1];
String price = row[2];
Product p = new Product(
code, description, Double.parseDouble(price));
return p;
}
}
return null;
}
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

output:-

Add a comment
Know the answer?
Add Answer to:
Java -Create an interface and implement it In the murach.db package, create an interface named IProductDB....
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • JAVA Need help getting the output of this code to be, by adding another Interface class...

    JAVA Need help getting the output of this code to be, by adding another Interface class : Pumping down chamber... Chamber pumped down and @ 0 torr. HiVac turbo spinning up... HiVac turbo @ speed. Gate valves opening... All gate valves open. Heater power on... Heater starting... Heater at operating temperature. System ready for production. This is the current code: package interfaceSample; import java.util.ArrayList; import java.util.Scanner; //Imports //Begin Class Interface public class Interface {     //Begin Main Method     public...

  • Filename(s): ReformatCode. java Public class: ReformatCode Package-visible class(es): none Write a program that reformats Java source...

    Filename(s): ReformatCode. java Public class: ReformatCode Package-visible class(es): none Write a program that reformats Java source code from the next-line brace style to the end-of-line brace style. The program is invoked from the command line with the input Java source code file as args [0] and the name of the file to save the formatted code in as args [1]. The original file is left untouched. The program makes no other changes the source code, including whitespace. For example, the...

  • Suppose we have the following Java Interface: public interface Measurable {    double getMeasure(); // An...

    Suppose we have the following Java Interface: public interface Measurable {    double getMeasure(); // An abstract method    static double average(Measurable[] objects) { // A static method    double sum = 0;    for (Measurable obj : objects) {    sum = sum + obj.getMeasure();    }    if (objects.length > 0) { return sum / objects.length; }    else { return 0; }    } } Write a class, called Person, that has two instance variables, name (as...

  • JAVA Modify the code to create a class called box, wherein you find the area. I...

    JAVA Modify the code to create a class called box, wherein you find the area. I have the code in rectangle and needs to change it to box. Here is my code. Rectangle.java public class Rectangle { private int length; private int width;       public void setRectangle(int length, int width) { this.length = length; this.width = width; } public int area() { return this.length * this.width; } } // CONSOLE / MAIN import java.awt.Rectangle; import java.util.Scanner; public class Console...

  • Problem 1 1. In the src → edu.neiu.p2 directory, create a package named problem1. 2. Create...

    Problem 1 1. In the src → edu.neiu.p2 directory, create a package named problem1. 2. Create a Java class named StringParser with the following: • A public static method named findInteger that takes a String and two char variables as parameters (in that order) and does not return anything. • The method should find and print the integer value that is located in between the two characters. You can assume that the second char parameter will always follow the first...

  • Code using Java What is an interface? Complete the following code: interface IExample{ public void print();...

    Code using Java What is an interface? Complete the following code: interface IExample{ public void print(); } class Example1 implements IExample{ . . . } // Driver class public class Questions { public static void main(String[] args) { . . . } } To have this message when you execute it: Implementation of an interface

  • JAVA HELP: Directions Write a program that will create an array of random numbers and output...

    JAVA HELP: Directions Write a program that will create an array of random numbers and output the values. Then output the values in the array backwards. Here is my code, I am having a problem with the second method. import java.util.Scanner; import java.util.Random; public class ArrayBackwards { public static void main(String[] args) { genrate(); print(); } public static void generate() { Scanner scanner = new Scanner(System.in);    System.out.println("Seed:"); int seed = scanner.nextInt();    System.out.println("Length"); int length = scanner.nextInt(); Random random...

  • The JCF provides numerous classes that implement the List interface, including LinkedList, ArrayList, and Vector. Write...

    The JCF provides numerous classes that implement the List interface, including LinkedList, ArrayList, and Vector. Write code to show how the JCF class ArrayList and LinkedList are used to maintain a grocery list. Verify List methods such as "add()", get(), "remove()", "isEmpty()" and "size()" by implementing a test program. import java.util.ArrayList; import java.util.Iterator; public class GroceryList { static public void main(String[] args){ ArrayList<String> groceryList = new ArrayList<String>(); Iterator<String> iter;    groceryList.add("apples"); groceryList.add("bread"); groceryList.add("juice"); groceryList.add("carrots"); groceryList.add("ice cream");    System.out.println("Number of items...

  • Problem 1 1. In the src → edu.neiu.p2 → problem1 directory, create a Java class called...

    Problem 1 1. In the src → edu.neiu.p2 → problem1 directory, create a Java class called HW4P1 and add the following: • The main method. Leave the main method empty for now. • Create a method named xyzPeriod that takes a String as a parameter and returns a boolean. • Return true if the String parameter contains the sequential characters xyz, and false otherwise. However, a period is never allowed to immediately precede (i.e. come before) the sequential characters xyz....

  • Need Help ASAP!! Below is my code and i am getting error in (public interface stack)...

    Need Help ASAP!! Below is my code and i am getting error in (public interface stack) and in StackImplementation class. Please help me fix it. Please provide a solution so i can fix the error. thank you.... package mazeGame; import java.io.*; import java.util.*; public class mazeGame {    static String[][]maze;    public static void main(String[] args)    {    maze=new String[30][30];    maze=fillArray("mazefile.txt");    }    public static String[][]fillArray(String file)    {    maze = new String[30][30];       try{...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT