Currency Exchange Program - java

Attached is my finalized code for a Lab project. I have everything done but for some reason my code sits idle? I think it may be an issue between the "bank1" and "bank2" objects and the Bank class?
I apologize that the code is so long, as I don not know where the issue is. Help please :(
Currency Exchange Class (main)
import javax.swing.*;
import java.io.FileNotFoundException;
import java.util.*;
public class CurrencyExchange {
public static void main(String [] args) throws FileNotFoundException {
//Create 2 bank objects, one for each file "bank1.txt" & "bank2.txt"
Bank bank1 = new Bank("bank1.txt");
Bank bank2 = new Bank("bank2.txt");
int userCont = 0;
do {
boolean buy = false;
double amount;
int banksSupported = 0;
String currencyCode;
Scanner keyboard = new Scanner(System.in);
String userAnswer;
//Ask user to buy or sell - use continue to repeat loop if invalid
System.out.println("Do you want to buy or sell?");
userAnswer = keyboard.nextLine();
if (!userAnswer.equalsIgnoreCase("buy") && (!userAnswer.equalsIgnoreCase("sell")) ) {
System.out.println("Invalid response. Please enter buy or sell. ");
continue;
}
if (userAnswer.equalsIgnoreCase("buy")) {
buy = true;
}
//Ask user for foreign currency - use continue to repeat loop if invalid
System.out.println("Which currency would you like to use?");
currencyCode = keyboard.nextLine().toUpperCase();
//Check and Print how many banks support the users currency - use continue to repeat loop if none
if(bank1.supportCurrency(currencyCode))
++banksSupported;
if(bank2.supportCurrency(currencyCode))
++banksSupported;
if (banksSupported == 0) {
System.out.println("There are no banks the support " + currencyCode + ". Please enter a different currency.");
continue;
}
else if (banksSupported == 1) {
System.out.println("One bank supports " + currencyCode + ".");
}
else {
System.out.println("Two banks support " + currencyCode + ".");
}
//Prompt the user for the amount of foreign currency and get the user input
System.out.println(" What amount of " + currencyCode + "?");
amount = keyboard.nextDouble();
//Use the quoteBuy or quoteSell methods of the Bank objects to get a Quote from every bank supporting the foreign currency.
//Print the quote(s) from the bank(s), using the toString method of the Quote object(s).
if(buy) {
if (bank1.supportCurrency(currencyCode)) {
System.out.println(bank1.quoteBuy(amount, currencyCode));
}
if (bank2.supportCurrency(currencyCode)) {
System.out.println(bank2.quoteBuy(amount, currencyCode));
}
}
else {
if (bank1.supportCurrency(currencyCode)) {
System.out.println(bank1.quoteBuy(amount, currencyCode));
}
if (bank2.supportCurrency(currencyCode)) {
System.out.println(bank2.quoteBuy(amount, currencyCode));
}
}
//Use the console to prompt the user for another transaction.
userCont = JOptionPane.showConfirmDialog(null, "Would you like to preform another transaction?", "Contniue", JOptionPane.YES_NO_OPTION);
} while(userCont == 0); // while ( the user wants to continue performing transactions )
}
}
Bank Class
import java.io.*;
import java.util.*;
public class Bank {
// Five private data fields: The name of the bank, The commission rate, Three fields for the three currencies exchanged by the bank.
// Each of these should have type Currency.
private String bankName;
private double commissionRate;
private Currency currencyCode1;
private Currency currencyCode2;
private Currency currencyCode3;
public Bank(String fileA) throws FileNotFoundException {
File bankFile = new File(fileA);
Scanner keyboard = new Scanner(System.in);
this.bankName = keyboard.nextLine();
this.commissionRate = Double.parseDouble((keyboard.nextLine()));
this.currencyCode1 = new Currency(keyboard.next(), Double.parseDouble(keyboard.next()));
this.currencyCode2 = new Currency(keyboard.next(), Double.parseDouble(keyboard.next()));
this.currencyCode3 = new Currency(keyboard.next(), Double.parseDouble(keyboard.next()));
keyboard.close();
}
public boolean supportCurrency(String currencyCode) {
return currencyCode.equalsIgnoreCase(currencyCode1.getCurrencyCode())
|| currencyCode.equalsIgnoreCase(currencyCode2.getCurrencyCode())
|| currencyCode.equalsIgnoreCase(currencyCode3.getCurrencyCode());
}
// Working on getRate method.
public double getRate(String currencyCode) {
double bankExchangeRate = -1.0;
if (currencyCode.equalsIgnoreCase(currencyCode1.getCurrencyCode())) {
bankExchangeRate = currencyCode1.getExchangeRate();
}
else if (currencyCode.equalsIgnoreCase(currencyCode2.getCurrencyCode())) {
bankExchangeRate = currencyCode2.getExchangeRate();
}
else if (currencyCode.equalsIgnoreCase(currencyCode3.getCurrencyCode())) {
bankExchangeRate = currencyCode3.getExchangeRate();
}
return bankExchangeRate; //return -1.0
}
public Quote quoteBuy(double amt, String currencyCode) {
double rate = getRate(currencyCode);
Quote quote;
if(rate == -1.0) {
quote = null;
}
else {
double userOwes = amt / (rate * (1 - commissionRate)); // This calculates the commission amount based on the dollar amount.
double commission = userOwes * commissionRate;
quote = new Quote(bankName, "USD", userOwes, currencyCode, amt, commissionRate, commission);
}
return quote;
}
public Quote quoteSell(double amt, String currencyCode) {
double rate = getRate(currencyCode);
Quote quote;
if(rate == -1.0) {
quote = null;
}
else {
double base = amt / rate; // This calculates the dollar value of the foreign currency.
double commission = commissionRate * base; // This calculates the commission amount based on the dollar amount.
double amtConverted = base - commission; // The bank takes a cut.
quote = new Quote(bankName, currencyCode, amt, "USD", amtConverted, commissionRate, commission);
}
return quote;
}
}
Currency Class
public class Currency {
// Two private data fields, one to hold the currency code and one to hold the exchange rate.
// Note that the exchange rate for the same currency could be different for different banks
private final String currencyCode;
private final double exchangeRate;
// A constructor that takes two arguments: the currency code and exchange rate.
// The constructor should assign the private members from the values of the arguments.
public Currency(String currencyCode, double currencyExchangeRate) {
this.currencyCode = currencyCode;
this.exchangeRate = currencyExchangeRate;
}
// An accessor method (getter) for each data field.
public String getCurrencyCode() {
return currencyCode;
}
public double getExchangeRate() {
return exchangeRate;
}
}
Quote Class
import java.text.DecimalFormat;
public class Quote {
private String bankName;
private String codeToBank;
private double amtToBank;
private String codeFromBank;
private double amtFromBank;
private double commissionRate;
private double commissionAmt$;
DecimalFormat decimalFormat;
public Quote(String bankName, String currencyCode, double amt, String usd, double amtConverted, double commissionRate, double commission) {
this.bankName = bankName;
this.codeToBank = currencyCode;
this.amtToBank = amt;
this.codeFromBank = usd;
this.amtFromBank = amtConverted;
this.commissionRate = commissionRate;
this.commissionRate = commission;
this.decimalFormat = new DecimalFormat("0.00");
}
public String toString() {
return (this.bankName + " is willing to offer you " + decimalFormat.format(this.amtFromBank)
+ " " + this.codeFromBank + " for "
+ decimalFormat.format(this.amtToBank) + " "
+ this.codeToBank + ", after collecting a commission of "
+ decimalFormat.format(this.commissionRate)
+ " USD (" + Math.round(100 * this.commissionRate) + "%)");
}
}

Your issue is that your Scanner is reading from System.in, when it should be reading from the input files "bank1.txt" or "bank2.txt".
Change this line in Bank:
Scanner keyboard = new Scanner(System.in);
to this:
Scanner keyboard = new Scanner(bankFile);
And your code will work as intended.

Related

Create an array list in java and store values tied to an employee name

I have a program that calculates an employees annual salary based upon there base salary and commission sales. I want to take the program a step further and create an arrayList that will ask for the employee name and then create an array, store the values from the program and print out those values for each employee name inputted.
I imagine that I need to create a for or a else loop to collect the data. Problem is I'm not sure where to do that and how to create the array. I have two classes:
1 class for my commission variable's and calculations:
package Commissions;
public class Calculations {
double totalSales;
private double comRate = 0.025;
private double annualSal = 80000;
private double salesTarget = 120000;
private double acceleration = 0.015;
private double compensation;
public Calculations (double TotalSales) {
this.totalSales = totalSales;
}
public double getCommissionCalc () {
if (totalSales >= salesTarget) {
compensation = (annualSal + (totalSales * (comRate + acceleration)));
return compensation;
} else if (totalSales >= salesTarget * .8) {
compensation = (annualSal + (totalSales * comRate));
return compensation;
} else {
compensation = annualSal;
return compensation;
}
}
}
1 class for my main and user input
package Commissions;
import java.text.NumberFormat;
import java.util.*;
public class paycheck {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner (System.in);
NumberFormat nf = NumberFormat.getCurrencyInstance();
System.out.println("Enter the employee name: ");
long empName = input.nextLong();
mediaArray[empName];
System.out.println("Enter your total sales for the year: ");
double totalSales = input.nextDouble();
System.out.println("\r");
Calculations c = new Calculations (totalSales);
System.out.println("Your Total compensation with your annual sales is: " + nf.format(c.getCommissionCalc()));
System.out.println("\r");
System.out.println("If you were to increase your sales you could earn even more money!");
System.out.println("\r");
double i = totalSales + 5000;
double finish = totalSales * 1.5;
while (i <= finish) {
c.totalSales = i;
System.out.println("If you were to increase your sales commission to " + nf.format(i) + " you could earn: " + nf.format(c.getCommissionCalc()));
i = i + 5000;
}
}
}
Here is the code as per my understanding of your problem, had to correct few things as you are saying enter name but taking long as input:
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Paycheck {
public static void main(String[] args) {
List<Employee> empList = new ArrayList<Employee>();
while (true) {
Scanner input = new Scanner(System.in);
NumberFormat nf = NumberFormat.getCurrencyInstance();
System.out.println("Enter the employee name (enter exit to exit): ");
String empName = input.nextLine();
// mediaArray[empName];
if(empName.equals("exit")) {
break;
}
System.out.println("Enter your total sales for the year: ");
double totalSales = input.nextDouble();
Calculations c = new Calculations(totalSales);
System.out
.println("Your Total compensation with your annual sales is: "
+ nf.format(c.getCommissionCalc()));
System.out.println("\r");
System.out
.println("If you were to increase your sales you could earn even more money!");
System.out.println("\r");
double i = totalSales + 5000;
double finish = totalSales * 1.5;
while (i <= finish) {
c.totalSales = i;
System.out
.println("If you were to increase your sales commission to "
+ nf.format(i)
+ " you could earn: "
+ nf.format(c.getCommissionCalc()));
i = i + 5000;
}
System.out.println("\r");
//store employee data into arraylist
empList.add(new Employee(empName, i));
}
for(Employee emp : empList) {
System.out.println("Employee Name: " + emp.getName() + " Total Sales: " + emp.getSales());
}
}
}
class Employee {
private String name;
private Double sales;
public Employee(String empName, double totalSales) {
this.name = empName;
this.sales = totalSales;
}
public Double getSales() {
return sales;
}
public void setSales(Double sales) {
this.sales = sales;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

Looping through an arraylist [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
Hi all I'm trying to loop through an array using a password of 4 letters and an ID of 4 int numbers.
Thus far I can create the two 'keys' BUT I can't get them to search for the account on the arraylist I have despite it's creation. I really don't know how to fix this problem since the only way seems to be to just call for an 'If' statement or switch.
Here is where I have the code set up:
int acctID;
int depositingAmount;
//System.out.println("Input your ID and then your password to deposit money.");
String inputID = JOptionPane.showInputDialog("Please input your ID to begin depositing money.");
acctID = Integer.parseInt(inputID);
String inputPassword = JOptionPane.showInputDialog("Please input your password to verify your account.");
// int depositAmount;
// do {
for (int i = 0; i < bankAccounts.size(); i++)//Loops through accounts in my arraylist.
{
if (acctID == bankAccounts.get(i).getAccountId() && inputPassword == bankAccounts.get(i).getPassword())//If ID and password work are true then it goes in here.
{
String depositAmount = JOptionPane.showInputDialog("Please input how much money you want to "
+ "input");//An here is where you would be able to spit out how much money to deposit.
depositingAmount = Integer.parseInt(depositAmount);
bankAccounts.get(i).deposit(depositingAmount);
break;
}
}
Like you can see the loop in theory is suppose to go "Oh okay lets me start going though all of the accounts in the list until I get to yours" and when it finds it "oh hey I found your account, here let me give you the deposit feature". Sorry if I tried to simplify it too much in this paragraph its just that this problem is frustrating me too no end because I know that if I can solve this then the rest of my project is done. I have a withdraw feature also but that's basically the same thing but playing with different methods on the same class.
EDIT: Here are the constructors
public BankAccount() {//ADDED TWO PARAMETERS
//NO ARGUMENT CONSTRUCTOR
accountId = (int) (Math.random() * 9000) + 999;
//RANDBETWEEN
setAccountBalance(0);
Random passcode = new Random();
//char charcs = (char)(passcode.nextInt(26) + 'a');
//Added string.
String chars = "abcdefghijklmnopqrstuvwxyz";
int length = chars.length();
for (int i = 0; i < 4; i ++){
password += chars.split("")[ (int) (Math.random() * (length - 1)) ];}
}
public BankAccount(double accountBalance) { // ONE ARGUMENT CONSTRUCTOR
accountId = (int) (Math.random() * 9000) + 1000;
setAccountBalance(accountBalance);
//Random passcode = new Random();
//password = (String) (passcode.nextInt(26)) + 'a';
//NEED A VARIABLE TO PASS IN
//4 Digit password
String chars = "abcdefghijklmnopqrstuvwxyz";
int length = chars.length();
for (int i = 0; i < 4; i ++){
password += chars.split("")[ (int) (Math.random() * (length - 1)) ];}
}
An here are the getters..
public int getAccountId() {
return accountId;
}
public String getPassword() {
return password;
}
Also here are the fields I created..
private int accountId;
private double accountBalance;
private static double annualInterestRate = 0.045;
private static java.util.Date dateCreated = new java.util.Date();
private String name;
private String password = "";
Here is where I stand with the If statement
if (acctID == bankAccounts.get(i).getAccountId() && inputPassword.equals(bankAccounts.get(i).getPassword()))
I've seen the other thread that's been posted has a similar question but their answer of just putting .equals() is not enough. Unless i'm stuppose to just take out bankAccounts from the line.
EDIT 2: The entire code.
import java.util.Random;
public class BankAccount {
private int accountId;
private double accountBalance;
private static double annualInterestRate = 0.045;
private static java.util.Date dateCreated = new java.util.Date();
private String name;
private String password = "";
public BankAccount() {//ADDED TWO PARAMETERS
//NO ARGUMENT CONSTRUCTOR
accountId = (int) (Math.random() * 9000) + 999;
//RANDBETWEEN
setAccountBalance(0);
Random passcode = new Random();
//char charcs = (char)(passcode.nextInt(26) + 'a');
//Added string.
String chars = "abcdefghijklmnopqrstuvwxyz";
int length = chars.length();
for (int i = 0; i < 4; i ++){
password += chars.split("")[ (int) (Math.random() * (length - 1)) ];}
}
public BankAccount(double accountBalance) { // ONE ARGUMENT CONSTRUCTOR
accountId = (int) (Math.random() * 9000) + 1000;
setAccountBalance(accountBalance);
//Random passcode = new Random();
//password = (String) (passcode.nextInt(26)) + 'a';
//NEED A VARIABLE TO PASS IN
//4 Digit password
String chars = "abcdefghijklmnopqrstuvwxyz";
int length = chars.length();
for (int i = 0; i < 4; i ++){
password += chars.split("")[ (int) (Math.random() * (length - 1)) ];}
}
public int getAccountId() {
return accountId;
}
public double getAccountBalance() {
return accountBalance;
}
public void setAccountBalance(double accountBalance) {
this.accountBalance = accountBalance;
}
public double getAnnualInterestRate() {
return annualInterestRate;
}
public void setAnnualInterestRate(double annualInterestRate) {
this.annualInterestRate = annualInterestRate;
}
public void withdraw(double amountToWithdraw) {
if (amountToWithdraw > accountBalance) {
//putting together withdraw make sure to have a validation to stop ppl from going over.
System.out.println("Sorry you cannot exceed the amount you have in your balance.");
}
else {
accountBalance = accountBalance - amountToWithdraw;
}
}
public void deposit(double amountToDeposit) {
if (amountToDeposit < 0) {
//deposits cannot be negative
System.out.println("You cannot deposit a negative amount of dallars.");
}
else {
accountBalance = accountBalance + amountToDeposit;
}
}
public double getMonthlyInterestRate() {
int MonthsInAYear = 12;//method variable is small BUT just need to get results
double monthlyInterestRate = annualInterestRate / MonthsInAYear;
return monthlyInterestRate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String toString(){
String bankInfo = " Password: " + getPassword() + " Account ID: " + getAccountId();
return bankInfo;
}
}
public class CurrentAccount extends BankAccount{
private static float overdraftLimit = 100;
CurrentAccount(){
super();
}
public static float getOverdraftLimit() {
return overdraftLimit;
}
// MAKE A SETTER FOR THE OVERDRAFTLIMIT
public void withdraw(double amountToWithdraw){
if (amountToWithdraw <= getAccountBalance()+overdraftLimit) {
setAccountBalance(getAccountBalance() - amountToWithdraw);
}
else {
System.out.println("Error this transaction has been cancelled.");
}
}
}
public class SavingsAccount extends BankAccount{
private static double interest;
public SavingsAccount (){
super();
interest = 0;
}
public void addInterest(){
interest = getAccountBalance() * getMonthlyInterestRate(); //GETTING ZEROS FROM ACCOUNTBALANCE
//CHANGE getAccountBalance with some other initial payment.
super.deposit(interest);
}
public double getInterest() {
return interest;
}
public void setInterest(float interest) {
this.interest = interest;
}
}
public class Bank {
Scanner input = new Scanner(System.in);
Scanner Restart = new Scanner(System.in);
private static ArrayList<BankAccount> bankAccounts; // MADE THIS STATIC
public Bank() {
bankAccounts = new ArrayList<BankAccount>();
}
public void openAccount() {
Object[] possibilities = {"Regular Account", "Savings Account", "Checking Account"};
Object inputValue = JOptionPane.showInputDialog(null, "Please pick an option from this menu: ",
"input", JOptionPane.INFORMATION_MESSAGE, null, possibilities, possibilities [0]);
if (inputValue.equals("Regular Account")) {
// Make a regular acct
String inputName = JOptionPane.showInputDialog(null, "Please input your name");
BankAccount newBankAccount = new BankAccount();
newBankAccount.setName(inputName);
bankAccounts.add(newBankAccount);
JOptionPane.showMessageDialog(null, "Account ID: " + newBankAccount.getAccountId());
JOptionPane.showMessageDialog(null, "Account Password: " + newBankAccount.getPassword());
} else if (inputValue.equals("Savings Account")) {
// Make a savings acct
String inputNameSavings = JOptionPane.showInputDialog(null, "Please input your name");
BankAccount newBankAccount = new SavingsAccount();
newBankAccount.setName(inputNameSavings);
bankAccounts.add(newBankAccount);
JOptionPane.showMessageDialog(null, "Account ID: " + newBankAccount.getAccountId());
JOptionPane.showMessageDialog(null, "Account Password: " + newBankAccount.getPassword());
} else if (inputValue.equals("Checking Account")) {
// Make a checking acct
String inputNameChecking = JOptionPane.showInputDialog(null, "Please input your name");
BankAccount newBankAccount = new CurrentAccount();
newBankAccount.setName(inputNameChecking);
bankAccounts.add(newBankAccount);
JOptionPane.showMessageDialog(null, "Account ID: " + newBankAccount.getAccountId());
JOptionPane.showMessageDialog(null, "Account Password: " + newBankAccount.getPassword());
}
}
public static ArrayList<BankAccount> getBankAccounts() {
return bankAccounts;//Moving this into the Open.Account?
}
public void closeAccount() {
System.out.println("Hello give me the name of the" + " "
+ "account you would like to close.");
String userName = input.next();// Gets input for first choice.
// Ask for account id
System.out.println("Please input your account ID");
int userAccountId = input.nextInt();
for (int i = 0; i < bankAccounts.size(); i++) {
if (bankAccounts.get(i).getName().equals(userName)
&& bankAccounts.get(i).getAccountId() == userAccountId) {
bankAccounts.remove(i);
System.out.println("Account removed");
}
}
// anyway, you would set the name probably in the constructor function
// for that particular instantiation of the class
}
public void update() {
// UPDATES MY ACCOUNTS
for (int i = 0; i < bankAccounts.size(); i++) {
if (bankAccounts.get(i) instanceof SavingsAccount) {
((SavingsAccount) bankAccounts.get(i)).addInterest();
} else if (bankAccounts.get(i) instanceof CurrentAccount) {
if (bankAccounts.get(i).getAccountBalance() < 0) {
System.out.println("\nThe Account: " + bankAccounts.get(i).getName() + " has been OverDrafted.\n");
}
}
}
}// ends update
public void withdraw(){
System.out.println("Input your ID and then your password to withdraw money.");
int acctID = input.nextInt();
int withdrawAmount;
// do {
for (int i = 0; i < bankAccounts.size(); i++){
//input needed.
if (acctID == bankAccounts.get(i).getAccountId()){
System.out.println("We have found your account. Please input how much money you would like to withdraw.");
withdrawAmount = input.nextInt();
bankAccounts.get(i).withdraw(withdrawAmount);
break;
}
// } while (input != 1);
}
}
public void deposit(){
int acctID;
int depositingAmount;
//System.out.println("Input your ID and then your password to deposit money.");
String inputID = JOptionPane.showInputDialog("Please input your ID to begin depositing money.");
acctID = Integer.parseInt(inputID);
String inputPassword = JOptionPane.showInputDialog("Please input your password to verify your account.");
// int depositAmount;
// do {
for (int i = 0; i < bankAccounts.size(); i++)//Loops through accounts in my arraylist.
{
if (acctID == bankAccounts.get(i).getAccountId() && inputPassword.equals(bankAccounts.get(i).getPassword()))//If ID and password work are true then it goes in here.
{
String depositAmount = JOptionPane.showInputDialog("Please input how much money you want to "
+ "input");//An here is where you would be able to spit out how much money to deposit.
depositingAmount = Integer.parseInt(depositAmount);
bankAccounts.get(i).deposit(depositingAmount);
break;
}
}
}
}
An finally the class i'm running it on...
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class TestBankAccount {
public static void main(String[] args) {
// JOptionPane.showMessageDialog(null, "Hello User.");
Object[] menuPossibilities = {"Create a New Account", "Deposit", "Withdraw", "Display Balance", "Exit"};
Object menuValues = JOptionPane.showInputDialog(null, "Please pick an option from this menu: ",
"input", JOptionPane.INFORMATION_MESSAGE, null, menuPossibilities, menuPossibilities [0]);
while (!menuValues.equals("Exit")){
Bank newBank = new Bank();
// Bank newBank1 = new Bank();
// Bank newBank2 = new Bank(); Do the same thing as below but switch out
// bank1 and bank2 as a substitute.
ArrayList<BankAccount> bankList = newBank.getBankAccounts();
if (menuValues.equals("Create a New Account")){
newBank.openAccount();
}
else if (menuValues.equals("Deposit")){
newBank.deposit();
}
else if (menuValues.equals("Withdraw")){
newBank.withdraw();
}
else if (menuValues.equals("Display Balace")){
newBank.deposit();
}
else if (menuValues.equals("Exit")){
System.out.println("Thank you for using our service.");
}
menuValues = JOptionPane.showInputDialog(null, "Since you did not pick 5 please pick another option: ",
"input", JOptionPane.INFORMATION_MESSAGE, null, menuPossibilities, menuPossibilities [0]);
}
}
}
Use .equals method to check strings for equality.

7-11 Online store program. Modification required?

I am a very amateur student programmer who has made a code that sells a user items and then calculates the tax of that item by asking what state the user lives in. It is a very simple code given my lack of experience with programming. Unfortunately, I made the mistake of writing this code without thinking ahead.
This program is actually my final project for my class. Because of that, there are requirements that I have to meet which I am currently having difficulties with. I have completed almost all of the requirements, but have noticed that some are not yet completed. Some requirements I am missing are...:
1 specialized constructer (I have never understood how to do this efficiently, and am having doubts as to if this is still even possible, given my code)
1 accessor and 2 modifiers (Same thing as constructor, how do I do this correctly with my given code?)
Some sort of formated output using printf (Maybe can be used to round the total price? Too bad I don't fully understand it)
Here is my [extremely inefficient] code itself:
import java.util.Scanner;
public class Tax_Calculator {
public static void main(String[]args)
{
Scanner in = new Scanner(System.in);
//variables
double taxPrice = 0;
double totalPrice = 0;
int choice = 0;
double rawCost = 0;
System.out.println("Hello! Welcome to the new 7/11 online ordering device.");
System.out.println("We're low on supplies, so only pick one.");
System.out.println("");
//menu
String [][] menu = {
{"(1) Pizza - $4.99"," (6) Slurpee - $0.79"},
{"(2) Cigarettes - $7.99"," (7) Hotdog - $1.99"},
{"(3) Coffee - $2.99", " (8) Doritos - $2.99"},
{"(4) Mountain Dew - $1.49", " (9) Water - $1.29"},
{"(5) Ice cream - $2.49", " (10) Muffin - $0.99"},
};
//prints menu
for (int e = 0; e < 5; e++)
{
System.out.println(menu[e][0] + "\t"+ menu[e][1]);
System.out.print("");
}
System.out.println("");
System.out.println("Enter the number of the item you want: ");
//user chooses item off of menu
int userInputMenu = in.nextInt();
if (userInputMenu == 1)
{
choice = 1;
System.out.println("You chose the pizza for $4.99.");
rawCost = 4.99;
}
if (userInputMenu == 2)
{
choice = 2;
System.out.println("You chose the cigarettes for $7.99.");
rawCost = 7.99;
}
if (userInputMenu == 3)
{
choice = 3;
System.out.println("You chose the coffee for $2.99.");
rawCost = 2.99;
}
**Continues all the way to userInputMenu == 10**
System.out.println("Now to calculate the tax, please enter the state you are currently in: ");
String userInputState = in.next();
//what state is the user in?
if (userInputState.equals("Alaska") || userInputState.equals("Delaware") || userInputState.equals("Montana") || userInputState.equals("New Hampshire") || userInputState.equals("Oregon"))
{
taxPrice = 0.0;
System.out.println("Luckily, the sales tax in " + userInputState + " is 0, so your final price is " + rawCost);
}
if (userInputState.equals("Colorado"))
{
taxPrice = 0.029;
totalPrice = ((taxPrice * rawCost) + rawCost);
System.out.println("The sales tax in " + userInputState + " is only " + taxPrice);
System.out.println("That means that the total price of your item is "+ totalPrice);
}
**Also continues for all 50 states**
//thank you
System.out.println("");
System.out.println("Thank you for shopping at the new online 7/11.");
System.out.println("Thank you come again.");
}
Just asking for some thorough explinations on how I can meet my missing requirements.
Also, how can I have it so when the user is inputting a state, the program can read it as either "MARYLAND" or "maryland"?
Have you read anything on object oriented programming? This is a great situation to use it, since you have a superclass of 'items', subclasses of those items 'coffee' 'slurpee' etc. Also is the customer able to purchase more than one item at a time and then find the total with tax?
I attempted to code this. You could take it further based on inputs from others on SO or your needs. It could be good start up for you. Add try/catch to handle exceptions:
Class to hold Menu objects:
public class Menu {
private int id;
private String item;
private double Price;
public Menu(int id, String item, double price) {
super();
this.id = id;
this.item = item;
Price = price;
}
public int getId() {
return id;
}
public String getItem() {
return item;
}
public double getPrice() {
return Price;
}
#Override
public String toString() {
return "Menu [id=" + id + ", item=" + item + ", Price=$" + Price + "]";
}
public boolean validateMenu(int id) {
if (id == this.id) {
System.out.println("You chose the " + item + " for " + Price);
return true;
}
return false;
}
}
Class to hold State objects:
public class State {
private String message;
private String state;
private double taxPrice;
public State(String state, double taxPrice, String message) {
this.state = state;
this.taxPrice = taxPrice;
this.message = message;
}
public String getMessage() {
return message;
}
public String getState() {
return state;
}
public double getTaxPrice() {
return taxPrice;
}
#Override
public String toString() {
return "State [taxPrice=" + taxPrice + ", state=" + state
+ ", message=" + message + "]";
}
public boolean validateState(String state) {
if (state.equalsIgnoreCase(this.state)) {
System.out.println(this.message.replace("userInputState", this.state) + this.taxPrice);
return true;
}
return false;
}
}
Tax_Calculator
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Tax_Calculator {
public static void main(String[] args) throws Exception {
Scanner in = null;
Tax_Calculator tc;
Menu menu = null;
State state = null;
double taxPrice;
double totalPrice;
System.out
.println("Hello! Welcome to the new 7/11 online ordering device.");
System.out.println("We're low on supplies, so only pick one.");
System.out.println("");
tc = new Tax_Calculator();
boolean continueFlag = true;
while (continueFlag) {
tc.printMenu();
System.out.println("");
System.out.println("Enter the number of the item you want: ");
in = new Scanner(System.in);
int userInputMenu = in.nextInt();
for (Menu menu2 : tc.menuList)
if (menu2.validateMenu(userInputMenu)) {
menu = menu2;
break;
}
if (menu == null)
System.out.println("Please choose a valid number! \n");
else
continueFlag = false;
}
System.out.println("");
System.out
.println("Now to calculate the tax, please enter the state you are currently in: ");
in.nextLine();
String userInputState = in.nextLine();
for (State state2 : tc.stateList)
if (state2.validateState(userInputState)) {
state = state2;
break;
}
taxPrice = state.getTaxPrice();
totalPrice = (1 + taxPrice) * menu.getPrice();
System.out.print("That means that the total price of your item is ");
System.out.printf("%.2f", totalPrice);
System.out.println("");
System.out.println("Thank you for shopping at the new online 7/11.");
System.out.println("Thank you come again.");
in.close();
tc.destroy();
}
private List<Menu> menuList = null;
private List<State> stateList = null;
Tax_Calculator() {
initMenu();
initState();
}
private void destroy() {
menuList = null;
stateList = null;
}
private void initMenu() {
menuList = new ArrayList<Menu>();
menuList.add(new Menu(1, "Pizza", 4.99));
menuList.add(new Menu(2, "Cigarettes", 7.99));
menuList.add(new Menu(3, "Coffee", 2.99));
}
private void initState() {
stateList = new ArrayList<State>();
stateList.add(new State("North Dakota", 0.05,
"The sales tax in userInputState is "));
stateList.add(new State("Arizona", 0.05,
"The sales tax in userInputState is "));
stateList.add(new State("Maine", 0.05,
"The sales tax in userInputState is "));
}
private void printMenu() {
for (Menu menu : menuList)
System.out.println(menu);
}
}

StringTokenizer and Array Java

I am completed the whole program, and it is working fine. But, I am having trouble with the StringTokenizer. I have class named Worker.java and a test class named TestWorker.java...
In the test class I have calculated and printed out the total hoursworked, grossSalary and etc..
But I am stuck in 1 position, that is I have to store name,id, and hourly rate in array, and then using the StringTokenizer, I have to prompt the user to enter worker ID and hourly rate.
When the user enter the user worker name and ID, the program output will show the user the hourly rate of the worker...
or in other words...
Allow the user to enter worker-ID and Hours repeatedly until user enter and empty string. Read the values and invoke the methods addWeekly() on the appropriate object(by searching through the array to locate the object with the specified ID). If a nonexistent ID is entered display an appropriate error message.
Please see my codings below and modify as your needs....
//Worker.java
public class Worker {
public final double bonus=100;
protected String name;
protected String workerID;
protected double hourlyRate;
protected double hoursWorked;
protected double weekHour;
protected double tax;
protected double grossSalary;
protected double netSalary;
public Worker() {
}
public Worker(String name,String workerID,double hourlyRate){
this.name = name;
this.workerID = workerID;
this.hourlyRate = hourlyRate;
}
public void addWeekly(double weekHour){
hoursWorked = hoursWorked + weekHour;
}
public double gross()
{
grossSalary = (hoursWorked*hourlyRate);
if(hoursWorked>=150)
{
grossSalary = grossSalary +100;
}
return grossSalary;
}
public double taxAndNet()
{
tax = (grossSalary - 500) * 0.3;
netSalary = (grossSalary-tax);
return netSalary;
}
public String getName()
{
return name;
}
public String getWorkerID()
{
return workerID;
}
public double getHourly()
{
return hourlyRate;
}
public double getTotalHours()
{
return hoursWorked;
}
public double getGrossSalary()
{
return grossSalary;
}
public void addToGross(double amt)
{
grossSalary = grossSalary + amt;
}
public void displaySalary()
{
System.out.println("Name :" + name + "\nID :" + workerID +"\nHourly rate : "+ hourlyRate +"\nTotal Hours Worked " + hoursWorked +"\nGross Pay: "+getGrossSalary()+ "\nTax : "+tax +"\nNetpay :" +netSalary);
}
}
//TestWorker.java
import java.util.StringTokenizer;
import java.util.Scanner;
public class TestWorker {
public static void main(String args[]) {
Worker e = new Worker("John Major","s123",15.0);
e.addWeekly(45);
e.addWeekly(40);
e.addWeekly(32);
e.addWeekly(38);
e.gross();
e.taxAndNet();
e.displaySalary();
Worker[] worklist = new Worker[5];
worklist[0] = new Worker("Richard Cooper","s1235",20.0);
worklist[1] = new Worker("John Major","s1236",18.0);
worklist[2] = new Worker("Mary Thatcher","s1237",15.0);
worklist[3] = new Worker("David Benjamin","s1238",16.0);
worklist[4] = new Worker("Jack Soo","s1239",25.0);
Scanner input = new Scanner(System.in);
String name;
do{
System.out.print("Please enter your name and worker ID: ");
name = input.nextLine();
StringTokenizer string = new StringTokenizer(name,"+");
System.out.println("******|||||*******");
while(string.hasMoreElements()){
System.out.println(string.nextElement());
}
}
while(name.isEmpty()==false);
String s = "Five+Three=Nine-One";
String arr[];
//declare it with 3 tokens as seen above:
StringTokenizer st = new StringTokenizer(s, "+=-");
//the array size is the number of tokens in the String:
arr = new String[st.countTokens()];
//when there are still more tokens, place it in the array:
int i = 0;
while(st.hasMoreTokens()){
arr[i] = st.nextToken();
i++;
}
//determine the word with the largest length:
int indexMax = 0;
for( i = 1; i < arr.length; i++){
if(arr[i].length() > arr[indexMax].length())
indexMax = i;
}
System.out.println("The largest element is in index: "
+ indexMax);
} //main
} //class
Please tell us your java version. Since jdk 1.4.2 you should use String.split(...) instead of the old Stringtokenizer. Check out this tutorial TIP: A little tutorial about String.split();

Why is my data mixed up when I compile?

There are a few things I would like some help on. First and foremost, when I compile, my product number and price get mixed up. Why? Secondly, why does the product type always return null? I would also like to combine all the message boxes but every attempt I have made fails. If someone could lead me in the right direction, I would appreciate it. Here is my code:
MAIN
package inventory4;
import java.util.Scanner;
import java.util.Arrays; //Needed to include data for arrays
import javax.swing.JOptionPane; //JOptionPane import tool
public class RunApp
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
ItemDetails theItem = new ItemDetails();
int number;
String Name = "";
String Type = "";
String sNumber = JOptionPane.showInputDialog(null,"How many items are to be put into inventory count?: ");
number = Integer.parseInt(sNumber);
ItemDetails[] inv = new ItemDetails[number];
for (int count = 0; count < inv.length; ++count)
{
Name = JOptionPane.showInputDialog(null,"What is item " + (count + 1) + "'s name?");
theItem.setName(Name);
Type = JOptionPane.showInputDialog(null,"Enter " + Name + "'s product type");
String spNumber = JOptionPane.showInputDialog(null,"Enter " + Name + "'s product number");
double pNumber = Double.parseDouble(spNumber);
theItem.setpNumber(pNumber);
String sUnits = JOptionPane.showInputDialog(null,"How many " + Name + "s are there in inventory?");
double Units = Double.parseDouble(sUnits);
theItem.setUnits(Units);
String sPrice = JOptionPane.showInputDialog(null,Name + "'s cost");
double Price = Double.parseDouble(sPrice);
theItem.setPrice(Price);
inv[count] = new ItemDetails(Name, Price, Units, pNumber);
}
for (int i = 0; i < inv.length; ++i)
{
JOptionPane.showMessageDialog(null, "Product Name: " + inv[i].getName());
//Why can't I use this instead of having multiple boxes?:
//JOptionPane.showMessageDialog(null, "Product Name: \nProduct Type: \nProduct Number: \nUnits in Stock: \nPrice Per Unit: " + inv[i].getName() + inv[i].getUniqueType() + inv[i].getpNumber() + inv[i].getUnits(), + inv[i].getPrice());
JOptionPane.showMessageDialog(null, "Product Type: " + inv[i].getUniqueType());
JOptionPane.showMessageDialog(null, "Product Number: " + inv[i].getpNumber());
JOptionPane.showMessageDialog(null, "Amount of Units in Stock: " + inv[i].getUnits());
JOptionPane.showMessageDialog(null, "Price per Unit: " + inv[i].getPrice());
JOptionPane.showMessageDialog(null, String.format("Total cost for %s in stock: $%.2f", inv[i].getName(), inv[i].calculateTotalPrice()));
JOptionPane.showMessageDialog(null,String.format("Restocking fee for %s is $%.2f", inv[i].getName(), inv[i].calculateRestock()));
String combinedData = inv[i].toString();
if(i == (inv.length -1)){
String lastItem = String.format("\nTotal Cost for all items entered: $%.2f\n", Items.getCombinedCost(inv));
combinedData = combinedData + lastItem; //combine total value to the end of the last object output
JOptionPane.showMessageDialog(null, combinedData); //Show Message
}else{
JOptionPane.showMessageDialog(null, combinedData); //Show Message
}
} //end for
} //end main
} //end class
ITEMS
package inventory4;
public class Items implements Comparable
{
private String Name;
public double pNumber, Units, Price;
String allInfo;
public Items()
{
Name = "";
pNumber = 0.0;
Units = 0.0;
Price = 0.0;
}
public int compareTo(Object item)
{
Items tmp = (Items)item;
return this.getName().compareTo(tmp.getName());
} // end compareTo method
public Items(String productName, double productNumber, double unitsInStock, double unitPrice)
{
Name = productName;
pNumber = productNumber;
Units = unitsInStock;
Price = unitPrice;
}
public String toString()
{
StringBuffer allInfo = new StringBuffer();
allInfo.append(String.format("Name: %s\n pNumber: %.0f \n Units: %.0f \n Price: %.2f\n",
getName(),getpNumber(),getUnits(),getPrice()));
return allInfo.toString();
}
//setter methods
public void setName(String n)
{
Name = n;
}
public void setpNumber(double no)
{
pNumber = no;
}
public void setUnits(double u)
{
Units = u;
}
public void setPrice(double p)
{
Price = p;
}
//getter methods
public String getName()
{
return Name;
}
public double getpNumber()
{
return pNumber;
}
public double getUnits()
{
return Units;
}
public double getPrice()
{
return Price;
}
public double calculateTotalPrice()
{
return (Units * Price);
}
public static double getCombinedCost(Items[] item) //This is used to set up the method
{
double combined = 0; //Loops through array after array is complete
for (int i = 0; i < item.length; ++i)
{
combined = combined + item[i].calculateTotalPrice(); //Sets up to combine all TotalPrice
//calculations in array
} //end loop
return combined;
} //end method
} //end class
ITEM DETAILS
package inventory4;
public class ItemDetails extends Items
{
private String UniqueType;
public ItemDetails()
{
super();
}
public ItemDetails(String productName, double productNumber, double unitsInStock, double unitPrice)
{
super(productName,productNumber,unitsInStock,unitPrice);
}
public String enterUniqueType()
{
return UniqueType;
}
public String setUniqueType()
{
return UniqueType;
}
public String getUniqueType()
{
return UniqueType;
}
public double calculateRestock() //setting up to calculate the restocking fee at 5%
{
return (Price * .05);
}
}
// getter???
public String setUniqueType() {
return UniqueType;
}
should be:
//setter
public void setUniqueType(String type) {
UniqueType = type;
}
and
inv[count] = new ItemDetails(Name, Price, Units, pNumber);
should be:
inv[count] = new ItemDetails(Name, pNumber, Units,Price );//look at the order
inv[count].setUniqueType(Type);//you have not set it.
I would also like to combine all the message boxes…
As an example, see JOptionPaneTest.
First and foremost, when I compile, my product number and price get mixed up. Why?
You're creating a new ItemDetails object with the call to
new ItemDetails(Name, Price, Units, pNumber);
but your constructor for ItemDetails is
ItemDetails(String productName, double productNumber, double unitsInStock, double unitPrice)
i.e., it takes the product number first and price last, not the other way around
Secondly, why does the product type always return null?
You're never actually setting your type, both your set and get methods do the same thing! That the setter is returning a value should've been a warning!
public String setUniqueType()
{
return UniqueType;
}
public String getUniqueType()
{
return UniqueType;
}
This is what it should be
public void setUniqueType(String type)
{
this.UniqueType = type;
}

Categories

Resources