I'm to create a banking program. I should be able to deposit, withdrawl, view balance, and then of course exit.
My problem is we have not gone over arrays yet and that is what I'm trying to use. When I initialize the array with [0] as it's only one type of data at a time, i recieve an:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
So my question is how can I be able to do this while modififying the balance until the user exits. I'm a bit stuck...
Any help is appreciated and I apoligize in advance for the messy code.
Thankyou everyone for the help. I did put: double[] balance = new double[1];
But now I am returning to the problem that I can't continue modifying the array with more deposits, and withdrawls. I initializes it back to 0.0.
Could anyone point me in the right direction?
Main class:
public class Project3 {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Introduction();
Banking obj1 = new Banking();
}
public static void Introduction()
{
//this message tells the user exactly what this program does.
JOptionPane.showMessageDialog(null,
"This is a small conversion program which allows you to do "
+ "\nDeposit "
+ "\nWithdrawl."
+ "\nView Balance."
+ "\nExit",
"Conversion Calculator",
JOptionPane.INFORMATION_MESSAGE);
}
}
Class:
public class Banking
{
double deposit;
double newbalance;
double[] balance = new double[0];
public Banking()
{
Menu();
}
public void Menu()
{
JDialog.setDefaultLookAndFeelDecorated(true);
Object[] selectionValues = { "Deposit", "Withdrawl"};
String initialSelection = "Deposit";
Object selection = JOptionPane.showInputDialog(null, "Would you like to "
+ "do today?",
"Home Banking Selection Screen", JOptionPane.PLAIN_MESSAGE, null, selectionValues, initialSelection);
// If statements used to call the method selected
if (selection == "Deposit")
Deposit();
if (selection == "Withdrawl")
Withdrawl();
}
public void Deposit()
{
balance[0] = Double.parseDouble(JOptionPane.showInputDialog(null,
"Please enter the total number of degrees in Fahrenheit to be Converted into Celcius? and press 'Ok'",
"Deposit",
JOptionPane.PLAIN_MESSAGE));
JOptionPane.showMessageDialog(null,
"You doposited $ " +balance+ "\n You now have $" ,
"The End",
JOptionPane.PLAIN_MESSAGE);
JDialog.setDefaultLookAndFeelDecorated(true);
Object[] selectionValues = { "Continue with more transactions", "Exit"};
String initialSelection = "Deposit";
Object selection = JOptionPane.showInputDialog(null, "Would you like to "
+ "do today?",
"Home Banking Selection Screen", JOptionPane.PLAIN_MESSAGE, null, selectionValues, initialSelection);
// If statements used to call the method selected
if (selection == "Continue witl more transactions")
Menu();
if (selection == "Exit")
Exit();
}
public void Withdrawl()
{
JOptionPane.showMessageDialog(null,
" Will be Withdrawl!", //Message to tell the user the program has ended
"2",
JOptionPane.PLAIN_MESSAGE);
}
public void Exit()
{
JOptionPane.showMessageDialog(null,
" Thank you and have a great day!", //Message to tell the user the program has ended
"The End",
JOptionPane.PLAIN_MESSAGE);
}
}
double[] balance = new double[0]; Does not create an array of 0
's.
For example: Your array does not look like this:
[0,0,0,0,0,0,0,0,0]
Instead your array looks like this:
[ ]
Saying Object obj = new Object[x] creates an array that is of length x. However, even then the items in the array are not initialized. You have to go manually set each one to 0.
You have a double array of size 0:
double[] balance = new double[0];
And then you are accessing it's first (non-existing element):
balance[0] = Double.parseDouble(JOptionPane.showInputDialog(null,
"Please enter the total number of degrees in Fahrenheit to be Converted into Celcius? and press 'Ok'",
"Deposit",
JOptionPane.PLAIN_MESSAGE));
That's why the ArrayIndexOutOfBoundsException: 0 is thrown.
Just use double[] balance = new double[1];
Here is size of array you are going to create ^
Every element will be initialised with 0.0 by default.
UPD: actually, you might want to try adding some checking to ensure that the user you are touching actually exists and the balance is set properly.
You can just initialize your array this way:
double[] balance = {};
At this point the size of the array will be zero.
However, based of your question, I do not think you need and array.
Simply declare balance this way:
double balance = 0.00d;
When you deposit:
balance = balance + depositAmount;
when you withdraw:
balance = balance - withdrawlAmount;
Related
I'm fairly new to coding spigot but I am trying to make a banking script where the player would click the deposit button and be prompted to type in the amount of money they want to deposit. However, when this happens in game, it automatically determines the input as 0 and doesn't give the player enough time to type in their message. Here is the code:
private void deposit(Player p, String gang) {
deposited.add(p);
p.closeInventory();
p.sendMessage(ChatManager.Feedback("jahseh", "Please type how much money you want to deposit"));
int input = (int) MyListener.typed;
if (Main.getEconomy().getBalance(p) >= input){
Main.getEconomy().bankDeposit(gang, input);
p.sendMessage(ChatManager.Feedback("jahseh", "You have deposited " + input + " stonebucks into your gang's bank."));
}
if (Main.getEconomy().getBalance(p) < input){
p.sendMessage(ChatManager.Feedback("alert", "You are trying to deposit more money than you currently have!"));
}
}
public void input (AsyncPlayerChatEvent event){
Player p = event.getPlayer();
String typed = event.getMessage();
if(Bank.deposited.contains(p)) {
Bank.deposited.remove(p);
event.setCancelled(true);
}
}
}
You have to wait for the listener to be executed, and only once it has been executed, run the code below.
This question already has answers here:
How to get the user input in Java?
(29 answers)
Closed 6 years ago.
So I made a class that is supposed to calculate the number of beers needed to become intoxicated. My class receives User Input for the name of the beer, the alcohol content, and then the user's weight to make the calculation.
Here's my whole Beer class
public class Beer {
private String name;
private double alcoholContent;
//Default apple values (Constructors)
public Beer()
{
this.name = "";
this.alcoholContent = 0.0;
}
//Accessors
public String getName()
{
return this.name;
}
public double getAlcoholContent()
{
return this.alcoholContent;
}
//Mutators
public void setName (String aName)
{
this.name = aName;
}
public void setAlcoholContent (double aAlcoholContent)
{
if (aAlcoholContent < 0 || aAlcoholContent > 1)
{
System.out.println("That is an invalid alcohol content");
return;
}
this.alcoholContent = aAlcoholContent;
}
//Methods
public double Intoxicated (double aWeight)
{
double numberOfDrinks = (0.08 + 0.015) * aWeight / (12 * 7.5 * this.alcoholContent);
return numberOfDrinks;
}
This is specifically my intoxicatedmethod in the class (I think it's right):
public double Intoxicated (double aWeight)
{
double numberOfDrinks = (0.08 + 0.015) * aWeight / (12 * 7.5 * this.alcoholContent);
return numberOfDrinks;
}
This is what the output window is supposed to look like, receiving User Input for the weight and then performing the calculation to see how many beers it would take based on the user's input when previously defining two beers to be considered intoxicated:
What’s the weight of the person consuming said beverages?
185
It would take 3.166 "firstBeerName" beers to become intoxicated.
It would take 1.979 "secondBeerName" beers to become intoxicated.
The intoxicated formula was given to me, I don't know how to properly set up my class testing main method file which calls this class to reflect that output.
You need to write a testing class, that contains a main method. In the main method you can create several Beer-Objects.
By iterating over your Beers, you can get the wanted results.
Look here to get information about how to set up a main method.
Create an Array of Beer-Objects in that method with different alcohol content
Get the user input for the weight and then
Iterate over your Array, call intoxicated() and print the results
You are going to want to create a main method which does the following:
1) Prints the prompt for the beer values (name and % alcohol)
2) Takes in user input for those beer values
3) Prints the prompt for the user's weight
4) Takes in the user input for the weight
5) Calculates and prints the result
For printing prompts, you will most likely want to use System.out.println("Some prompt here!");
For taking input, you will most likely want to use a Scanner. You can search around on this website and others, as well as read the documentation, for how to take input with using that class.
Here is an example of a main method:
public static void main(String[] args) {
Beer blueMoon = new Beer("Blue Moon", 5.4);
Beer hoegaarden = new Beer("Hoegaarden", 4.9);
System.out.println("Enter your weight: ");
Scanner input = new Scanner();
Double weight = input.nextLine();
double value = beer1.Intoxicated(weight);
System.out.println("It would take " + value + " of " + blueMoon.getName() + " to become intoxicated.");
}
I would suggest renaming your Intoxicated method to intoxicated, as method names are generally camelCased in Java.
I am not going to give you the exact code because this seems like homework and I already graduated, but that should be enough to get you started. My advice would be to search around for any specific questions you come up with.
You can write a main method like this:
public static void main(String [ ] args)
{
Beer beer1 = new Beer().
beer1.setName("firstBeerName");
beer1.setAlcoholContent(3.166);
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("What’s the weight of the person consuming said beverages?");
double weight = reader.nextDouble();
double answer = beer1.Intoxicated(weight);
System.out.println("It would take "+answer+" "+beer1.getName()+" beers to become intoxicated.")
// similar for beer2
}
I would encourage you to throw IllegalArgumentException when checking condition in setter:
public void setAlcoholContent(double aAlcoholContent) {
if (aAlcoholContent < 0 || aAlcoholContent > 1) {
throw new IllegalArgumentException("Alcohol content can't be more than 1 or less than 0");
}
this.alcoholContent = aAlcoholContent;
}
And for your question you can test it like this:
public static void main(String[] args) {
List<Beer> beers = new ArrayList<>();
beers.add(new Beer("firstBeerName", 0.04));
beers.add(new Beer("secondBeerName", 0.06));
Scanner reader = new Scanner(System.in);
System.out.println("What’s the weight of the person consuming said beverages?");
double weight = reader.nextDouble();
DecimalFormat decimalFormat = new DecimalFormat("0.000");
for(Beer beer : beers){
System.out.println("It would take " + decimalFormat.format(beer.Intoxicated(weight)) + " " + beer.getName() +" beers to become intoxicated.");
}
}
Also you can use loop for creating new beers, just ask user for amount of beers that he can obtain result for, and then create for loop.
I am going to create a program that keeps track of the balance on a bank account. The program shall use a loop that continues until the user choses to exit by answering no to the question Do you want to continue?.
In the loop the user shall be asked to enter an amount (positive for deposit and negative for withdraw). The amount shall be added/subtracted from an account balance variable. All deposits/withdraws shall be saved as a history so that we can print it later. When the user choses to exit the loop the current account balance together with the account history (from the array/ArrayList) shall be printed.
Now, I want to use an array with ten slots for the history feature.
My question is how can I keep track of the all deposit, withdraw and current account balance (using an array with ten slots for the history feature) so that I can print it out while the user exits the program?
My code:
BankApp class:
package bankapp;
import java.util.Scanner;
public class BankApp {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
askingUser au = new askingUser();
System.out.println("WELCOME TO OUR BANK!\nYou have 100 SEK by default in your account.");
while (true) {
au.userInput();
System.out.println("Do you want to continue? Answer by Yes or No.");
String yesOrNo = input.next();
if (yesOrNo.equalsIgnoreCase("yes")) {
au.userInput();
} else if (yesOrNo.equalsIgnoreCase("no")) {
System.out.println("History: ");
//print out the transaction history
System.exit(0);
} else {
System.out.println("Invalid character input.");
}
}
}
}
askingUser class:
package bankapp;
import java.util.Scanner;
public class askingUser {
Scanner input = new Scanner(System.in);
double initialBal = 100;
public void userInput() {
System.out.println("Enter your amount: (+ve for deposit & -ve for withdraw)");
double inputAmount = input.nextDouble();
if (inputAmount >= 0) {
double newPosAm = initialBal + inputAmount;
System.out.println("Your current balance is: " + newPosAm + " SEK");
} else {
double newNegAm = initialBal + inputAmount;
System.out.println("Your current balace is: " + newNegAm + " SEK");
}
}
}
If you use an array, you have to keep track of the number of elements stored inside and resize the array when necessary. The easiest way would be to keep the history as strings in ArrayList. You would add one message to that list per transaction:
ArrayList<String> history = new ArrayList<String>();
void addToHistory(String transaction) {
history.add(transaction);
}
void printHistory() {
for(String s : history) {
System.out.println(s);
}
}
addToHistory("Withdrawal: 100 SEK" );
addToHistory("Deposit: 200 SEK" );
printHistory();
You need a queue to do that. However, for a simple, fast and primitive implementation you can:
Define an object called Transaction(deposit - double, withdraw - double, current account balance - double)
Add a List of Transactions into askingUser class as an attribute. I strongly recommend renaming the class name to AskingUser to make it seen as object.
At each operation add a new Transaction to end of the List you just added.
At exit, print out the last -say- 10 elements of the List; you can reach it through askingUser object. You can also define a function in askingUser class to print out the last 10 elements, if you make the function work according to selected number of elements, you can add number of Transactions to the function's inputs.
I'm attempting to resolve an issue with a
syntax error on token "}" , { expected.
The program should be able to calculate tax on the amount enter.
import javax.swing.JOptionPane;
public class Accounting {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//declare variables
int accountNumber;
int age=0;
int months=0;
double amount=0.0;
double increasedAmount=0.0;
double incomeTax=0.0;
double newAmount=0.0;
char letter;
double rate=0.03;
double interest=0.0;
double tax=0.40;
double income=0.0;
//get input
accountNumber=Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter the account number (Type 999 to exit "));
age=Integer.parseInt(JOptionPane.showInputDialog(null, "Enter the age "));
amount=Double.parseDouble(JOptionPane.showInputDialog(null, "Enter the amount "));
months=Integer.parseInt(JOptionPane.showInputDialog(null, "Enter the number of months "));
letter=(JOptionPane.showInputDialog(null, "--- --- Main Menu --- --- --- " +
"\n A. Seniors Account " + "\n B. Income Tax " + "\n C. Special Accounts " +
"\n Please select a letter from the menu ( Type X to exit the Menu)")).charAt(0);
//call function
interest=amount*rate*months;
income=amount*tax;
increasedAmount=calcSenior(amount, interest);
incomeTax=calcTax(amount, income );
//display results
JOptionPane.showMessageDialog(null, "The increased amount is " + increasedAmount);
JOptionPane.showMessageDialog(null, "The income tax is " + incomeTax);}
public static void displayHeading()
{
JOptionPane.showMessageDialog(null, "############################# ");
JOptionPane.showMessageDialog(null, "Als Accounting Services ");
JOptionPane.showMessageDialog(null, "Your success is our business. ");
JOptionPane.showMessageDialog(null, "############################# ");
}
// code methods
//case 1:
public static double calcSenior (double amt, double intest)
{
double cost;
cost=amt+intest;
return cost;
}
//case 2:
public static double calcTax(double amot, double inc)
{
double cost1;
cost1=amot+inc;
return cost1;
}
//case 3:
public static void makeDeductions (int age, double amount)
{
double newAmount;
if (age > 40)
{
newAmount=amount-100;
JOptionPane.showMessageDialog(null, "Amount " + amount);
}
else
{
JOptionPane.showMessageDialog(null, "No deductions at this time ");
}
}
} - error
while (accountNumber != 999)
{
Accounting.displayHeading();
switch (accountNumber)
{
case 1:
calcSenior();
break;
case 2:
calcTax();
break;
case 3:
makeDeductions();
break;
default: JOptionPane.showMessageDialog(null, "Bye! Have a nice day ");
}//end switch
}
}
}
The problem is, your while loop is out side the body of the class definition...
public class Accounting {
//...
} // End of class..
while...
This is illegal in Java. You must place the while loop within a executional context, such as a method or static initialiser block...
Your code's laid out unusually. You've got a piece of main towards the top and towards the bottom.
Here's the quick (compiling) fix:
Remove the curly brace at the end of JOptionPane.showMessageDialog(null, "The income tax is " + incomeTax);}.
Move the while loop to after that line.
Fix the method calls from within your while loop so that the parameters that they're using are correct.
Admittedly, this says nothing about the correctness of your program, but only to the point that it would be much, much closer to compiling.
At the end of the makeDeductions (int age, double amount) method you have this:
}
} - error
That first } closes the method body, and the following } closes the class body, so that leaves you with a - error outside class body, illegal syntax in Java. Also, there's a while after that, also illegal outside method body (and of course illegal outside class body)
If you delete both of those lines (numbers 100 and 101, copypasting your code) that problem is resolved (though that - error probably does something, even if I can't figure out what, so be careful when deleting it). But there's one more:
In what now would be part of the makeDeductions (int age, double amount) method body you now have references to variable accountNumber which is declared in the main(String[] args) method and thus doesn't exist in this context
You call for calcSenior() when that overload doesn't exist, the only one you have declared is calcSenior (double amt, double intest) (notice the two parameters)
Same for calcTax(), you have only declared calcTax(double amot, double inc)
And yet the same for makeDeductions (), with only makeDeductions (int age, double amount) having been declared. Careful here though, remember that I'm asuming you deleted those likes I specified at the beginning, so this code is INSIDE THE makeDeductions (int age, double amount) BODY, meaning that if you call makeDeductions with int and double parameters, you are in fact calling this very method, which can cause an infinite loop if you don't have a stopping condition to avoid the method to call itself infinitely (causing a stack overflow)
And that's all I could find. I hope this is useful to you :)
Maybe you are using Eclipse as IDE and trying to run code that doesn't compile. Check your Problems view in Eclipse, and fix the compilation errors before executing the application.
I'm having trouble with printing out the variable priceUsed
After the method getPriceAfterUse() get the value for me, the method OutputDetails should print all the information. But the variable priceUsed is printed 0.0. I don't know why.
Here is my code:
import java.util.Scanner;
class Car
{
public String brandName;
public String color;
public double priceNew, priceUsed;
public double odometer;
public double getPriceAfterUse()
{
priceUsed = priceNew*(1-(odometer/6000000));
return priceUsed;
}
public double updateMilage()
{
Scanner keyboard = new Scanner(System.in);
odometer = keyboard.nextDouble();
return odometer;
}
public void outputDetails()
{
System.out.println("The car brand name is : " + brandName);
System.out.println("The car new price: " + priceNew);
System.out.println("The car used price: " + priceUsed);
System.out.println("The car color: " + color);
System.out.println("The car Odemeter: " + odometer );
}
}
public class CarTest{
public static void main(String args[])
{
Scanner keyboard = new Scanner (System.in);
Car a = new Car();
System.out.println("Enter you car Brand Name: ");
a.brandName = keyboard.next();
System.out.println("Enter your car color: ");
a.color = keyboard.next();
System.out.println("Enter your new price: ");
a.priceNew = keyboard.nextDouble();
System.out.println("Enter your Odometer:");
a.updateMilage();
System.out.println();
a.outputDetails();
System.out.println();
}
}
public double getPriceAfterUse()
{
priceUsed = priceNew*(1-(odometer/6000000));
return priceUsed;
}
Only this method sets the value of priceUsed, and it isn't called until after outputDetails(), so that's the reason you're not getting the correct result.
However, there's a more important problem here: as a rule of thumb, methods called getSomething() shouldn't be doing anything other than return a value. They certainly must not have any side effects visible from the outside.
Even more generally, methods should have names which describe what they do as closely as possible. Misleading method names can cause you a lot of pain in the future.
Another thing you should look out for is to try to keep your objects in a consistent state. As you've noticed, priceUsed isn't automatically updated when mileage is, even though it is a function of mileage. It is also a function of priceNew, which can also be set separately, so unless you call every method in the correct order, you'll get an inconsistent state. The solution to this is to have a single operation that updates all of them at once:
public void updateValue( double priceNew, double odometer ) {
this.priceNew = priceNew;
this.odometer = odometer;
this.priceUsed = priceNew * (1.0d - ( odometer / 6000000.0d ) );
}
You are calling OutputDetails before you are setting the value of PricedUsed.
If you look at the output on the last line you have
System.out.println(a.getPriceAfterUse());
This works correctly because it it the first time it is called. Maybe you could add getPriceAfterUse() call to the OutputDetials method so that the used price is updated each time you display the values.
EDIT:
To solve this problem you could do this.
public void outputDetails() {
//Calculate the used price before outputting the value
getPriceAfterUse()
System.out.println("The car brand name is : " + brandName);
System.out.println("The car new price: " + priceNew);
System.out.println("The car used price: " + priceUsed);
System.out.println("The car color: " + color);
System.out.println("The car Odemeter: " + odometer );
}
or in your test script you could do this.
Scanner keyboard = new Scanner (System.in);
Car a = new Car();
System.out.println("Enter you car Brand Name: ");
a.brandName = keyboard.next();
System.out.println("Enter your car color: ");
a.color = keyboard.next();
System.out.println("Enter your new price: ");
a.priceNew = keyboard.nextDouble();
System.out.println("Enter your Odometer:");
a.updateMilage();
System.out.println();
//UPDATE THE USED PRICE
a.getPriceAfterUse();
a.outputDetails();
System.out.println();
EDIT #2:
Here is where I think your problem lies.
You have a class Cars, where you have the variables brandName, color, priceNew, priceUsed, and odometer.
I believe you are confusing the return statement of the method with setting the value of the variable.
When you call Car a = new Car(); you have created a new Car Object. Now assume that inside of this car element all of the variables (in this case brandName, color, priceUsed, etc) are empty.
You are setting their values by calling\:
a.brandName = "something"
a.color = "some color"
a.priceNew = "some value"
So now all of these values have been set... except for odometer and priceUsed
you set the odometer with
a.updateMilage();
and then you called:
a.outputDetails();
But where along this chain of commands have you changed or even set the value of priceUsed? you have not done this. So when you call outputDetails it will print out all of the values in your Car Object. and since you have not set the value of priceUsed it will print out 0.0
remember that the return in a function does not set the value it just sends a value back to whatever called it... that is how the value gets passed back to System.out.println for example
System.out.println(a.getPriceAfterUse()) will print out the calculated price after use and the value that is printed is that is returned by the public double getPriceAfterUse() method.
BUT the value of the variable priceUsed which is inside your object is SET when you run the line
priceUsed = priceNew*(1-(odometer/6000000));
Until that line us run the value of priceUsed in the Car object will print out 0.0
hmmm... TLDR :)