In: Computer Science
Create a PoemDriver.java class with a main method. In the main method, create an ArrayList of Poem objects, read in the information from PoemInfo.txt and create Poem objects to populate the ArrayList. After all data from the file is read in and the Poem objects added to the ArrayList- print the contents of the ArrayList. Paste your PoemDriver.java text (CtrlC to copy, CtrlV to paste) into the open space before. You should not change Poem.java or PoemInfo.txt. Watch your time as the quiz will close after 40 minutes and I will not accept email submissions. It is better to paste periodically into the quiz so you turn in something.
I am using Scanner class to take the said .txt file as a input from a predefined path.
Kindly refer below java code snippet:
import java.io.File;
import java.io.FileNotFoundException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Scanner;
public class PoemDriver {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("PoemInfo.txt"));
input.useDelimiter("-|\n");
Product[] products = new Product[0];
//read the .txt file line by line and convert to JAVA objects
while(input.hasNext()) {
int id = input.nextInt();
String department = input.next();
String name = input.next();
double price = Double.valueOf(input.next().substring(1));
int stock = input.nextInt();
Product newProduct = new Product(name, price, department, id, stock);
products = addProduct(products, newProduct);
}
for (Product product : products) {
System.out.println(product);
}
}
private static Product[] addProduct(Product[] products, Product productToAdd) {
Product[] newProducts = new Product[products.length + 1];
System.arraycopy(products, 0, newProducts, 0, products.length);
newProducts[newProducts.length - 1] = productToAdd;
return newProducts;
}
//definition of Product class, you can take anything
public static class Product {
protected String name;
protected double price;
protected String department;
protected int id;
protected int stock;
private static NumberFormat formatter = new DecimalFormat("#0.00");
constructor
public Product(String n, double p, String d, int i, int s) {
name = n;
price = p;
department = d;
id = i;
stock = s;
}
@Override
public String toString() {
return String.format("ID: %d\r\nDepartment: %s\r\nName: %s\r\nPrice: %s\r\nStock: %d\r\n",
id, department, name, formatter.format(price), stock);
}
}
}