Question: Exercise 9-3 Parse a string of product data In this exercise, youll parse a string that contains data for a product and store that data
Exercise 9-3 Parse a string of product data
In this exercise, youll parse a string that contains data for a product and store that data in a Product object.
Review the application
1. Open the project named ch09_ex3_ProductParser in the extra_ex_starts directory.
2. Open the Main and Product classes and review the code. Note that the Main class defines a Product object and a String object that stores the data for a product with each field delimited by a colon (:). However, this code doesnt parse this string and store the data in the Product object.
3. Run the application. At this point, it shouldnt print any product data to the console.
Add the code that parses the string
4. In the Main class, add code that parses the string and gets the three fields that are stored in the string. Then, store this data in the Product object.
5. Run the application and make sure it works correctly. After a successful run, the console should look something like this:
Code: java
Description: Murach's Java Programming
Price: $57.50
Product.Java -------------------------------------------------------------------------------------------------------------
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); } }
Main.java-----------------------------------------------------------------------------------------------------
package murach.ui;
import murach.business.Product;
public class Main {
public static void main(String[] args) { String productString = "java:Murach's Java Programming:57.50"; Product product = new Product(); //TODO: process productString and populate fields of product object System.out.println("Code: " + product.getCode()); System.out.println("Description: " + product.getDescription()); System.out.println("Price: " + product.getPriceFormatted()); } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
