How do I add strings together with different names - java

I've already created the ticketAgent and ticketType class and I'm having a tough time trying to add the strings. I've tried using a wrapper class but not sure if that's even the right approach. I've pasted my code and then the prompt respectively. Thanks for the help. I'm a first time poster, so I hope I've followed the posting guidelines.
Prompt:
Write a program called TicketBooth that instantiates at 3 different ticket agents. The TicketBooth program should prompt the user for the ticket agent they wish to purchase a ticket from and then display the list of ticket types and prices that are available. The TicketBooth program should allow the user to make a selection for the ticket to purchase. After a ticket type is selected, the TicketBooth program should display the:
• total sales for that ticket agent
• total number of tickets sold by the ticket agent
• total number of tickets sold by all ticket agents
The TicketBooth program should continue to prompt the user to purchase tickets from one of the ticket agents until the user types quit.
package Exercises;
import java.util.Scanner;
public class TicketBooth {
private static Scanner input;
public static void main(String[] args) {
input = new Scanner(System.in);
String ticketAgent = "sam", "nicole" , "alex";
String ticketType = "one";
int t = Integer.parseInt(ticketAgent);
int s = Integer.parseInt(ticketType);
int sum;
System.out.println("Please select your ticket agent: ");
ticketAgent = input.next();
System.out.println("Please select your ticket type or press -1 to quit: ");
ticketType = input.next();
sum = t +s;
System.out.println("The total tickets that were sold were: " + sum);
}
}
package exercises;
public class TicketAgent {
private static int numOfTicksPerAgent;
private String agentName;
private int numSold = 0;
private double totalSales = 0.0;
public TicketAgent(String agent) {
agentName = agent;
numSold = 0;
totalSales = 0.0;
numOfTicksPerAgent += 1;
}
public void sellTicket(TicketType tt) {
numSold++;
totalSales = totalSales + tt.getticketPrice();
numOfTicksPerAgent++;
}
public double gettotalSales() {
return totalSales;
}
public double getnumSold() {
return numSold;
}
public double getnumOfTicksPerAgent() {
return numOfTicksPerAgent;
}
}
package exercises;
public enum TicketType
{
CHILD (6.50),
ADULT (9.50),
SENIOR (6.50);
private double tikPrice;
TicketType(double price)
{
tikPrice = price;
}
public double getticketPrice()
{
return tikPrice;
}
}

The problem is, that it seems that this is your homework and
nobody wants to make your homeworks for you.
edit: I saw that you added your classes just now.
All you have to do is to add the do while loop
and instantiate your Agents in the right way.
Where, exactly, is your problem? So we can help you better.
My first approach would be, to make it simple,
to write a TicketAgent class and a TicketType class.
Write the TicketAgent in a way, you can put the name of
the agent and the types into the constructor.
TicketAgent agentSam = new TicketAgent("Sam", new ExpensiveTicket());
Add setter and getter methods.
And the TicketType needs a float value for the price and maybe a String description
or something like that.
After you are done with this, go back to your main class.
Open a do while loop and set as the loop argument a boolean
value for the user abort, which is false at the beginning and
changes if the user types in the quit command.
Before the loop, instantiate the Agents with the tickets.
Display names and prices. Display tickets. Count together. Ask for abort.
Hope this helps a little.
And sorry for my english, it is not my mother-tongue.
additional:
private boolean userWantsToQuit = false;
private List<TicketAgent> avaibleAgents = new ArrayList<TicketAgent>();
private List<TicketAgent> usedAgents= new ArrayList<TicketAgent>();
private List<TickeType> boughtTickets= new ArrayList<TicketType>();
main(...){
agents.add(new TicketAgent("Sam"));
agents.add(new TicketAgent("wise"));
agents.add(new TicketAgent("gamgee"));
do{
usedAgents.add(askUserForAgent()); //extra static method
boughtTickets.add(askUserForType(agent)); //extra static method
userWantsToQuit = askUserToQuit();//extra static method
}while(!userWantsToQuit);
displayAgentSummary(usedAgents);
displayTicketSummary(boughtTickets);
}
[...]
public static displayAgentSummary(List<TicketAgent> agents)
{
for(TicketAgent agent : agents)
{
System.out.println("Served by: " + agent.getName());
}
}
public static displayTicketSummary(List<TicketType> tickets)
{
float totalPrice = 0;
for(TicketType ticket : tickets)
{
totalPrice =+ ticket.getPrice();
System.out.println("You bought a " + ticket.getName() + " for " + ticket.getPrice()";
}
System.out.println("You bought tickets in total for " + totalPrice + " dollar".
}

Related

How to transfer funds from one account to another in java, using user input for each desired account, and amount to transfer

I am trying to create and execute a method which allows the user to choose an account from which and an account to which the user wants to transfer an amount, which the user also chooses. But, I don't know how to get user input asking from and to which class they want to transfer funds to.
I've tried using the Scanner method but I can't get it to work.
Here is the code, it's the same as the code beneath this but this is easier to view imo: https://gist.github.com/KamronKelley/32d9a40c285e501f64cf73fa28bf87b5
package banking;
public class Account {
String name;
double balance;
public Account() {
name = "";
balance = 0.0;
}
public void setName(String newName) {
name = newName;
}
public String getName() {
return name;
}
public double getBalance() {
return balance;
}
public void addFunds(double addedAmount) {
balance = balance + addedAmount;
}
public void withdraw(double withdrawnAmount) {
balance = balance - withdrawnAmount;
}
public void transfer(double amount, Account from, Account to) { //here is the transfer method, if i can improve this or alter it in order to make it easier to run using user input from the main file, let me know
if(from.balance >= amount){
from.balance = from.balance - amount;
to.balance = to.balance + amount;
System.out.println("Funds successfully transfered.");
} else {
System.out.println("Insufficient funds");
}
}
}
package banking;
import java.util.Scanner;
public class BankSimulator {
public static void main(String[] args) {
System.out.println("Hello and welcome to the banking system. Please enter a name to create an account, no spaces: ");
Scanner scan = new Scanner(System.in);
Account a1 = new Account();
a1.setName(scan.next());
System.out.println("Account name: " + a1.getName());
int count = 0;
while(count == 0) {
System.out.println("What would you like to do next?" + "\n" +
"Change account name: press 1" + "\n" +
"See account name: press 2" + "\n" +
"Check balance: press 3" + "\n" +
"Add money to balance: press 4" + "\n" +
"Withdraw money from balance: press 5" + "\n" +
"Exit program: press 7: " + "\n" +
"To transfer funds between accounts: press 6");
int toDo = scan.nextInt();
if(toDo == 1) {
System.out.println("Enter new account name: ");
a1.setName(scan.next());
System.out.println("Account name: " + a1.getName());
}
else if(toDo == 2) {
System.out.println("Account name: " + a1.getName());
}
else if(toDo == 3) {
System.out.println("Current balance: $" + a1.getBalance());
}
else if(toDo == 4) {
System.out.println("Desired amount to add: $");
a1.addFunds(scan.nextDouble());
System.out.println("Money successfully added to balance.");
}
else if(toDo == 5) {
System.out.println("Desired amount to withdraw: $");
a1.withdraw(scan.nextDouble());
System.out.println("Money successfully withdrawn from balance.");
}
else if(toDo == 6) {
System.out.println("Enter the account you would like to transfer money from:");
String fromAccount = scan.next();
System.out.println("Enter the account you would like to transfer money to:");
String toAccount = scan.next();
System.out.println("Enter the amount of money you would like to transfer: $");
double moneyToTransfer = scan.nextDouble();
//this is what i need help with, I don't know what to do with these three things, and since the first two arent accounts, i cant run the transfer method on them
}
else if(toDo == 7) {
System.out.println("Thank you for using our banking system. Until next time.");
count = 1;
}
}
}
}
I can't do anything with the user input because I need the desired accounts in order to run the transfer method with them.
You need to keep track of all the accounts in a List or maybe a Map. Then you using the user input you search and retrieve the desired accounts. Also I don't think you need the transfer method in the Account object you can just use withdraw and addFunds from the main, or maybe have it like a static method. Also I think you will need a few additional operations, like create new account and maybe a login that will just change the active account. Currently you only have 1 account which is a1 so it makes no sense to transfer anything.
I think I understand what you are saying, I already checked your code but I think there's a bit of redundant code in there, like your "Account from". If you are the owner of an account and you are transferring to another do you need to specify your account number? You understand?
Secondly, it's best your multiple ifs and else-ifs to switch case statements.
class bankAccount {
String name;
private double balance;
private final long acctNum = ThreadLocalRandom.current().nextLong(100000000, 999999999);
public bankAccount(String name, double balance) {
this.name = name;
this.balance = balance;
System.out.println("HELLO " + name + ", Your account number is: " + acctNum);
}
public void setName(String name) {
this.name = name;
}
public void addFunds(int amount) {
this.balance += amount;
}
public void withdrawFunds(int amount) {
this.balance -= amount;
}
public double getBalance() {
return balance;
}
public long getAcctNum() {
return acctNum;
}
public void transfer(bankAccount name, double amount) {
if(this.balance >= amount) {
name.balance += amount;
this.balance -= amount;
System.out.println("Transaction Successful");
}
else {
System.err.println("Insufficient Funds!");
}
}
}
class BankSimulator {
static bankAccount John = new bankAccount("John", 50000);
static bankAccount James = new bankAccount("James", 3000);
public static void main(String[] args) {
John.transfer(James, 300);
System.out.println("John's new balance is "+ John.getBalance());
System.out.println("James' new balance is "+ James.getBalance());
}
}
since you'll be making use of another account, you should create two instances of the Account class, this would clarify the ambiguity between which accounts to transfer to.
Essentially all I did was create the Account class, created an instance named John(John's Account) and create an instance named James (James' Account), so now, There you go with two account classes, with different fields but similar methods (getBalance(), transfer(), getAcctNum(), addFunds(), withdrawFunds()).
I Hope this is what you need, Happy Coding!
I suggest you create dummy data (existing) Account first:
List<Account> accountList = new ArrayList<>();
Account acct1 = new Account("tester1", 100.0);
Account acct2 = new Account("tester2", 100.0);
accountList.add(acct1);
accountList.add(acct2);
Add constructor for Account for easier adding of Accounts:
public Account(String name, double balance) {
this.name = name;
this.balance = balance;
}
Store new account account in list:
accountList.add(a1);
For your procedure for "(toDo == 6)" which is for transfer:
Check first if accountList has at least 2 accounts because it won't make sense if there's only 1 account.
else if (toDo == 6) {
if (accountList.size() > 2) {
System.out.println("Enter the account you would like to transfer money from:");
String fromAccount = scan.next();
System.out.println("Enter the account you would like to transfer money to:");
String toAccount = scan.next();
System.out.println("Enter the amount of money you would like to transfer: $");
double moneyToTransfer = scan.nextDouble();
for (Account account : accountList) {
if (account.getName().equals(fromAccount)) {
account.withdraw(moneyToTransfer);
}
if (account.getName().equals(toAccount)) {
account.addFunds(moneyToTransfer);
}
}
} else
System.out.println("Cannot transfer.");
}
Also consider if the account actually exists, so add additional checking. Hope this helps!
I know this conversation was from awhile ago, however, must mention to definitely Not use a static method as anthony suggested in this type of situation because a static method can only access static variables and methods.

Main class java does not return the value i passed in using scanner [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have this main class
public class Hotel
{
Scanner scan = new Scanner(System.in);
Register[] items = new Register[15];
int count = 0;
public static void main(String[] args)
{
DecimalFormat fmt = new DecimalFormat("0.##");
Hotel run = new Hotel();
int quantity, sale,night;
Register deluxe = new Deluxe();
Register family = new Family();
Register suite = new Suite();
Scanner input = new Scanner(System.in);
System.out.println("Enter customer's name:");
String name = input.next();
run.enterItems();
if(run.count != 0)
{
System.out.println("\nHotel Reservation Payment");
System.out.println("============================");
System.out.println("Customer name: " + name);
deluxe.displayInfo(); //supposed to print the details
family.displayInfo(); //supposed to print the details
suite.displayInfo(); //supposed to print the details
System.out.println("The final total is RM" + fmt.format(run.calcTotal()));
}
else
{
System.out.println("No items entered.");
run.enterItems();
}
}
public double calcTotal()
{
double total = 0;
for(int i = 0;i<count;i++)
{
total += items[i].total();
}
return total;
}
that is supposed to return the value i put in in the scanner here in the enterItems() that is in the class as the main class
public void enterItems()
{
int type, quantity, sale,night;
double price;
............................
System.out.println("\nNow please enter how many of Deluxe Room you want to book.");
quantity = scan.nextInt();
System.out.println("\nHow many night?");
night = scan.nextInt();
items[count] = new Deluxe(quantity,sale,night);
count++;
}
So this will pass to the class called Deluxe where i have this method called displayInfo()
public class Deluxe implements Register
{
int quantity,night;
double sale;
public Deluxe(){}
....................................
public double total()
{
double total, price = 200.0;
price = price*quantity*night;
total = price - (price * (sale/100));
total += total *.06;
return total;
}
public void displayInfo(){
if (quantity > 0){
System.out.println("Room Type : Deluxe Room");
System.out.println("Quantity: " +quantity);
System.out.println("Discount: " +sale);
}
}
}
the problem is, in checking for quantity > 0, it actually does not get any value that i put in in the scanner. It will always return 0 for quantity regardless what amount i put in.
But the calculation works fine. Calculation is to calculate how many (quantity) rooms book x night stay x the room's price.
The calculation is also in the same class as the displayInfo() which is in class Deluxe.
So i was wondering what did i do wrong here.
The quantity which you input here:
System.out.println("\nNow please enter how many of Deluxe Room you want to book.");
quantity = scan.nextInt();
Goes into main(String[] args).quantity that's defined here:
public class Hotel
{
....
public static void main(String[] args)
{
...
int quantity, sale,night;
...
}
The quantity that you check here:
if (quantity > 0){...}
Is a different parameter - it's Deluxe.quantity and is defined here:
public class Deluxe implements Register
{
int quantity,night;
...
}
Those two parameters have no relation. If you want them both to be the same, you need to pass to class Deluxe the main(String[] args).quantity parameter. You can do this via your own constructor under Hotel.main(String[] args), like so:
DecimalFormat fmt = new DecimalFormat("0.##");
Hotel run = new Hotel();
int quantity, sale,night;
Register family = new Family();
Register suite = new Suite();
Scanner input = new Scanner(System.in);
System.out.println("Enter customer's name:");
String name = input.next();
quantity = run.enterItems();
Register deluxe = new Deluxe(quantity,0,0); // entering the default value for the other two parameters like the empty constructor would leave them.
if(run.count != 0)
{
System.out.println("\nHotel Reservation Payment");
System.out.println("============================");
System.out.println("Customer name: " + name);
deluxe.displayInfo(); //supposed to print the details
family.displayInfo(); //supposed to print the details
suite.displayInfo(); //supposed to print the details
System.out.println("The final total is RM" + fmt.format(run.calcTotal()));
}
else
{
System.out.println("No items entered.");
run.enterItems();
}
if you change your enterItems() function to return the quantity parameter you need, like so:
public int enterItems()
{
int type, quantity, sale,night;
double price;
.........
System.out.println("\nNow please enter how many of Deluxe Room you want to book.");
quantity = scan.nextInt();
System.out.println("\nHow many night?");
night = scan.nextInt();
items[count] = new Deluxe(quantity,sale,night);
count++;
return quantity;
}
Notice, this solves this only for the quantity parameter. if you need more, you might need to return the Deluxe structure from enterItems(). Good luck!

Simplest Dialog/Message Box for beginners?

I am unsure of how to do this. I am in a intro to java class and it asks us to use a message box (instead of just system.out.println) I remember we imported something and it was an easy change, but I am unable to find any notes on it.
Furthermore all examples I've found across the web and this site are taking it beyond the scope of this class.
I apologize in advance if this is an incorrect format, this is my first time posting here.
TLDR: Trying to change
System.out.print("Enter renter name: ");
renterName = input.next();
to appear in a message box instead of in the Eclipse Console
I know we imported something (same way we import Scanner) to make this work, but every example I find is essentially saying create your own dialog box methods which is beyond my scope of knowledge, and this class.
COMPLETE CODE IS FOLLOWS:
import java.util.Scanner;
public class RentYourVideo {
public static void main(String[] args) {
int numberOfRentals, finalBill;
VideoRental rental = new VideoRental(); //runs constructor
Scanner input = new Scanner(System.in);
String renterName;
System.out.print("Enter renter name: ");
renterName = input.next();
System.out.print("Enter number of videos to rent: ");
numberOfRentals = input.nextInt();
rental.setRentalFee(); //needs to set rental fee to $5 according to assignment
rental.calculateBill(numberOfRentals); //from prev input
finalBill = rental.getFinalBill();
System.out.println(renterName + " your total bill for " +numberOfRentals+ " videos is $" +finalBill);
input.close();
}
}
//CHANGE ALL PROMPTS & OUTPUT TO DIALOG/MESSAGE BOX!!!!
public class VideoRental {
private int rentalFee, finalBill, numberOfRentals;
public VideoRental() { //constructor method
rentalFee = 0;
finalBill = 0;
}
public void setRentalFee() { //set method
rentalFee = 5;
} //the assignment claims this must set rentalFee = 5
public void calculateBill(int inRented) {
numberOfRentals = inRented;
finalBill = rentalFee * numberOfRentals;
}
public int getFinalBill() {
return finalBill;
}
}
Check this out:
String name = JOptionPane.showInputDialog(null, "Enter name here:");
http://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html
import javax.swing.JOptionPane;
[...]
public static void main(String[] args) {
int numberOfRentals, finalBill;
VideoRental rental = new VideoRental(); //runs constructor
String renterName;
renterName = JOptionPane.showInputDialog(null, "Enter renter name: ");
numberOfRentals = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number of videos to rent: "));
rental.setRentalFee(); //needs to set rental fee to $5 according to assignment
rental.calculateBill(numberOfRentals); //from prev input
finalBill = rental.getFinalBill();
JOptionPane.showMessageDialog(null, renterName + " your total bill for " +numberOfRentals+ " videos is $" +finalBill);
}

looping, get/set methods, and multiple classes, oh my

I am really struggling with get/set methods. I understand the basic concept - first you set the value then you retrieve it. I am finding it rather difficult to find information about it with the minimal concepts I have already learned. I am on the 6th chapter or my first Java and programming class and it is all online. I created a couple other classes that used set/get methods, but those don't really seem to fit this project.
public class Purchase{
int inv;
double sale;
double tax;
double taxAmount = 0.05;
public int getInv()
{
return inv;
}
public void setInv(int inv)
{
inv = inv;
}
public void setSale(double s)
{
sale = s;
tax = sale * taxAmount;
}
public double getSale()
{
return sale;
}
//display
public void display()
{
System.out.println("Invoice number: " + getInv() + "\nSale amount: $" + getSale() + "\nTax: $" + tax + "\nTotal: $" + (tax + sale));
}
}
import java.util.Scanner;
public class CreatePurchase{
public static void main(String[] args)
{
Purchase one = new Purchase();
Scanner input = new Scanner(System.in);
do
{
System.out.print("Please enter you invoice number. This will be a number between 1000 and 8000. ");
inv = input.nextInt();
one.setInv(inv);
}
while(inv < 1000 && inv > 8000);
{
System.out.println("Please enter the amount of your sale. ");
sale = input.nextInt();
}
}
}
The CreatePurchase class is not finished, but I compile it and get the below for every variable every time it appears:
CreatePurchase.java:16: error: cannot find symbol
inv = input.nextInt();
^
It was my understanding that a default constructor is made, so I didn't add one, but called it in CreatePurchase.
Any suggestions?
You've failed to declare the variable inv any where, for example...
public static void main(String[] args) {
Purchase one = new Purchase();
// !! Variable must be declared before it can be used !! //
int inv = 0;
Scanner input = new Scanner(System.in);
do {
System.out.print("Please enter you invoice number. This will be a number between 1000 and 8000. ");
inv = input.nextInt();
one.setInv(inv);
} while (inv < 1000 && inv > 8000);
{
System.out.println("Please enter the amount of your sale. ");
// This will be your next problem...
sale = input.nextInt();
}
}
Your Purchase class is also going to have problems...
The following method is essentially assigning the value of inv back to itself, which is meaningless in this context...
public void setInv(int inv)
{
inv = inv;
}
Instead, you should be assigning to the instance of the Purchase class's inv variable...
public void setInv(int inv)
{
this.inv = inv;
}
You have at least two problems. First, you can create a new variable with the same name as another variable that's in a bigger container (scope). In this case, the new variable "hides" or "shadows" the outer one. In your setInv method, when you say inv = inv, both invs refer to the innermost variable, the one in the method signature. To save the argument to the class's field, you need to specify the outer inv: this.inv = inv;.
In your CreatePurchase class, you don't have any inv defined; there's one in Purchase, but that's over there, not here. You just need to declare int inv; right after your Purchase one.
Based on these two errors, I would recommend reading an article or tutorial about variable scope in Java to learn the rules about which variables are accessible where.
You havent declared the variable inv in main method, at this step
inv = input.nextInt();
Change your program to below
int inv = 0;
Scanner input = new Scanner(System.in);
do
{
System.out.print("Please enter you invoice number. This will be a number between 1000 and 8000. ");
inv = input.nextInt();
if(inv >1000 & inv <8000)
one.setInv(inv);//add to one variable only if its correct,otherwise ignore it
}
while(inv < 1000 && inv > 8000);

Parameter usage on the fly when declaring object

I am asking the user to input the name and his money value like this.
I tried to do this on the fly like this:
for (int i = 0; i < numOfPlayers; i++) {
players.add(new Player(JOptionPane.showInputDialog("Please enter your name: "), getIntInput(players.get(i).name + " enter your amount of money: ")));
}
getIntInput is a custom method to get int input.
It should work like this:
Please enter your name:
Alex
Alex enter your amount of money:
Whatever int...
Can I do this on the fly, or should I traditionally use another for loop to ask for the money?
Coding like you are, is asking for troubles and difficulties.
Try to follow these steps:
Ask name
Put name in variable
Ask amount of money
Put money in variable
Create Person with name and variable
Instead of trying to do everything in 1 line.
If you look at Wesley's answer, IMO it's the more "obvious" and simple way to achieve your goal.
However, I may suggest you the Builder pattern here.
for (int i = 0; i < numOfPlayers; i++) {
players.add( PlayerBuilder.init().askName().askMoney().create() );
}
public final class PlayerBuilder {
private String name = "-No name-";
private int money = 0;
private PlayerBuilder() {
}
public static PlayerBuilder init() {
return new PlayerBuilder();
}
public PlayerBuilder askName() {
this.name = JOptionPane.showInputDialog("Please enter your name: ");
return this;
}
public PlayerBuilder askMoney() {
this.money = getIntInput(this.name + " enter your amount of money: ");
return this;
}
public Player create() {
return new Player(name, money);
}
private int getIntInput(String msg) {
// ...
}
}
If you want to save some time writing the PlayerBuilder class, you can transfer the dirty job to Lombok. It will to do it on the fly for you...

Categories