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

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);
}
}
}

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);
}
}

How to read .csv file in 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;
}
}

Im getting errors with some methods

I'm writing this java class which is the TUI for the Class loyaltyCard, However, I'm facing some errors with the methods below. Would appreciate any help, Thanks.
public void addLoyalty Card
public void ShowAllLoyaltyCards (it should print details of all loyaltycards with a space between each)
public void showLoyaltyCard (print out loyaltycard with the choose card number, if unsuccessful "message"
Here is my code:
import java.util.ArrayList;
import java.util.Scanner;
public class LoyaltyCardTUI
{
private LoyaltyCardList loyaltyCardList;
private Scanner myScanner;
public LoyaltyCardTUI()
{
myScanner = new Scanner(System.in);
LoyaltyCardList loyaltyCardList = new LoyaltyCardList();
}
public void menu()
{
int command = -1;
while (command != 0)
{
displayMenu();
command = getCommand();
execute (command);
}
}
**public void addLoyaltyCard(**)
{
loyaltyCardList.addLoyaltyCard(new LoyaltyCard());
}
private void displayMenu()
{
System.out.println( "Options are" );
System.out.println( "Enter 1" );
System.out.println( "Enter 2" );
System.out.println( "Enter 3" );
System.out.println( "Enter 4" );
}
private void execute( int command)
{
if ( command == 1)
addLoyaltyCard();
else
if ( command == 2 )
getNumberOfLoyaltyCards();
else
if ( command == 3)
quitCommand();
else
if ( command == 4)
quitCommand();
else
if ( command == 5)
quitCommand();
else
System.out.println("Unknown Command");
}
private int getCommand()
{
System.out.print ("Enter command: ");
int command = myScanner.nextInt();
myScanner.nextLine();
return command;
}
public void getNumberOfLoyaltyCards()
{
int command = myScanner.nextInt();
System.out.println("We have" + loyaltyCardList.getNumberOfLoyaltyCards() + "loyaltyCards");
}
public void quitCommand()
{
int command = myScanner.nextInt();
System.out.println("Application Closing");
System.exit(0);
}
private void removeLoyaltyCard()
{
System.out.print("Enter card number : ");
String cardNumber = myScanner.nextLine();
if (loyaltyCardList.removeLoyaltyCard(cardNumber))
System.out.println("LoyaltyCard with card number " + cardNumber + " removed from class list");
else
System.out.println("LoyaltyCard with card number " + cardNumber + " not found");
}
**public void showAllLoyaltyCards()**
{
for(LoyaltyCard loyaltyCard : loyaltyCards)
{
loyaltyCard.printCustomerDetails();
System.out.println();
}
}
**public void showLoyaltyCard()**
{
for (LoyaltyCard loyaltyCard : loyaltyCards)
{
if (cardNumber.equals(loyaltyCard.getCardNumber()))
{
return System.out.println(loyaltyCard);
}
else
{
return System.out.println("Could not find loyalty card for card number"+cardNumber);
}
}
}
private void unknownCommand(int command)
{
System.out.println("Invalid Command : "+ command);
}
}

Java Suit Application using enums, methods and user input updated

I have got through all of this paper except the last part(Part 5) I have attached the picture of the paper for the part I am struggling with above.
When running my application tester, when I press 3, nothing happens. Does anyone know why? the code of my classes is below. NOTE: the updateBrand() method which is called in the tester in the makeChangeToSuit method is in the morningSuit and suit classes.
I would appreciate any help on this matter.
package SuitProg;
import java.util.Scanner;
public abstract class Suit {
//instance variables
private String Colour;
private double dailyCost;
private int trouserLength;
private int jacketChestSize;
private boolean available;
protected double totalPrice;
//constructor
public Suit(String colour, double dailyCost, int trouserLength, int jacketChestSize, boolean available) {
super();
Colour = colour;
this.dailyCost = dailyCost;
this.trouserLength = trouserLength;
this.jacketChestSize = jacketChestSize;
this.available = available;
this.totalPrice = totalPrice;
}
//accessors & mutators
public String getColour() {
return Colour;
}
public double getDailyCost() {
return dailyCost;
}
public int getTrouserLength() {
return trouserLength;
}
public int getJacketChestSize() {
return jacketChestSize;
}
public boolean getAvailability() {
return available;
}
public double getTotalPrice() {
return totalPrice;
}
public void setDailyCost(double dailyCost) {
this.dailyCost = dailyCost;
}
public void setTrouserLength(int trouserLength) {
this.trouserLength = trouserLength;
}
public void setJacketChestSize(int jacketChestSize) {
this.jacketChestSize = jacketChestSize;
}
public void setAvailability(boolean available) {
this.available = available;
}
//methods
public String toString() {
return " Suit [ Colour: " + getColour() + ", Daily Cost: " + String.format("%.2f", getDailyCost())
+ "\nTrouser Length: " + getTrouserLength() + ", Jacket Chest Size: " + getJacketChestSize()
+ " Is it available? " + getAvailability();
}
public void calcTotalPrice (int numDaysHired) {
totalPrice = totalPrice + (getDailyCost() * numDaysHired);
}
public String printDailyCost() {
getDailyCost();
return "£" + String.format("%.2f", getDailyCost());
}
public void makeChange(Scanner input) {
boolean valid = false;
do {
System.out.println("Are you sure you want to change the branding of a suit?");
String response = input.nextLine().toLowerCase();
if (response.equalsIgnoreCase("Y")) {
valid = true;
updateBrand(null);
}
else
if (response.equalsIgnoreCase("N")) {
valid = true;
System.exit(0);
break;
}
} while (!valid);
}
public void updateBrand(Scanner input) {
boolean valid = false;
int selection;
System.out.println("The list of available brands are below:");
System.out.println("1 - " + Brand.Highstreet);
System.out.println("2 - " + Brand.TedBaker);
System.out.println("3 - " + Brand.FrenchConnection);
do {
System.out.println("Please enter the number of the Brand you wish to change.");
if (input.hasNextInt()) {
selection = input.nextInt();
if (selection < 1 || selection > 3) {
valid = false;
System.out.println("Please enter a number betwen 1 and 3");
} else
valid = true;
System.out.println("You have selected number: " + selection);
if (selection == 1) {
System.out.println("Please enter the changes you want to make");
System.out.println("New brand name : ");
//
}
}
} while (!valid);
}
}
package SuitProg;
import java.util.Scanner;
public class MorningSuit extends Suit implements Brandable {
//instance variables
private boolean boutonniere;
private boolean topHat;
public Brand brand;
//constructor
public MorningSuit(String colour, double dailyCost, int trouserLength, int jacketChestSize, boolean available, boolean boutonniere, boolean topHat) {
super(colour, dailyCost, trouserLength, jacketChestSize, available);
this.boutonniere = boutonniere;
this.topHat = topHat;
}
//accessors & mutators
public boolean getBout() {
return boutonniere;
}
public boolean getTopHat() {
return topHat;
}
public void setBout(boolean boutonniere) {
this.boutonniere = boutonniere;
}
public void setTopHat(boolean topHat) {
this.topHat = topHat;
}
public void setBrand(Brand brand) {
this.brand = brand;
}
//methods
public String toString() {
return "Morning Suit [ Boutonniere " + getBout() + " TopHat " + getTopHat() + " Colour: " + getColour() + ", Daily Cost: £" + String.format("%.2f", getDailyCost())
+ "\nTrouser Length: " + getTrouserLength() + ", Jacket Chest Size: " + getJacketChestSize()
+ " Is it available? " + getAvailability() + "]";
}
public void calcTotalPrice(int numDaysHired) {
if (getBout()) {
totalPrice = totalPrice + 3;
}
if (getTopHat()) {
totalPrice = totalPrice + 10;
}
totalPrice = totalPrice + (numDaysHired * getDailyCost());
System.out.println("The morning suit was hired for " + numDaysHired + " days.");
System.out.println("The total cost for the hire was: £" + String.format("%.2f", totalPrice));
}
public String getBrand() {
return "The brand of this Morning Suit is " + brand.toString().toLowerCase();
}
public void makeChange(Scanner input) {
boolean valid = false;
do {
System.out.println("Are you sure you want to change the branding of a suit?");
String response = input.nextLine().toLowerCase();
if (response.equalsIgnoreCase("Y")) {
valid = true;
updateBrand(input);
}
else
if (response.equalsIgnoreCase("N")) {
valid = true;
System.exit(0);
break;
}
} while (!valid);
}
public void updateBrand(Scanner input) {
boolean valid = false;
int selection;
System.out.println("The list of available brands are below:");
System.out.println("1 - " + Brand.Highstreet);
System.out.println("2 - " + Brand.TedBaker);
System.out.println("3 - " + Brand.FrenchConnection);
do {
System.out.println("Please enter the number of the Brand you wish to change.");
if (input.hasNextInt()) {
selection = input.nextInt();
if (selection < 1 || selection > 3) {
valid = false;
System.out.println("Please enter a number betwen 1 and 3");
} else
valid = true;
System.out.println("You have selected number: " + selection);
if (selection == 1) {
System.out.println("Please enter the changes you want to make");
System.out.println("New brand name : ");
//
}
}
} while (!valid);
}
}
package SuitProg;
public enum Brand {
Highstreet,TedBaker,FrenchConnection
}
package SuitProg;
public interface Brandable {
public String getBrand();
}
package SuitProg;
import java.util.Scanner;
public class EveningSuit extends Suit implements Brandable {
//variables
private boolean cufflinks;
private boolean waistcoat;
public Brand brand;
public EveningSuit(String colour, double dailyCost, int trouserLength, int jacketChestSize, boolean available, boolean cufflinks, boolean waistcoat) {
super(colour, dailyCost, trouserLength, jacketChestSize, available);
this.cufflinks = cufflinks;
this.waistcoat = waistcoat;
this.brand = Brand.Highstreet;
}
//accessors & mutators
public boolean getCuffs() {
return cufflinks;
}
public boolean getWaistcoat() {
return waistcoat;
}
public void setCuffs(boolean cufflinks) {
this.cufflinks = cufflinks;
}
public void setWaistcoat(boolean waistcoat) {
this.waistcoat = waistcoat;
}
//methods
public String toString() {
return "Evening Suit [ Cufflinks " + getCuffs() + " Waistcoat " + getWaistcoat() + " Colour: " + getColour() + ", Daily Cost: £" + String.format("%.2f", getDailyCost())
+ "\nTrouser Length: " + getTrouserLength() + ", Jacket Chest Size: " + getJacketChestSize()
+ " Is it available? " + getAvailability() + "]";
}
public void calcTotalPrice (int numDaysHired) {
if (getCuffs()) {
totalPrice = totalPrice + 5;
}
if (getWaistcoat()) {
totalPrice = totalPrice + 10;
}
totalPrice = totalPrice + (getDailyCost() * numDaysHired);
System.out.println("The evening suit was hired for " + numDaysHired + " days.");
System.out.println("The total cost for the hire was: £" + String.format("%.2f", totalPrice));
}
public String getBrand() {
return "The brand of this Evening Suit is " + brand.toString().toLowerCase();
}
public void makeChange(Scanner input) {
boolean valid = false;
do {
System.out.println("Are you sure you want to change the branding of a suit?");
String response = input.nextLine().toLowerCase();
if (response.equalsIgnoreCase("Y")) {
valid = true;
System.out.println("You can not change the brand name of an evening suit.");
}
else
if (response.equalsIgnoreCase("N")) {
valid = true;
System.exit(0);
break;
}
} while (!valid);
}
}
package SuitProg;
import java.util.ArrayList;
import java.util.Scanner;
public class Tester05 {
public static void main(String[] args) {
//create arrayList of suits
ArrayList<Suit> suits = new ArrayList<Suit>();
//create morningSuit object
MorningSuit MorningSuit1 = new MorningSuit("Black", 80.00, 32, 36, true, true, false);
MorningSuit1.setBrand(Brand.FrenchConnection);
//create evening suit
EveningSuit EveningSuit1 = new EveningSuit("White", 70.25, 34, 36, true, true, true);
//add suits to arrayList
suits.add(MorningSuit1);
suits.add(EveningSuit1);
//print all details of arrayList
for (Suit eachSuit : suits) {
System.out.println(eachSuit .toString()+"\n");
}
System.out.println(MorningSuit1.getBrand());
System.out.println(EveningSuit1.getBrand());
printMenu(suits);
}
public static void printMenu(ArrayList<Suit> suits) {
Scanner input = new Scanner(System.in);
System.out.println("----------------Suit Hire-----------------");
System.out.println("What would you like to do?");
System.out.println("\n1)Display all suits\n2)Display available suits\n3)Change Suit brand\n4)Finished");
System.out.println("Please select an option: ");
int selection = input.nextInt();
if (selection == 1) {
displayAllSuits(suits);
} else
if (selection == 2) {
displayAllSuits(suits);
}
else
if (selection ==3) {
makeChangeToSuits(suits, input);
}
else
if (selection ==4) {
System.out.println("You are now exitting the system.");
System.exit(0);
}
}
public static void makeChangeToSuits(ArrayList<Suit> suits, Scanner input) {
for (int i = 0; i > suits.size(); i ++) {
suits.get(i).updateBrand(input);
}
}
public static void displayAllSuits(ArrayList<Suit> suits) {
for (Suit eachSuit : suits) {
System.out.println(eachSuit .toString()+"\n");
}
}
public static void displayAvailableSuits(ArrayList<Suit> suits) {
for (int i = 0; i > suits.size(); i++) {
if (suits.get(i).getAvailability()) {
System.out.println(suits.get(i).toString());
}
}
}
}
The problem is in your makeChangeToSuits method when you iterate the list. It should look like:
public static void makeChangeToSuits(ArrayList<Suit> suits, Scanner input) {
for (Suit suit : suits) {
suit.updateBrand(input);
}
}
Also, your displayAvailableSuits method should look like:
public static void displayAvailableSuits(ArrayList<Suit> suits) {
for (Suit suit : suits) {
if (suit.getAvailability()) {
System.out.println(suit.toString());
}
}
}

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