I'm working on a shop program and i'm trying to find the total value of the products in stock. The data related to each item is present in a row of the file named "SHOP.txt", like : "H;L;10;€10,50;83259875;YellowPaint"(that is the first line of the file where all the products are saved in this format, separated by ";" : department,unityOfmeasure,quantity,price,code,name).To calculate the total value, the program read each token from the aforementioned line and calculate the value by multiplying quantity for price.
I already saved in the file about 10 products but when i try to compile my code, I keep getting an error and it calculate the value only of the first product.
public static void main(String[] args) throws IOException {
while (running) {
System.out.println("\nPress 0 to load the inventory. " + "\nPress 1 to save and close"
+ "\nPress 2 to add products to the inventory" + "\nPress 3 to find products"
+ "\nPress 4 for the total value of the inventory");
int answer = in.nextInt();
switch (answer) {
case 0:
System.out.println("insert the name of the file to load");
Loading(in.next());
break;
case 1:
saveAndQuit();
break;
case 2:
addProduct();
break;
case 3:
inputCode();
break;
case 4:
inventoryValue();
break;
}
}
System.exit(0);
}
private static void inventoryValue() throws FileNotFoundException {
Scanner scanner = new Scanner(new File("SHOP.txt"));
scanner.useDelimiter(";|\n");
Product[] products = new Product[0];
while (scanner.hasNext()) {
String department = scanner.next();
String unityOfMeasure = scanner.next();
int quantity = scanner.nextInt();
double price = scanner.nextDouble();
String code = scanner.next();
String name = scanner.next();
Product newProduct = new Product(department, unityOfMeasure, quantity, price, code, name);
products = newProduct(products, newProduct);
double totalValue = Arrays.stream(products).mapToDouble(p -> p.quantity * p.price).sum();
System.out.println("Total Value: " + totalValue + "\n\n");
for (Product product : products) {
System.out.println(product);
}
}
}
private static Product[] newProduct(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 newProduct;
}
This is the complete code as requested.
Product Class:
public class Product implements Serializable {
protected String department;
protected String unityOfMeasure;
protected int quantity;
protected double price;
protected String code;
protected String name;
private static NumberFormat formatter = new DecimalFormat("#0.00");
public Product(String dep, String uom, int qnt, double prz, String cod, String nm) {
reparto = dep;
unitaDiMisura = uom;
quantità = qnt;
prezzo = prz;
codice = cod;
nome = nm;
}
// setters
public void setDep(String rep) {
this.department = department;
}
public void setPrz(double prz) {
this.price = price;
}
public void setUdm(String udm) {
this.unityOfMeasure = unityOfMeasure;
}
public void setQnt(int qnt) {
this.quantity = quantity;
}
public void setCod(String cod) {
this.code = code;
}
public void setNm(String nm) {
this.name = name;
}
// getters
public String getDep() {
return department;
}
public String getUom() {
return unityOfMeasure;
}
public double getPrz() {
return price;
}
public int getQnt() {
return quantity;
}
public String getCod() {
return code;
}
public String getNm() {
return name;
}
public double getTotal() {
return quantity * price;
}
public void remove() {
this.quantity--;
}
public String toString() {
// ----quantity not less than 0 ----
if (quantity < 0) {
System.out.println(quantity = 0);
}
return String.format(department + ";" + unityOfMeasure + ";" + quantity + ";" + "€" + formatter.format(price) + ";"
+ code+ ";" + name + " \n");
}
}
Shop Class:
public class Shop implements Serializable {
public List<Product> collection;
public Shop() {
collection = new ArrayList<Product>();
}
public void addProduct(Product product) {
collection.add(product);
}
public void sellProduct(String name) {
for (Product product : collection) {
if (name.equals(product.getNm())) {
if (product.getQnt() >= 0) {
prodotto.remove();
}
return;
}
}
}
public void duplicatedProduct(String code) {
for (Product product : collection) {
if (code.equals(product.getCod())) {
System.out.println("Error. Duplicated product");
}
return ;
}
}
#Override
public String toString() {
String total = "\n";
Iterator<Product> i = collection.iterator();
while (i.hasNext()) {
Product l = (Product) i.next();
total = total + l.toString();
}
return total;
}
}
Main Class:
public class Main {
static String fileName = null;
static Shop shp = new Shop();
static Scanner in = new Scanner(System.in);
static boolean running = true;
public static void main(String[] args) throws IOException {
while (running) {
System.out.println("\nPress 0 to load inventory. " + "\nPress 1 to save and quit"
+ "\nPress 2 to add product to the inventory" + "\nPress 3 to find a product"
+ "\nPress 4 for the total value of the inventory");
int answer = in.nextInt();
switch (answer) {
case 0:
System.out.println("Insert the name file to load.");
Loading(in.next());
break;
case 1:
saveAndQuit();
break;
case 2:
addProduct();
break;
case 3:
inputCode();
break;
case 4:
inventoryValue();
break;
}
}
System.exit(0);
}
private static void inventoryValue() throws FileNotFoundException {
Scanner scanner = new Scanner(new File("SHOP.txt"));
scanner.useDelimiter(";|\n");
Product[] products = new Product[0];
while (scanner.hasNext()) {
String department = scanner.next();
String unityOfMeasure = scanner.next();
int quantity = scanner.nextInt();
double price = scanner.nextDouble();
String code = scanner.next();
String name = scanner.next();
Product newProduct = new Product(department, unityOfMeasure, quantity, price, code, name);
products = newProduct(products, newProduct);
double totalValue = Arrays.stream(products).mapToDouble(p -> p.quantity * p.price).sum();
System.out.println("Total Value: " + totalValue + "\n\n");
for (Product product : products) {
System.out.println(product);
}
}
}
private static Product[] newProduct(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 newProduct;
}
private static void inputCode() throws IOException {
String code;
String line = null;
System.out.println("\nInsert code: ");
code = in.next();
try {
FileReader fileReader = new FileReader("SHOP.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
String[] token = line.split(";");
if ((";" + line + ";").contains((";" + code + ";"))) {
System.out.println(line);
}
}
bufferedReader.close();
} catch (FileNotFoundException ex) {
System.out.println("Impossible to open the file ");
} catch (IOException ex) {
System.out.println("error opening the file ");
}
}
private static void addProduct() {
String department;
String unityOfMeasure;
int quantity;
double price;
String code;
String name;
System.out.println("\ninsert department: ");
department= in.next();
System.out.println("\ninsert unity of measure: ");
unityOfMeasure = in.next();
System.out.println("\ninserit quantity: ");
quantity = in.nextInt();
System.out.println("\ninsert price: ");
price = in.nextDouble();
System.out.println("\ninsert code: ");
code = in.next();
System.out.println("\ninsert name: \n");
name = in.next();
Product p = new Product(department, unityOfMeasure, quantity, price, code, name);
shp.addProduct(p);
}
private static void saveAndQuit() {
running = false;
PrintWriter printWriter = null;
try {
printWriter = new PrintWriter(new FileWriter("SHOP.txt", true));
printWriter.println(shp);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (printWriter != null) {
printWriter.close();
}
}
}
private static void Loading(String name) throws IOException {
FileReader fr;
fr = new FileReader("SHOP.txt");
BufferedReader br;
br = new BufferedReader(fr);
String s;
while (true) {
s = br.readLine();
if (s == null)
break;
System.out.println(s);
}
br.close();
fr.close();
}
}
This is the content of the txt File (SHOP.txt) where products are stored :
H;L;10;10,50;83259875;YellowPaint
E;U;20;1,50;87678350;Lamp
H;L;10;10,50;83259891;BluePaint
H;L;10;10,00;83259892;RedPAint
H;U;30;12,00;98123742;Hammer
G;U;80;15,00;87589302;Seeds
G;U;3;130,00;17483921;Lawnmower
this is the error that i expect to solve:
Total value: 105.0
H;L;10;€10,50;83259875;YellowPaint
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Main.inventoryValue(Main.java:68)
at Main.main(Main.java:47)
How can I solve this problem?
In your file where you say it is storing a double for the price, it should just be a decimal value. You have a '€' symbol in front of it and a ',' instead of a '.'. scanner.nextDouble() will not work if there is another symbol there. I'd recommend to store your prices without the currency symbol and a decimal rather than a comma and just append the '€' in front of wherever you plan on showing your total as so:
System.out.println("Total Value: €" + totalValue + "\n\n");
Related
I am trying to learn Java and am really struggling on part of a problem that I have. I am being asked to write a method to read a text file where each line representing an instance of an object e.g. SalesPerson
The question is asking me to add an identifier id for every line that read in, the id is not present in the text file. I have id declared in my Sales Person class with a constructor and getter and setter methods, and have my method to read the text file below in another class. However it doesn't work and I am not sure where I am going wrong. Could someone give me a pointer..? I would be very grateful.,
public static Collection<SalesPerson> readSalesData() {
String pathname = CXU.FileChooser.getFilename();
File aFile = new File(pathname);
Scanner bufferedScanner = null;
Set<SalesPerson> salesSet = new HashSet<>();
try {
int id;
String name;
String productCode;
int sales;
int years;
Scanner lineScanner;
String currentLine;
bufferedScanner = new Scanner(new BufferedReader(new FileReader(aFile)));
while(bufferedScanner.hasNextLine()) {
currentLine = bufferedScanner.nextLine();
lineScanner = new Scanner(currentLine);
lineScanner.useDelimiter(",");
id = salesPerson.getId();
name = lineScanner.next(); //return the next token as a string
years = lineScanner.nextInt();
productCode = lineScanner.next(); // return the next token as a string
sales = lineScanner.nextInt(); // return the next token as a double
salesSet.add(new SalesPerson(id, name, years, productCode, sales));
}
}
catch (Exception anException) {
System.out.println("Error: " + anException);
}
finally {
try {
bufferedScanner.close();
}
catch (Exception anException) {
System.out.println("Error: " + anException);
}
}
return salesSet;
}
\\Constructor from Class SalesPerson
public SalesPerson(int aId, String aname, int aYears, String aProductCode, int aSales) {
super(); // optional
this.id = ++nextId;
this.name = aname;
this.years = aYears;
this.productCode = aProductCode;
this.sales = aSales;
}
Please check the following code I tried to make things little more simple:
package com.project;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
public class Temp {
public static void main(String[] args) {
Set<SalesPerson> salesPersons = (Set<SalesPerson>) readSalesData();
System.out.println(salesPersons.toString());
}
public static Collection<SalesPerson> readSalesData() {
Set<SalesPerson> salesPersons = new HashSet<>();
try {
File file = new File("D:/file.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
if (line.isEmpty())
break;
String[] rowData = line.split(";");
salesPersons.add(new SalesPerson(rowData[0].trim(), Integer.parseInt(rowData[1].trim()), rowData[2].trim(), Integer.parseInt(rowData[3].trim())));
}
fileReader.close();
} catch (Exception ex) {
System.out.println(ex);
}
return salesPersons;
}
}
package com.project;
public class SalesPerson {
// Static to keep reserve value with each new instance
private static int AUTO_ID = 1;
private int id;
private String name;
private int years;
private String productCode;
private int sales;
public SalesPerson() {
}
public SalesPerson(String name, int years, String productCode, int sales) {
this.id = AUTO_ID;
this.name = name;
this.years = years;
this.productCode = productCode;
this.sales = sales;
AUTO_ID++;
}
// Getters & Setters...
#Override
public String toString() {
return "ID: " + id + ", Name: " + name + ", Years: " + years + ", Product Code: " + productCode + ", Sales: " + sales + System.lineSeparator();
}
}
And this my data file:
FullName1 ; 20; p-code-001; 10
FullName2 ; 30; p-code-002; 14
FullName3 ; 18; p-code-012; 1040
I have created class Patient (pojo), where I have declared variables.
I have added getter and setter methods, as well as a constructor:
public class Patient {
private String patientName;
private String phoneNumber;
private int age;
//generate getter and setter method
public String getPatientName() {
return patientName;
}
public void setPatientName(String patientName) {
this.patientName = patientName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//generate constructor
public Patient(String patientName, String phoneNumber, int age) {
this.patientName = patientName;
this.phoneNumber = phoneNumber;
this.age = age;
}
}
I have created an interface PatientDetails and implemented the methods in the Hospital class.
public interface PatientDetails {
public void addpatient();
public void refreshPatient()throws IOException;
}
Here is how the methods are implemented:
public class Hospital implements PatientDetails {`
Scanner scan = new Scanner(System.in);
int token = 0;
String name, mobileNumber;
static HashMap<Integer, Patient> map = new HashMap<Integer, Patient>();
File file = new File("E:\\Patient\\pt.txt");
int age;
public void addpatient() {
BufferedWriter bufferedWriter = null;
FileWriter fileWriter = null;
try {
// true = append file
// write a data in a file
fileWriter = new FileWriter(file, true);
bufferedWriter = new BufferedWriter(fileWriter);
System.out.println("Enter the name");
scan.nextLine();
name = scan.nextLine();
System.out.println("Enter Mobile number must be 10 digit");
mobileNumber = scan.nextLine();
System.out.println("Enter the age");
age = scan.nextInt();
bufferedWriter.write("TokenNumber:" + token + "," + "PatientName:" + name + ",PhoneNumber:" + mobileNumber
+ ",Age :" + age + ";");
// for nextline
bufferedWriter.newLine();
// close file
bufferedWriter.close();
fileWriter.close();
System.out.println("yours Appoint cofirmed....\nPatient Name: " + name + "\nMobile number: " + mobileNumber
+ "\nToken number is: " + token + "\nAge is:" + age);
token++;
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Something went wrong");
e.printStackTrace();
}
}
#Override
public void refreshPatient() throws IOException {
Patient patient=new Patient(mobileNumber, mobileNumber, age);
String filePath = file.getPath();
System.out.println("refreshed successfully");
String line;
BufferedReader reader = new BufferedReader(new FileReader(filePath));
map=new HashMap<>();
while ((line = reader.readLine()) != null) {
String[] parts = line.split(":", 2);
if (parts.length >= 2) {
String key = parts[0];
String value = parts[1];
//map.put(Integer.parseInt(key), value);
} else {
System.out.println("ignoring line: " + line);
}
}
System.out.println(map);
reader.close();
}`)
I have added the patient name, age, and mobile number into the patient.txt file.
When I call the refresh method all the values should come to the map, but I am not getting the Patient class values into the map.
How to fix that?
you should split with , before :.
I have some problem code I pulled from a book that should not be saying a non-static variable or method needs to be static. The error on the variable comes without me changing anything with that code. The error in the method came after I added code to it but now even when I take the code out it still gives me the error. I have the variable error in Product.java in the getFormattedPrice method in the format currency statement. The method error is in the main method when I call writeProducts.
public class Product
{
private String code;
private String description;
private double price;
public Product(String code, String description, double price)
{
this.code = code;
this.description = description;
this.price = price ;
}
public Product()
{
this("", "", 0);
}
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 static String getFormattedPrice()
{
NumberFormat currency = NumberFormat.getCurrencyInstance();
return currency.format(price);
}
public String getFormattedPrice(double price)
{
NumberFormat currency = NumberFormat.getCurrencyInstance();
return currency.format(price);
}
public boolean equals(Object object)
{
if (object instanceof Product)
{
Product product2 = (Product) object;
if
(
code.equals(product2.getCode()) &&
description.equals(product2.getDescription()) &&
price == product2.getPrice()
)
return true;
}
return false;
}
public String toString()
{
return "Code: " + code + "\n" +
"Description: " + description + "\n" +
"Price: " + this.getFormattedPrice() + "\n";
}
}
main method
public class XMLTesterApp
{
private static String productsFilename = "products.xml";
public static void main(String[] args)
{
System.out.println("Products list:");
ArrayList<Product> products = readProducts();
printProducts(products);
for(Product p2 : products){
System.out.println(p2.getPrice());
}
Product p1 = new Product("test", "XML Tester", 77.77);
products.add(p1);
writeProducts(products);
System.out.println("XML Tester has been added to the XML document.\n");
System.out.println("Products list:");
products = readProducts();
printProducts(products);
products.remove(2);
writeProducts(products);
System.out.println("XML Tester has been deleted from the XML document.\n");
System.out.println("Products list:");
products = readProducts();
printProducts(products);
}
private static ArrayList<Product> readProducts()
{
ArrayList<Product> products = new ArrayList<>();
Product p = null;
XMLInputFactory inputFactory = XMLInputFactory.newFactory();
try{
FileReader fileReader = new
FileReader("C:\\Users\\AndrewSpiteri\\Documents\\Classes\\Baker\\CS 242\\java\\netbeans\\ex_starts\\ch19_ex1_XMLTester\\products.xml");
XMLStreamReader reader = inputFactory.createXMLStreamReader(fileReader);
while(reader.hasNext()){
int eventType = reader.getEventType();
switch(eventType){
case XMLStreamConstants.START_ELEMENT:
String elementName = reader.getLocalName();
if(elementName.equals("Product")){
p = new Product();
String code = reader.getAttributeValue(0);
p.setCode(code);
}
if(elementName.equals("Description")){
String description = reader.getElementText();
p.setDescription(description);
}
if(elementName.equals("Price")){
String priceString = reader.getElementText();
double price = Double.parseDouble(priceString);
p.setPrice(price);
}
break;
case XMLStreamConstants.END_ELEMENT:
elementName = reader.getLocalName();
if(elementName.equals("Product"))
products.add(p);
break;
default:
break;
}
reader.next();
}
}
catch(IOException | XMLStreamException e){
System.out.println(e);
}
// add code that reads the XML document from the products.xml file
return products;
}
private void writeProducts(ArrayList<Product> products)
{
XMLOutputFactory outputFactory = XMLOutputFactory.newFactory();
try{
FileWriter fileWriter = new
FileWriter("C:\\Users\\AndrewSpiteri\\Documents\\Classes\\Baker\\CS 242\\java\\netbeans\\ex_starts\\ch19_ex1_XMLTester\\products.xml");
XMLStreamWriter writer = outputFactory.createXMLStreamWriter(fileWriter);
writer.writeStartDocument("1.0");
writer.writeStartElement("Products");
for(Product product : products){
writer.writeStartElement("Product");
writer.writeAttribute("Code", product.getCode());
writer.writeStartElement("Description");
writer.writeCharacters(product.getDescription());
writer.writeEndElement();
writer.writeStartElement("Price");
double price = product.getPrice();
writer.writeCharacters(Double.toString(price));
writer.writeEndElement();
writer.writeEndElement();
}
writer.writeEndElement();
writer.flush();
writer.close();
}
catch(IOException | XMLStreamException e){
System.out.println(e);
}
}
private static void printProducts(ArrayList<Product> products)
{
for (Product p : products)
{
printProduct(p);
}
System.out.println();
}
private static void printProduct(Product p)
{
String productString =
StringUtils.padWithSpaces(p.getCode(), 8) +
StringUtils.padWithSpaces(p.getDescription(), 44) +
p.getFormattedPrice();
System.out.println(productString);
}
}
Remove the static from this method.
public static String getFormattedPrice()
{
NumberFormat currency = NumberFormat.getCurrencyInstance();
return currency.format(price);
}
You get the error because price in an instance variable, not a static class variable.
And add static to private void writeProducts in order to call writeProducts from another static method.
So in my program I am trying to create a basic .txt file within the project to write/read individual customer objects to. Here is my code for both reading and writing to the file. The program runs with out compilation errors and rights with out throwing an exception but when I try to read the file the program throws "no such file or directory, null" As requested here is all the code for the program as it sits: you get the menu enter 1 to add a customer (that seems to work or so i think) then enter 2 to load and display said customer data that is not working.
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class Bank {
public static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
do {
try {
System.out.println("-----------------------------------");
System.out.println(" Main Menu");
System.out.println("-----------------------------------");
System.out.println("");
System.out.println(" Item Description");
System.out.println(" ---- --------------------------");
System.out.println(" 1 Creat a new customer");
System.out.println(" 2 View an existing customer");
System.out.println(" 3 Exit the program");
System.out.println("");
System.out.println(" Please enter your choice: ");
int select = Integer.valueOf(in.nextLine());
switch ( select ) {
case 1:
createCustomer();
break;
case 2:
viewCustomer();
break;
case 3:
System.exit(0);
break;
default:
System.out.println("\nInvalid selection.");
break;
}
}
catch ( Exception e) {
System.out.println(e.getMessage());
}
} while( true );
}
//----------------------------Main Methods-------------------------------------------\\
public static void createCustomer() {
try {
String select;
System.out.println("");
System.out.println("-----------------------------------");
System.out.println(" Create Customer");
System.out.println("-----------------------------------");
System.out.print("Customer name: ");
String customerName = in.nextLine();
System.out.print("Customer number: ");
String customerNum = in.nextLine();
Customer newCustomer = new Customer( customerName, customerNum);
System.out.print("Checking account? (y/n): ");
select = in.nextLine();
if ( select.equalsIgnoreCase("y") ) {
System.out.print("\tBalance: ");
double intBalance = Double.valueOf(in.nextLine());
Checking newChecking = new Checking("001", intBalance);
newCustomer.addAccount(newChecking);
}
System.out.print("Saving account? (y/n): ");
select = in.nextLine();
if ( select.equalsIgnoreCase("y") ) {
System.out.print("\t APR: ");
double apr = Double.valueOf(in.nextLine());
System.out.print("\tBalance: ");
double intBalance = Double.valueOf(in.nextLine());
Savings newSavings = new Savings("002", intBalance);
Savings.setAnnualPercentageRate(apr);
newCustomer.addAccount(newSavings);
}
System.out.print("Money Market account? (y/n): ");
select = in.nextLine();
if ( select.equalsIgnoreCase("y") ) {
System.out.print("\t APR: ");
double apr = Double.valueOf(in.nextLine());
MoneyMarket.setAnnualPercentageRate(apr);
System.out.print("Minimum Balance: 1200.00");
System.out.print("\tBalance: ");
double intBalance = Double.valueOf(in.nextLine());
MoneyMarket newMoneyMarket = new MoneyMarket("003", intBalance);
newCustomer.addAccount(newMoneyMarket);
}
Customer.saveCustomer(newCustomer);
System.out.println(newCustomer.getCustomerDetails());
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}
public static void viewCustomer() {
System.out.println("");
System.out.println("-----------------------------------");
System.out.println(" View Customer");
System.out.println("-----------------------------------");
System.out.println(" \nEnter Customer number: ");
String customerNum = in.nextLine();
Customer newCustomer = Customer.loadCustomer(customerNum);
System.out.println(newCustomer.getCustomerDetails());
}
}
//=====================================================================================\\
interface ITaxable {
double getTaxesDue();
}
//=====================================================================================\\
abstract class Account {
private String accountNum;
private double balance;
public Account(String accountNum, double amount) throws Exception {
deposit(amount);
setAccountNum(accountNum);
}
public void setAccountNum(String accountNum) {
this.accountNum = accountNum;
}
public String getAccountNum() {
return accountNum;
}
public double getBalance() {
return balance;
}
public void deposit(double amount) throws Exception {
if ( amount < 0){
throw new Exception("Must enter a deposit greater than 0.");
}
else {
balance += amount;
}
}
public void withdraw(double amount) throws Exception {
if ( amount > getBalance() ){
throw new Exception("Amount exceeds balance.");
}
else {
balance -= amount;
}
}
public String toString() {
return "Account Number: " + accountNum + ", Balance: " + balance;
}
}
//=====================================================================================\\
class Checking extends Account {
public Checking(String accountNum, double amount) throws Exception {
super(accountNum, amount);
}
public void cashCheck(int checkNum, int amount) throws Exception {
this.withdraw(amount);
}
public String toString(){
return "CHK" +getAccountNum()+ " " +getBalance();
}
}
//=====================================================================================\\
class Savings extends Account implements ITaxable {
static double annualPercentageRate;
public Savings( String accountNum, double amount ) throws Exception {
super(accountNum, amount);
}
public static void setAnnualPercentageRate(double annualPercentageRate) throws Exception {
if ( annualPercentageRate > 0 ) {
Savings.annualPercentageRate = annualPercentageRate;
}
else {
throw new Exception("APR rate must be greater then 0.");
}
}
public static double getAnnualPercentageRate() {
return annualPercentageRate;
}
public void addInterest() throws Exception {
int numberOfDays = 30;
double interest = getBalance() * numberOfDays * (getAnnualPercentageRate() / 100 / 365);
deposit(interest);
}
#Override public double getTaxesDue(){ return 0;}
public String toString(){
return "SAV" +getAccountNum()+ " " +getBalance();
}
}
//=====================================================================================\\
class MoneyMarket extends Savings{
static double miniumBalance = 1200;
public MoneyMarket( String accountNum, double balance ) throws Exception {
super(accountNum, balance);
if ( balance < miniumBalance ) {
throw new Exception("Minimum balance not met.");
}
}
public static void setMiniumBalance( double amount) throws Exception {
if ( amount < 0 ){
throw new Exception("Must enter a amount greater then 0.");
}
else {
MoneyMarket.miniumBalance = miniumBalance;
}
}
public static double getMiniumBalance() {
return miniumBalance;
}
#Override
public void withdraw( double amount ) throws Exception {
if ( getBalance() - amount > miniumBalance ) {
super.withdraw(amount);
}
else {
throw new Exception("Amount is greater then minimum balance.");
}
}
public String toString() {
return "MMA " +getAccountNum()+" "+getBalance();
}
}
//=====================================================================================\\
class Customer{
private String customerName;
private String customerNum;
private ArrayList<Account> accounts = new ArrayList<Account>();
public Customer( String customerName, String cutomerNum) {
setCustomerName(customerName);
setCustomerNum(cutomerNum);
}
public void setCustomerName( String customerName ) { this.customerName = customerName; }
public void setCustomerNum( String customerNum ) { this.customerNum = customerNum; }
public String getCustomerName() { return customerName; }
public String getCustomerNum() { return customerNum; }
public void addAccount(Account a) throws Exception {
if (a != null) {
accounts.add(a);
}
else {
throw new Exception("Invalid entry");
}
}
public static void saveCustomer(Customer c) throws Exception {
if ( c != null) {
String fileName = c.customerNum + ".txt";
OutputStream file = new FileOutputStream(fileName);
OutputStream buffer = new BufferedOutputStream(file);
ObjectOutput output = new ObjectOutputStream(buffer);
output.writeObject(c);
OutputStream close;
}
else {
throw new Exception("Customer does not exist.");
}
System.out.println("\nCustomer Saved.");
}
public static Customer loadCustomer(String customerNum) {
try {
String fileName = customerNum + ".txt";
InputStream file = new FileInputStream(fileName);
InputStream buffer = new BufferedInputStream(file);
ObjectInput input = new ObjectInputStream(buffer);
Customer x = (Customer) input.readObject();
InputStream close;
return x;
}
catch (Exception e) {
System.out.println(e.getMessage());
return null;
}
}
public String getCustomerDetails() {
String dets;
dets = "\nCUSTOMER DETAIL REPORT\n" +
"-------------------------------------------\n";
dets += String.format("%s (#%s)\n", this.getCustomerName(), this.getCustomerNum());
for (Account a : accounts) {
dets += String.format("\t%s\n", a);
}
return dets;
}
#Override public String toString() { return customerName; }
}
//=====================================================================================\\
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Please I would like know How would I implement JOptionPane instead of import java.util.Scanner;
I also have 4 separate classes
If i implement JOptionPane will it clean up the code I would also like to know any changes anyone would make.
Employee.Class
import java.text.NumberFormat;
import java.util.Scanner;
public class Employee {
public static int numEmployees = 0;
protected String firstName;
protected String lastName;
protected char gender;
protected int dependents;
protected double annualSalary;
private NumberFormat nf = NumberFormat.getCurrencyInstance();
public Benefit benefit;
private static Scanner scan;
public Employee() {
firstName = "";
lastName = "";
gender = 'U';
dependents = 0;
annualSalary = 40000;
benefit = new Benefit();
numEmployees++;
}
public Employee(String first, String last, char gen, int dep, Benefit benefit1) {
this.firstName = first;
this.lastName = last;
this.gender = gen;
this.annualSalary = 40000;
this.dependents = dep;
this.benefit = benefit1;
numEmployees++;
}
public double calculatePay1() {
return annualSalary / 52;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("First Name: ").append(firstName).append("\n");
sb.append("Last Name: ").append(lastName).append("\n");
sb.append("Gender: ").append(gender).append("\n");
sb.append("Dependents: ").append(dependents).append("\n");
sb.append("Annual Salary: ").append(nf.format(getAnnualSalary())).append("\n");
sb.append("Weekly Pay: ").append(nf.format(calculatePay1())).append("\n");
sb.append(benefit.toString());
return sb.toString();
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public <Gender> void setGender(char gender) {
this.gender = gender;
}
public <Gender> char getGender() {
return gender;
}
public void setDependents(int dependents) {
this.dependents = dependents;
}
public void setDependents(String dependents) {
this.dependents = Integer.parseInt(dependents);
}
public int getDependents() {
return dependents;
}
public void setAnnualSalary(double annualSalary) {
this.annualSalary = annualSalary;
}
public void setAnnualSalary(String annualSalary) {
this.annualSalary = Double.parseDouble(annualSalary);
}
public double getAnnualSalary() {
return annualSalary;
}
public double calculatePay() {
return annualSalary / 52;
}
public double getAnnualSalary1() {
return annualSalary;
}
public static void displayDivider(String outputTitle) {
System.out.println(">>>>>>>>>>>>>>> " + outputTitle + " <<<<<<<<<<<<<<<");
}
public static String getInput(String inputType) {
System.out.println("Enter the " + inputType + ": ");
scan = new Scanner(System.in);
String input = scan.next();
return input;
}
public static int getNumEmployees() {
return numEmployees;
}
public static void main(String[] args) {
displayDivider("New Employee Information");
Benefit benefit = new Benefit();
Employee employee = new Employee("George", "Anderson", 'M', 5, benefit);
System.out.println(employee.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Hourly Temp Employee Information");
Hourly hourly = new Hourly("Mary", "Nola", 'F', 5, 14, 45, "temp");
System.out.println(hourly.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Hourly Full Time Employee Information");
Hourly hourly1 = new Hourly("Mary", "Nola", 'F', 5, 18, 42, "full time");
System.out.println(hourly1.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Hourly Part Time Employee Information");
Hourly hourly11 = new Hourly("Mary", "Nola", 'F', 5, 18, 20, "part time");
System.out.println(hourly11.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Salaried Revised Employee Information");
Benefit benefit1 = new Benefit("None", 500, 3);
Salaried salaried = new Salaried("Frank", "Lucus", 'M', 5, 150000, benefit1, 3);
System.out.println(salaried.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Salaried Employee Information");
Benefit benefit11 = new Benefit("None", 500, 3);
Salaried salaried1 = new Salaried("Frank", "Lucus", 'M', 5, 100000, benefit11, 2);
System.out.println(salaried1.toString());
System.out.println("Total employees: " + getNumEmployees());
}
}
SALARIED.CLASS
import java.util.Random;
import java.util.Scanner;
public class Salaried extends Employee {
private static final int MIN_MANAGEMENT_LEVEL = 0;
private static final int MAX_MANAGEMENT_LEVEL = 3;
private static final int BONUS_PERCENT = 10;
private int managementLevel;
private Scanner in;
public Salaried() {
super();
Random rand = new Random();
managementLevel = rand.nextInt(4) + 1;
if (managementLevel == 0) {
System.out.println("Not Valid");
}
//numEmployees++;
}
private boolean validManagementLevel(int level) {
return (MIN_MANAGEMENT_LEVEL <= level && level <= MAX_MANAGEMENT_LEVEL);
}
public Salaried(String fname, String lname, char gen, int dep,
double sal, Benefit ben, int manLevel)
{
super.firstName = fname;
super.lastName = lname;
super.gender = gen;
super.dependents = dep;
super.annualSalary = sal;
super.benefit = ben;
while (true) {
if (!validManagementLevel(manLevel)) {
System.out.print("Invalid management level, please enter
another management level value in range [0,3]: ");
manLevel = new Scanner(System.in).nextInt();
} else {
managementLevel = manLevel;
break;
}
}
//numEmployees++;
}
public Salaried(double sal, int manLevel) {
super.annualSalary = sal;
while (true) {
if (!validManagementLevel(manLevel)) {
System.out.print("Invalid management level, please enter another
management level value in range [0,3]: ");
in = new Scanner(System.in);
manLevel = in.nextInt();
} else {
managementLevel = manLevel;
break;
}
}
// numEmployees++;
}
#Override
public double calculatePay() {
double percentage = managementLevel * BONUS_PERCENT;
return (1 + percentage/100.0) * annualSalary / 52;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(super.toString());
sb.append("Management Level: ").append(managementLevel).append("\n");
return sb.toString();
}
}
Hourly.Class
import java.util.Scanner;
public class Hourly extends Employee {
private static final double MIN_WAGE = 10;
private static final double MAX_WAGE = 75;
private static final double MIN_HOURS = 0;
private static final double MAX_HOURS = 50;
private double wage;
private double hours;
private String category;
private Scanner in;
private Scanner in2;
private Scanner in3;
private Scanner in4;
public Hourly() {
super();
this.wage = 20;
this.hours= 30;
this.category = "full time";
annualSalary = wage * hours * 52;
}
public Hourly(double wage_, double hours_, String category_) {
while (true) {
if (!validWage(wage_)) {
System.out.print("Invalid wage: ");
in2 = new Scanner(System.in);
wage_ = in2.nextDouble();
} else {
this.wage = wage_;
break;
}
}
while (true) {
if (!validHour(hours_)) {
System.out.print("Invalid hours: ");
in = new Scanner(System.in);
hours_ = in.nextDouble();
} else {
this.hours = hours_;
break;
}
}
while (true) {
if (!validCategory(category_)) {
System.out.print("Invalid category, please enter another category value: ");
category_ = new Scanner(System.in).next();
} else {
this.category = category_;
break;
}
}
annualSalary = wage * hours * 52;
//numEmployees++;
}
public Hourly(String fname, String lname, char gen, int dep, double wage_,double hours_, String category_) {
super.firstName = fname;
super.lastName = lname;
super.gender = gen;
super.dependents = dep;
super.annualSalary = annualSalary;
super.benefit = benefit;
while (true) {
if (!validWage(wage_)) {
System.out.print("Invalid wage : ");
in3 = new Scanner(System.in);
wage_ = in3.nextDouble();
} else {
this.wage = wage_;
break;
}
}
while (true) {
if (!validHour(hours_)) {
System.out.print("Invalid hours : ");
hours_ = new Scanner(System.in).nextDouble();
} else {
this.hours = hours_;
break;
}
}
while (true) {
if (!validCategory(category_)) {
System.out.print("Invalid category, please enter another category value: ");
in4 = new Scanner(System.in);
category_ = in4.next();
} else {
this.category = category_;
break;
}
}
annualSalary = wage * hours * 52;
//numEmployees++;
}
private boolean validHour(double hour) {
return (MIN_HOURS <= hour && hour <= MAX_HOURS);
}
private boolean validWage(double wage) {
return (MIN_WAGE <= wage && wage <= MAX_WAGE);
}
private boolean validCategory(String category) {
String[] categories = {"temp", "part time", "full time"};
for (int i = 0; i < categories.length; i++)
if (category.equalsIgnoreCase(categories[i]))
return true;
return false;
}
public double calculatePay() {
return annualSalary / 52;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(super.toString());
sb.append("Wage: ").append(wage).append("\n");
sb.append("Hours: ").append(hours).append("\n");
sb.append("Category: ").append(category).append("\n");
return sb.toString();
}
}
Benefit.Class
public class Benefit {
private String healthInsurance;
private double lifeInsurance;
private int vacationDays;
public Benefit() {
healthInsurance = "Full";
lifeInsurance = 100;
vacationDays = 5;
}
public Benefit(String health, double life, int vacation) {
setHealthInsurance(health);
setLifeInsurance(life);
setVacation(vacation);
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Health Insurance: ").append(healthInsurance).append("\n");
sb.append("Life Insurance: ").append(lifeInsurance).append("\n");
sb.append("Vacation Days: ").append(vacationDays).append("\n");
return sb.toString();
}
public void setHealthInsurance(String healthInsurance) {
this.healthInsurance = healthInsurance;
}
public String getHealthInsurance() {
return healthInsurance;
}
public void setLifeInsurance(double lifeInsurance) {
this.lifeInsurance = lifeInsurance;
}
public double getLifeInsurance() {
return lifeInsurance;
}
public void setVacation(int vacation) {
this.vacationDays = vacation;
}
public int getVacation() {
return vacationDays;
}
public void displayBenefit() {
this.toString();
}
}
Start by taking a look at How to Make Dialogs...
What you basically want is to use JOptionPane.showInputDialog, which can be used to prompt the use for input...
Yes, there are a few flavours, but lets keep it simply and look at JOptionPane.showInputDialog(Object)
The JavaDocs tells us that...
message - the Object to display
Returns:user's input, or null meaning the user canceled the input
So, from that we could use something like...
String value = JOptionPane.showInputDialog("What is your name?");
if (value != null) {
System.out.println("Hello " + value);
} else {
System.out.println("Hello no name");
}
Which displays...
Now, if we take a look at your code, you could replace the use of scan with...
public static String getInput(String inputType) {
String input = JOptionPane.showInputDialog("Enter the " + inputType + ": ");
return input;
}
As an example...
Now, what I might recommend is creating a simple helper method which can be used to prompt the user in a single line of code, for example...
public class InputHelper {
public static String promptUser(String prompt) {
String input = JOptionPane.showInputDialog(prompt);
return input;
}
}
which might be used something like...
String value = InputHelper.promptUser("Please enter the hours worked");
hours_ = Double.parse(value);
And this is where it get's messy, as you will now need to valid the input of the user.
You could extend the idea of the InputHelper to do automatic conversions and re-prompt the user if the value was invalid...as an idea
It is much easier than you think, if you try. Get used to reading the Java API.
http://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html
Even has examples.
String input;
JOptionPane jop=new JOptionPane();
input=jop.showInputDialog("Question i want to ask");
System.out.println(input);