How to read .csv file in Java? - java

I'm trying to read .csv file which can run as per the below options given in program which are:
Enter 1 to output all the information for all of the products in the inventory.
Enter 2 to output all the information for all of the products under a particular category (Bakery, Meat, Produce, Deli, Cleaning).
Enter 3 to add more products to the inventory
My .csv file is below:
MEAT,Chicken breast,14.50,8,2020-03-03,1
PRODUCE,Royal Gala apple,2.5,20,2020-03-20,1.0
MEAT,Chicken kebabs honey soy,9.0,6,2020-03-03,0.48
PRODUCE,Broccoli,2.00,33,2020-03-10,0.4
MEAT,Burger patties,10.00,8,2020-03-08,0.4
MEAT,Lamb loin chop,28.00,12,2020-03-05,0.5
PRODUCE,Nectarine,7.00,9,2020-03-09,1.8
MEAT,Beef premium mince,12.50,16,2020-02-27,0.6
PRODUCE,Avacado,2.35,10,2020-03-07,0.2
PRODUCE,Green grapes,7.00,5,2020-03-01,1.0
I'm able to run the first option and display all the information. I need help in option 2 and option 3.
This is my Main class:
package InventorySystem;
import java.io.FileNotFoundException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
/**
* All that is remaining to do is task 4 & 5:
* 1. Implement the file reading/writing to the csv file.
* hint:- Just save to the csv file on exiting (when the user presses "q") by incrementally
* printing each item in the LocalStore inventory (eg. store.inventory.get(i).toString()).
* Do the opposite when you first run the program, the very first thing program should do
* is read the csv file and incrementally add each line in the file as a new object into the
* inventory ArrayList.
* 2. Implement exception handling for the file reading/writing
* 3. Implement data validation in case the user enters incorrect data
*/
public class Main
{
private static String name,
veganStr = "";
private static double basePrice,
weight;
private static int quantity,
day,
month,
year;
private static boolean vegan = false;
private static LocalStore store = new LocalStore("My Food Store","35 Queen Street",35500);
//method to get the mandatory information to create an Inventory item
private static void getMandatory()
{
System.out.print("Enter the item's name --> ");
name = Keyboard.readInput();
System.out.print("Enter the item's base price --> ");
basePrice = Double.parseDouble(Keyboard.readInput());
System.out.print("Enter the item quantity --> ");
quantity = Integer.parseInt(Keyboard.readInput());
}
//method to get the optional items required for Deli & Bakery items
private static void getOptional()
{
System.out.println("Enter the expiry date --> ");
String date = Keyboard.readInput();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date parsedDate = null;
try {
parsedDate = dateFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.print("Enter the item's weight --> ");
weight = Double.parseDouble(Keyboard.readInput());
}
//method to get the vegan details
private static void getVegan()
{
System.out.print("Is the item suitable for vegans? Y/N --> ");
veganStr = Keyboard.readInput();
if(veganStr.equalsIgnoreCase("y"))
{
vegan = true;
}
}
private static void addDeliItem()
{
getMandatory();
getOptional();
getVegan();
//add the new item
store.inventory.add(new Deli(name,basePrice,quantity,day,month,year,weight,vegan));
}
private static void addBakeryItem()
{
getMandatory();
getOptional();
getVegan();
store.inventory.add(new Bakery(name,basePrice,quantity,day,month,year,weight,vegan));
}
private static void addProduceItem()
{
getMandatory();
getOptional();
store.inventory.add(new Produce(name,basePrice,quantity,day,month,year,weight));
}
private static void addMeatItem()
{
getMandatory();
getOptional();
store.inventory.add(new Meat(name,basePrice,quantity,day,month,year,weight));
}
private static void addCleaningItem()
{
getMandatory();
store.inventory.add(new Cleaning(name,basePrice,quantity));
}
private static void mainMenu() throws FileNotFoundException {
Scanner menuOptionIn = new Scanner(System.in);
Scanner addOptionIn = new Scanner(System.in);
String menuAnswer,
addOption;
boolean cont = true;
while (cont) {
//show the menu to the user
System.out.println("\n---MAIN MENU---\nEnter 1 to output all the information for all of the products in the inventory\n" +
"Enter 2 to output all the information for all of the products under a particular category\n" +
"Enter 3 to add more products to the inventory\n" +
"Enter q to quit the program");
//read the user's input
menuAnswer = menuOptionIn.nextLine();
if (menuAnswer.equals("1") || menuAnswer.equals("2") || menuAnswer.equals("3")) {
switch (menuAnswer) {
case "1":
//output info for all products
store.printAll();
break;
case "2":
//output info for particular category
System.out.println("\nWhat category item would you like to view?\n" +
"Enter 1 for Deli\n" +
"Enter 2 for Bakery\n" +
"Enter 3 for Produce\n" +
"Enter 4 for Meat\n" +
"Enter 5 for Cleaning\n" +
"Enter r to return to the menu");
addOption = addOptionIn.nextLine();
switch (addOption) {
case "1":
store.printType("Deli");
break;
case "2":
store.printType("Bakery");
break;
case "3":
store.printType("Produce");
break;
case "4":
store.printType("Meat");
break;
case "5":
store.printType("Cleaning");
break;
case "r":
//return to the main menu
break;
default:
break;
}
break;
case "3":
//add products
//ask the user to select item group they wish to add
System.out.println("\nWhat category item would you like to add?\n" +
"Enter 1 for Deli\n" +
"Enter 2 for Bakery\n" +
"Enter 3 for Produce\n" +
"Enter 4 for Meat\n" +
"Enter 5 for Cleaning\n" +
"Enter r to return to the menu");
addOption = addOptionIn.nextLine();
switch (addOption) {
case "1":
addDeliItem();
break;
case "2":
addBakeryItem();
break;
case "3":
addProduceItem();
break;
case "4":
addMeatItem();
break;
case "5":
addCleaningItem();
break;
case "r":
//return to the main menu
break;
default:
break;
}
break;
}
} else if (menuAnswer.equalsIgnoreCase("q")) {
System.exit(0);
}
}
}
public static void main(String[] args) throws FileNotFoundException {
mainMenu();
//print all test objects
store.printAll();
//print only Meat
store.printType("Meat");
}
}
This is my LocalStore class where changes needs to be done under addProduct and printType.
package InventorySystem;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class LocalStore
{
private String supermarketName,
location;
private int maxProducts;
public ArrayList<Inventory> inventory = new ArrayList<>(maxProducts);
public LocalStore(String n,String l,int max)
{
this.supermarketName = n;
this.location = l;
this.maxProducts = max;
}
//add product to inventory array
public void addProduct(Inventory inv)
{
if(inventory.size()<maxProducts)
{
inventory.add(new Inventory(inv));
System.out.println("Inventory Successfully added");
}
else if(inventory.size() == maxProducts)
{
System.out.println("Inventory full");
}
}
public void printAll() throws FileNotFoundException {
/*for(int i=0;i<inventory.size();++i)
{
System.out.println(inventory.get(i).toString());*/
final String FILE_NAME = "productList.csv";
Scanner scnr = new Scanner(new FileInputStream(FILE_NAME));
while (scnr.hasNextLine()) {
System.out.println(scnr.nextLine());
}
scnr.close();
}
public void printType(String type)
{ //check for Deli
if(type.equalsIgnoreCase("Deli"))
{
System.out.println("Deli Items...");
for(int i=0;i<inventory.size();++i)
{
if(inventory.get(i) instanceof Deli)
{
System.out.println(inventory.get(i).toString());
}
}
}
//check for Bakery
else if(type.equalsIgnoreCase("Bakery"))
{
System.out.println("Bakery Items...");
for(int i=0;i<inventory.size();++i)
{
if(inventory.get(i) instanceof Bakery)
{
System.out.println(inventory.get(i).toString());
}
}
}
//check for Produce
else if(type.equalsIgnoreCase("Produce"))
{
System.out.println("Produce Items...");
for(int i=0;i<inventory.size();++i)
{
if(inventory.get(i) instanceof Produce)
{
System.out.println(inventory.get(i).toString());
}
}
}
//check for Meat
else if(type.equalsIgnoreCase("Meat"))
{
System.out.println("Meat Items...");
for(int i=0;i<inventory.size();++i)
{
if(inventory.get(i) instanceof Meat)
{
System.out.println(inventory.get(i).toString());
}
}
}
//check for Cleaning
else if(type.equalsIgnoreCase("Cleaning"))
{
System.out.println("Cleaning Items...");
for(int i=0;i<inventory.size();++i)
{
if(inventory.get(i) instanceof Cleaning)
{
System.out.println(inventory.get(i).toString());
}
}
}
//inform user no matches exist
else
{
System.out.println("No items match your search...");
}
}
//set and get supermarket details
public void setSupermarketName(String n)
{
this.supermarketName = n;
}
public String getSupermarketName()
{
return this.supermarketName;
}
public void setSupermarketLocation(String l)
{
this.location = l;
}
public String getSupermarketLocation()
{
return this.location;
}
public void setMaxProducts(int m)
{
this.maxProducts = m;
}
public int getMaxProducts()
{
return this.maxProducts;
}
}

Related

Check and retain the previous object instead of creating a new one

I am new to Java.
I created a banking system where user can pay their utility bills. I want to keep that status of the bills whether it is paid or not in Bills class. But whenever user wants to go to pay their bills and it creates a new object which vipes the previous data stored in that object. I want something to check if an object already exists it uses that but if it does not exists then create an object and use that. Please do let me know if it is possible.
Look at case 2 where it makes a new object everytime.
import java.util.Scanner;
import java.util.Random;
public class Main {
static boolean isAccount = false;
public static void main(String[] args) {
Menu menu = new Menu(isAccount);
menu.showMenu();
menu.take();
}
}
class Menu {
int option = 0;
boolean isAccount;
double money;
Scanner input = new Scanner(System.in);
public Menu(boolean isAccount) {
this.isAccount = isAccount;
}
public void showMenu() {
System.out.println("Choose your option: \n1. Create an Account\n2. Pay Bills\n3. Banking");
}
public void take() {
if (input.hasNextInt()) {
int opt = input.nextInt();
this.option = opt;
}
System.out.println("Option value: " + this.option);
navigate();
}
public void navigate() {
while (this.option != -1) {
switch (this.option) {
case 1:
if (!isAccount) {
Scanner nameInput = new Scanner(System.in);
System.out.print("Enter your name: ");
String name;
name = nameInput.next();
Random rand = new Random();
int id, number;
do {
number = rand.nextInt(99999);
id = number;
} while (number < 10000);
Scanner accountInput = new Scanner(System.in);
System.out.print("Do you want current account (true/false): ");
boolean isCurrent = accountInput.nextBoolean();
Account acc = new Account(name, id, isCurrent);
this.money = acc.getMoney();
acc.print();
isAccount = true;
} else {
System.out.println("You already have an account!");
}
break;
case 2:
if (isAccount) {
System.out.println("Money: " + this.money);
Bill bill = new Bill(this.money);
bill.showBills();
bill.selectBill();
this.money = bill.getMoney();
} else {
System.out.println("Please make an account before you pay the bill!");
showMenu();
take();
}
break;
case 3:
if (isAccount) {
Banking bank = new Banking(money);
bank.showMenu();
bank.takeOption();
this.money = bank.getMoney();
System.out.println("\nNew Bank Balance: " + this.money + "\n");
} else {
System.out.println("Please make an account before you do banking");
showMenu();
take();
}
}
this.showMenu();
this.take();
}
}
}
here's the bills class
import java.util.Scanner;
import java.util.Random;
class Bill {
class Paid {
boolean electricity, water, gas, internet = false;
}
int option;
double money;
Paid paidBills = new Paid();
public Bill(double money) {
this.money = money;
}
public void showBills () {
System.out.println("\nWhich bill do you want to pay?");
System.out.println("1. Electricity Bill\n2. Gas Bill\n3. Water Bill\n4. Internet Bill\n5. See Bills Status");
}
public void selectBill() {
Scanner input = new Scanner(System.in);
option = input.nextInt();
navigate(this.option);
}
public void navigate(int option) {
switch (option) {
case 1:
Electricity ebill = new Electricity(this.money);
double tempEBill = Math.floor(ebill.makeBill());
ebill.showBill(tempEBill);
this.money = ebill.pay(tempEBill);
ebill.receipt(tempEBill, this.money);
paidBills.electricity = true;
break;
case 2:
Gas gbill = new Gas(money);
double tempGBill = Math.floor(gbill.makeBill());
gbill.showBill(tempGBill);
this.money = gbill.pay(tempGBill);
gbill.receipt(tempGBill, this.money);
paidBills.gas = true;
break;
case 3:
Water wbill = new Water(money);
double tempWBill = Math.floor(wbill.makeBill());
wbill.showBill(tempWBill);
this.money = wbill.pay(tempWBill);
wbill.receipt(tempWBill, this.money);
paidBills.water = true;
break;
case 4:
Internet ibill = new Internet(money);
double tempIBill = Math.floor(ibill.makeBill());
ibill.showBill(tempIBill);
this.money = ibill.pay(tempIBill);
ibill.receipt(tempIBill, this.money);
paidBills.internet = true;
break;
case 5:
showPaidBills();
break;
}
}
public void showPaidBills() {
System.out.println("\nElectricty: " + paidBills.electricity + "\nWater: " + paidBills.water + "\nGas: " + paidBills.gas + "\nInternet: " + paidBills.internet + "\n");
}
public double getMoney() {
return this.money;
}
}
class Electricity {
double money;
static double bill;
public Electricity(double money) {
this.money = money;
}
public double makeBill() {
Random rand = new Random();
bill = rand.nextDouble() * 1000;
return bill;
}
public void showBill(double tempBill) {
System.out.println("\nElectricity Bill: " + tempBill);
}
public double pay(double tempBill) {
return money - tempBill;
}
public void receipt(double tempBill, double money) {
System.out.println("Bill paid amount = " + tempBill);
System.out.println("Remaining Amount in Bank = " + money + "\n");
}
}
class Water extends Electricity {
public Water(double money) {
super(money);
}
public void showBill(double tempBill) {
System.out.println("\nWater Bill: " + tempBill);
}
}
class Gas extends Electricity {
public Gas(double money) {
super(money);
}
public void showBill(double tempBill) {
System.out.println("\nGas Bill: " + tempBill);
}
}
class Internet extends Electricity {
public Internet(double money) {
super(money);
}
public void showBill(double tempBill) {
System.out.println("\nInternet Bill: " + tempBill);
}
}

Is there any way to use the video class in my code

I am unable to use the video class in my program.My code i running fine but according the question i should make use of the video class
But I'am getting the desired output without using it
import java.util.Scanner;
class Video{
String videoName;
boolean checkout;
int rating;
Video(String name){
videoName=name;
}
String getName(){
return videoName;
}
void doCheckout(){
}
void doReturn(){
}
void receiveRating(int rating){
this.rating=rating;
}
int getRating(){
return rating;
}
boolean getCheckout(){
return checkout;
}
}
videoStore extends the video class but there is no use with methods of video class the videoStore array values are resetting after every execution i dont know why
class VideoStore extends Video{
String videoStore[]=new String[100];
int rating[]=new int[100];
boolean status[]=new boolean[100];
int i=0,ind=0,len=-1;
VideoStore(String name) {
super(name);
}
void addVideo(String name){
videoStore[i]=name;
status[i]=false;
i++;
len++;
}
void doCheckout(String name){
if(len>=0){
int index=index(name);
status[index]=true;
}
else{
System.out.println("Nothig in inventory");
}
}
void doReturn(String name){
if(len>=0){
int index=index(name);
status[index]=false;
}
else{
System.out.println("Nothing in inventory");
}
}
void receiveRating(String name,int rating){
if(len>=0){
int index=index(name);
this.rating[index]=rating;
}
else{
System.out.println("Nothing in inventory");
}
}
void listInventory(){
if(len!=-1){
for(int p=0;p<=len;p++){
System.out.println(videoStore[p]+"\t"+status[p]+"\t"+rating[p]);
}
}
else{
System.out.println("nothing in inventory");
}
}
int index(String name){
for (int i = 0; i < videoStore.length; i++) {
if(videoStore[i].equals(name)){
return i;
}
}
return -1;
}
}
this is the main method
public class VideoLauncher {
public static void main(String[] args) {
String yn="y";
int option=0;
String videoName="";
VideoStore vs=new VideoStore(videoName);
Scanner sc=new Scanner(System.in);
do{
System.out.println("1.Add video");
System.out.println("2.Checkout video");
System.out.println("3.Return video");
System.out.println("4.recieve rating");
System.out.println("5.List inventory");
System.out.println("6.Exit");
System.out.println("please enter the option from 1..6");
option=sc.nextInt();
switch(option){
case 1:
System.out.println("please enter the video name");
videoName=sc.next();
Video v=new Video(videoName);
vs.addVideo(videoName);
System.out.println("video added successfully");
System.out.println("do you want to continue(y) else (n)");
yn=sc.next();
break;
case 2:
System.out.println("please enter the name of the video to checkout");
videoName=sc.next();
vs.doCheckout(videoName);
System.out.println("Video "+videoName+" checkedout successfully");
System.out.println("do you want to continue(y) else (n)");
yn=sc.next();
break;
case 3:
System.out.println("please enter the name of the video to return");
videoName=sc.next();
vs.doReturn(videoName);
System.out.println("Video "+videoName+" returned successfully");
System.out.println("do you want to continue(y) else (n)");
yn=sc.next();
break;
case 4:
System.out.println("enter the videoname");
videoName=sc.next();
System.out.println("enter the rating");
int rating=sc.nextInt();
vs.receiveRating(videoName,rating);
System.out.println("rating "+rating+" for video"+videoName+" recorded");
System.out.println("do you want to continue(y) else (n)");
yn=sc.next();
break;
case 5:
vs.listInventory();
System.out.println("do you want to continue(y) else (n)");
yn=sc.next();
break;
case 6:
yn="n";
System.out.println("exiting");
break;
default :
System.out.println("please enter proper option");
}
}while(yn.equals("y"));
}
}
I am not going to give you the whole code but just get you started.
When VideoStore extends Video you are saying, VideoStore is a Video which is wrong, what you want to say is VideoStore has Videos. What you need is a list of Videos in your VideoStore
So your VideoStore should look something like that:
class VideoStore {
Video[] videos = new Video[100];
void addVideo(String name) {
Video v = new Video(name);
for(int i=0; i<videos.length; i++) {
if(videos[i] == null) {
videos[i] = v;
break;
}
}
}
void doCheckout(String name) {
int index = index(name);
videos[index].setCheckout(true);
}
void doReturn(String name) {
// your code
}
void receiveRating(String name, int rating) {
// your code
}
void listInventory() {
// your code
}
int index(String name) {
// your code
}
}
And to your interrogation:
the videoStore array values are resetting after every execution i dont know why
this is normal, they are only in memory and will be wiped out once the program terminates.

How to scan and respond to a user's input?

Creating a simple ATM menu with few options on it.
Want to know how to let user inputs something to select the options, and then the codes can respond to the input.
For example, "readLine(string)"
Following is my code:
public class Menu
{
private String menuText;
private int optionCount;
public Menu()
{
menuText = "";
optionCount = 0;
}
public void addOption(String option)
{
optionCount = optionCount + 1;
menuText = menuText + optionCount + ") " + option + "\n";
}
public void display()
{
System.out.println(menuText);
}
}
public class MenuDemo{
public MenuDemo()
{
}
public static void main(String[] args)
{
Menu mainMenu = new Menu();
mainMenu.addOption("Log In Account");
mainMenu.addOption("Deposit Check");
mainMenu.addOption("Help");
mainMenu.addOption("Quit");
mainMenu.display();
}
}
You can read the user Input with Scanner class. And then with switch statement do your required actions:
import java.util.Scanner;
class Menu
{
private String menuText;
private int optionCount;
public Menu()
{
menuText = "";
optionCount = 0;
}
public void addOption(String option)
{
optionCount = optionCount + 1;
menuText = menuText + optionCount + ") " + option + "\n";
}
public void display()
{
System.out.println(menuText);
}
}
public class MenuDemo{
public MenuDemo()
{
}
public static void main(String[] args)
{
Menu mainMenu = new Menu();
mainMenu.addOption("1. Log In Account");
mainMenu.addOption("2. Deposit Check");
mainMenu.addOption("3. Help");
mainMenu.addOption("4. Quit");
mainMenu.display();
Scanner input = new Scanner(System.in);
System.out.println("Enter Choice: ");
String i = input.nextLine();
switch(i){
case "1":
//do something
System.out.println("User Entered 1 : " + i);
break;
case "2":
//do something
System.out.println("User Entered 2 : " + i);
break;
case "3":
//do something
System.out.println("User Entered 3 : " + i);
break;
case "4":
//do something
System.out.println("User Entered 4 : " + i);
break;
default:
System.out.println("Quit" + i);
}
}
}

Can't seem to get it to write to an arrayList and then to a file

I have been working on this and can't seem to get it to run correctly. It should create an arraylist then add, remove, mark as loaned, mark as returned, and write to a file when you quit. I can't find what I messed up.
package cs1181proj1;
import static cs1181proj1.Media.media;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
/**
*
* #author Veteran
*/
public class CS1181Proj1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// Create ArrayList and mediaFile.
ArrayList<Media> Item = new ArrayList<>();
Scanner keyboard = new Scanner(System.in);
File mediaFile = new File("mediaFile.dat");
String Title;
String Format;
String loanedTo = null;
String dateLoaned = null;
int number = 0;
if (mediaFile.exists()) {
try {
try (ObjectInputStream dos = new ObjectInputStream(
new FileInputStream(mediaFile))) {
Item = (ArrayList<Media>) dos.readObject();
}
} catch (FileNotFoundException a) {
System.out.println("Thou hast erred! The file doth not exist!");
} catch (IOException b) {
System.out.println("GIGO My Lord or Lady!");
} catch (ClassNotFoundException c) {
System.out.println("Avast! I am in a quandry");
}
}
//Print out menu of choices
while (number != 6) {
System.out.println("");
System.out.println("1. Add new media item");
System.out.println("2. Mark an item out on loan");
System.out.println("3. Mark an item as Returned");
System.out.println("4. List items in collection");
System.out.println("5. Remove a media item");
System.out.println("6. Quit");
System.out.println("");
//accept users menu choice
try {
number = keyboard.nextInt();
} catch (InputMismatchException e) {
System.out.println("That's not a number between 1 and ` `6. IS IT!");
}
//Switch to tell program what method to use depending on user ` `//option
switch (number) {
case 1:
insert();
break;
case 2:
onLoan();
break;
case 3:
returned();
break;
case 4:
list();
break;
case 5:
removeItem();
break;
case 6:
System.out.println("Goodbye");
Quit(mediaFile);
break;
}
}
}
//Method for inserting items in arraylist
public static void insert() {
ArrayList<Media> media = new ArrayList<>();
System.out.println("New titles name");
Scanner newEntry = new Scanner(System.in);
String title = newEntry.nextLine();
System.out.println("");
//title of media
while (titleAlreadyExists(title, media)) {
System.out.println("Title already exists");
title = newEntry.nextLine();
System.out.println("");
}
//format of media
System.out.println("What format");
String format = newEntry.nextLine();
media.add(new Media(title, format));
System.out.println("Your entry has been created.");
}
//In case entry already exists
public static boolean titleAlreadyExists(
String title, ArrayList<Media> media) {
for (Media entry : media) {
if (entry.getTitle().equals(title)) {
return true;
}
}
return false;
}
//Method for putting item on loan
public static void onLoan() {
System.out.println("Enter name of Title on loan");
Scanner newLoan = new Scanner(System.in);
ArrayList<Media> media = new ArrayList<>();
String loanTitle = newLoan.nextLine();
System.out.println("Who did you loan this to");
Scanner To = new Scanner(System.in);
String loanedTo = To.nextLine();
System.out.println("");
System.out.println("When was it lent out?");
Scanner date = new Scanner(System.in);
String dateLoaned = date.nextLine();
System.out.println("");
for (Media title : media) {
if (title.getTitle().equals(loanTitle)) {
title.setDateLoaned(dateLoaned);
title.setloanedTo(loanedTo);
System.out.println(title + " loaned to " + loanedTo + ` `"on date" + dateLoaned + "is listed as loaned");
}
}
}
//Method for returning item in collection
public static void returned() {
System.out.println("Enter name of Title returned");
Scanner returned = new Scanner(System.in);
ArrayList<Media> media = new ArrayList<>();
String returnedTitle = returned.nextLine();
String loanedTo = null;
String dateLoaned = null;
System.out.println("");
for (Media title : media) {
if (title.getTitle().equals(returnedTitle)) {
title.setDateLoaned(dateLoaned);
title.setloanedTo(loanedTo);
System.out.println(title + "is listed as returned");
}
}
}
//Method for listing items in collection
public static void list() {
System.out.println("Your collection contains:");
for (int i = 0; i < media.size(); i++) {
System.out.print((media.get(i)).toString());
System.out.println("");
}
}
//method for removing an item from the collection
private static void removeItem() {
System.out.println("What item do you want to remove?");
Scanner remover = new Scanner(System.in);
ArrayList<Media> media = new ArrayList<>();
String removeTitle = remover.nextLine();
System.out.println("");
media.stream().filter((title) -> ` ` (title.getTitle().equals(removeTitle))).forEach((title) -> {
media.remove(removeTitle);
System.out.println(title + "has been removed");
});
}
//method for saving to file when the user quits the program.
//To ensure there is no data loss.
public static void Quit(File mediaFile) {
try {
ArrayList<Media> media = new ArrayList<>();
try (ObjectOutputStream oos = new ObjectOutputStream(new ` ` FileOutputStream(mediaFile))) {
oos.writeObject(media);
System.out.println("Your file has been saved.");
}
} catch (IOException e) {
System.out.println("Unable to write to file. Data not ` `saved");
}
}
}
Here is its companion media file:
package cs1181proj1;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Comparator;
/**
*
* #author Veteran
*/
public class Media implements Serializable {
static ArrayList<String> media = new ArrayList<>();
private String Title;
private String Format;
private String loanedTo = null;
private String dateLoaned = null;
Media() {
this.Title = ("Incorrect");
this.Format = ("Incorrect");
this.loanedTo = ("Available");
this.dateLoaned = ("Available");
}
Media(String Title, String Format) {
this.Title = Title;
this.Format = Format;
this.loanedTo = ("Available");
this.dateLoaned = ("Available");
}
//Get and Set Title
public String getTitle() {
return this.Title;
}
public void setTitle(String Title) {
this.Title = Title;
}
//Get and Set Format
public String getFormat() {
return this.Format;
}
public void setFormat(String Format) {
this.Format = Format;
}
//Get and Set loanedTo
public String getLoanedTo() {
return this.loanedTo;
}
public void setloanedTo (String loanedTo){
this.loanedTo = loanedTo;
}
//Get and set dateLoaned
public String getDateLoaned() {
return this.dateLoaned;
}
public void setDateLoaned(String dateLoaned){
this.dateLoaned = dateLoaned;
}
#Override
public String toString(){
return this.Title + ", " + this.Format +", " + this.loanedTo + ", "
+ this.dateLoaned;
}
public static Comparator <Media> TitleComparator = new Comparator <Media>(){
#Override
public int compare(Media t, Media t1) {
String title = t.getTitle().toUpperCase();
String title1 = t1.getTitle().toUpperCase();
return title.compareTo(title1);
}
};
}

Using ObservaleList to add element into ListView

I am having the problem with adding an array to ObservableList the use it to add that array into ListView. When I compiled, I got NullPointerException. This exception occurs when I call the listAllItems() method. If I do not use the GUI control, instead of using switch-statement and letting the user choose the option, then there are no exception occur at the run time. Could someone help me figure out what happen? Thanks
Requirement
Create a LibraryGUI class
◦ This class should have a Library object as one of its fields. In the LibraryGUI constructor
you will need to call the library constructor method to initialize this field and then call its
open() method to read in the items from the data file.
◦ Use a JList to display the contents of the library. Use the setListData method of the JList
class together with the listAllItems method of the Library class to keep the list current with
the library contents.
import javax.swing.JOptionPane;
public class MediaItem {
/*Fields*/
private String title;
private String format;
private boolean onLoan;
private String loanedTo;
private String dateLoaned;
/*Default Constructor - Initialize string variables for null and boolean variable for false*/
public MediaItem()
{
title = null;
format = null;
onLoan = false;
loanedTo = null;
dateLoaned = null;
}
/*Parameterized Constructor*/
public MediaItem(String title, String format)
{
this.title = title;
this.format = format;
this.onLoan = false;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
public boolean isOnLoan() {
return onLoan;
}
public void setOnLoan(boolean onLoan) {
this.onLoan = onLoan;
}
public String getLoanedTo() {
return loanedTo;
}
public void setLoanedTo(String loanedTo) {
this.loanedTo = loanedTo;
}
public String getDateLoaned() {
return dateLoaned;
}
public void setDateLoaned(String dateLoaned) {
this.dateLoaned = dateLoaned;
}
/*Mark item on loan*/
void markOnLoan(String name, String date){
if(onLoan == true)
JOptionPane.showMessageDialog(null,this.title + " is already loaned out to " + this.loanedTo + " on " + this.dateLoaned);
else {
onLoan = true;
loanedTo = name;
dateLoaned = date;
}
}
/*Mark item return*/
void markReturned(){
if(onLoan == false)
JOptionPane.showMessageDialog(null, this.title + " is not currently loaned out");
onLoan = false;
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JOptionPane;
import javafx.scene.control.TextInputDialog;
public class Library extends MediaItem {
/*Fields*/
private ArrayList<MediaItem> itemsList = new ArrayList<>();
public ArrayList<MediaItem> getItemsList() {
return itemsList;
}
public void setItemsList(ArrayList<MediaItem> itemsList) {
this.itemsList = itemsList;
}
public int displayMenu()
{
Scanner input = new Scanner(System.in);
System.out.println("\nMenu Options \n"
+"\n1. Add new item\n"
+"\n2. Mark an item as on loan\n"
+"\n3. List all item\n"
+"\n4. Mark an item as returned\n"
+"\n5. Quit\n"
+"\n\nWhat would you like to do?\n");
int choices = input.nextInt();
while (choices < 1 || choices >5)
{
System.out.println("I'm sorry, " + choices + " is invalid option");
System.out.println("Please choose another option");
choices = input.nextInt();
}
return (choices);
}
public void addNewItem(String title, String format)
{
MediaItem item = new MediaItem(); // the object of item
/*Use the JOptionPane.showInputDialog(null,prompt) to let the user input the title and the format
* store the title and the format to the strings and pass it to the parameter of addNewItem(String, String) method
* title and format will go through the loop if title already exited let the user input another title and format
* Using the same method JOptionPan.ShowInputDialog and JOptionPane.showMessage()
*/
boolean matches = false;
for(int i = 0; i< itemsList.size(); i++){
if(title.equals(itemsList.get(i).getTitle())){
String newTitle = JOptionPane.showInputDialog(null, "this " + title + " already exited. Please enter the title again");
String newFormat = JOptionPane.showInputDialog(null, "Enter the format again");
item = new MediaItem(newTitle,newFormat);
itemsList.add(item);
matches = true;
}
}if(!matches){
item = new MediaItem(title,format);
itemsList.add(item);
}
}
public void markItemOnLoan(String title, String name, String date)
{
boolean matches = false;
for(int i = 0; i < itemsList.size(); i++)
{ if (title.equals(itemsList.get(i).getTitle()))
{
itemsList.get(i).markOnLoan(name,date);
matches = true;
}
}
if (!matches)
{
JOptionPane.showMessageDialog(null,"I am sorry. I couldn't find " + title + " in the library");
}
}
public String[] listAllItems()
{
String[] list = new String[itemsList.size()];
for (int n = 0; n < itemsList.size(); n++)
{
if(itemsList.get(n).isOnLoan() == true)
list[n] = itemsList.get(n).getTitle() + " (" + itemsList.get(n).getFormat() + " ) loaned to " + itemsList.get(n).getLoanedTo() + " on " + itemsList.get(n).getDateLoaned();
else
list[n] = itemsList.get(n).getTitle() + " (" + itemsList.get(n).getFormat() + ")";
if(list[n] == null){
String title = "title ";
String format = "format ";
String loanTo = "name ";
String date = "date ";
list[n] = title + format + loanTo + date;
}
}
return list;
}
public void markItemReturned(String title)
{
boolean matches = false;
for( int i = 0; i < itemsList.size(); i++)
{
if(title.equals(itemsList.get(i).getTitle()))
{
matches = true;
itemsList.get(i).markReturned();
}
}
if(!matches)
{
JOptionPane.showMessageDialog(null,"I am sorry. I couldn't find " + title + " in the library");
}
}
public void deleteItem(String title){
boolean matches = false;
for(int i = 0; i < itemsList.size(); i++){
if(title.equals(itemsList.get(i).getTitle())){
itemsList.get(i).setTitle(null);
itemsList.get(i).setFormat(null);
itemsList.get(i).setDateLoaned(null);
itemsList.get(i).setLoanedTo(null);
itemsList.get(i).setOnLoan(false);
}
}
if(!matches)
JOptionPane.showMessageDialog(null,"I am sorry. I couldn't find " + title + " in the library");
}
public void openFile(){
Scanner input = null;
try{
input = new Scanner(new File("library.txt"));
Scanner dataInput = null;
MediaItem item = new MediaItem();
int index = 0;
String title = " ";
String format = " ";
String date = " ";
String onLoanTo = " ";
Boolean onLoan = false;
Boolean checkString= false;
Boolean checkBoolean = false;
itemsList = new ArrayList<>();
while(input.hasNextLine()){
dataInput = new Scanner(input.nextLine());
dataInput.useDelimiter("-");
while(input.hasNext()){
Boolean dataBoolean = dataInput.nextBoolean();
String dataString = dataInput.next();
if(index == 0){
item.setTitle(dataString);
title = item.getTitle();
checkString = true;
}else if(index == 1){
item.setFormat(dataString);
format = item.getFormat();
checkString= true;
}else if(index == 2){
item.setOnLoan(dataBoolean);
checkBoolean = true;
}else if(index == 3){
item.setLoanedTo(dataString);
checkString = true;
}else if(index == 4){
item.setDateLoaned(dataString);
checkString = true;
}else {
if(checkString == false)
throw new Exception("Invalid data " + dataString);
if(checkBoolean == false)
throw new Exception("Invalid data " + dataBoolean);
}
index++;
itemsList.add(new MediaItem(title,format));
}
index = 0;
title = " ";
format = " ";
date = " ";
onLoan = false;
onLoanTo = " ";
checkString= false;
checkBoolean = false;
}
}catch(Exception ex){
JOptionPane.showMessageDialog(null, ex.getMessage());
}finally{
if(input != null){
try{
input.close();
}catch(NullPointerException ex){
JOptionPane.showMessageDialog(null,"Error: File can not be closed");
}
}
}
}
public void saveFile(){
PrintWriter output = null;
try{
output = new PrintWriter(new File("library.txt"));
for(int i = 0; i < itemsList.size(); i++){
output.println(itemsList.get(i).getTitle() + "-" + itemsList.get(i).getFormat()+ "-" + itemsList.get(i).isOnLoan() + "-"
+ itemsList.get(i).getLoanedTo() + "-" + itemsList.get(i).getDateLoaned());
}
}catch(FileNotFoundException e1){
JOptionPane.showMessageDialog(null,"Could not find the data file. Program is exiting.");
}catch(IOException e2){
JOptionPane.showMessageDialog(null, "Something went wrong with writing to the data file.");
}catch(Exception e3){
JOptionPane.showMessageDialog(null,"Something went wrong.");
}
finally{
if( output != null){
try{
output.close();
System.exit(0);
}catch (NullPointerException e4){
JOptionPane.showMessageDialog(null, "Error: File can not be closed");
}
}
}
}
}
enter code here
import java.util.ArrayList;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
public class LibraryGUI extends Application{
private ListView<String> listView;
private Library library;
private Button btAdd, btCheckIn, btCheckOut, btDelete;
public void LibraryGUI(){
library = new Library();
library.openFile();
}
public void start(Stage primaryStage) throws Exception {
listView = new ListView<>();
//Add all item in the listAllItem() method to the list view
String[] list = library.listAllItems();
int length = library.getItemsList().size();
for (int i = 0; i < length; i++)
{
ObservableList<String> element = FXCollections.observableArrayList( list[i].toString());
listView.setItems(element);
}
listView.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
btAdd = new Button(" Add");
btCheckIn = new Button(" CheckIn ");
btCheckOut = new Button(" CheckOut ");
btDelete = new Button(" Delete ");
FlowPane flowP = new FlowPane();
listView.setPrefSize(400, 275);
btAdd.setPrefSize(100, 25);
btAdd.setAlignment(Pos.BOTTOM_LEFT);
btCheckIn.setPrefSize(100, 25);
btCheckIn.setAlignment(Pos.BOTTOM_LEFT);
btCheckOut.setPrefSize(100, 25);
btCheckOut.setAlignment(Pos.BOTTOM_LEFT);
btDelete.setPrefSize(100,25);
btDelete.setAlignment(Pos.BOTTOM_LEFT);
flowP.getChildren().addAll(listView,btAdd,btCheckIn,btCheckOut,btDelete);
Scene scene = new Scene (flowP,400,300);
primaryStage.setTitle("Calculator");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Code for Switch-Statement
import java.util.Scanner;
public class Code8 {
public static void main(String[] args) {
MediaItem newItem = new MediaItem();
Library library = new Library();
Scanner in = new Scanner(System.in);
int option = 0;
while (option != 5)
{
option = library.displayMenu();
switch(option)
{
case 1:
System.out.print("What is the title? ");
String newTitle = in.nextLine();
newItem.setTitle(newTitle);
System.out.println("What is the format? ");
String newFormat = in.nextLine();
newItem.setFormat(newFormat);
library.addNewItem(newTitle, newFormat);
break;
case 2:
System.out.println("Which item (enter the title)? ");
newTitle = in.nextLine();
newItem.setTitle(newTitle);
System.out.println("Who are you loaning it to? ");
String name = in.nextLine();
newItem.setLoanedTo(name);
System.out.println("When did you loan it to them? ");
String date = in.nextLine();
library.markItemOnLoan(newTitle, name, date);
break;
case 3:
String[] list = library.listAllItems();
int length = library.getItemsList().size();
for (int i = 0; i < length; i++)
{
System.out.println(list[i].toString());
}
break;
case 4:
System.out.println("Which item (enter the title)? ");
newTitle = in.nextLine();
newItem.setTitle(newTitle);
library.markItemReturned(newTitle);
break;
case 5:
System.out.println("Goodbye");
break;
}// switch statement
}//while statement
} //main method
}

Categories