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.
Related
I've been trying to write a java program to calculate daily salary relying on hours worked per day. and if it was weekend or no. (boolean value).
The time the user need to write is 0824 it equals to 08:24 (no idea how to ask for hour:minutes pattern and subtract them).
I've been using only one loop to ask for payment Per Hour again and again if the user puts values lower than 28.00$ or higher than 100.00$.
When the program running after asking for paymentPerHour the program stops <terminated> is not shown.
Would appreciate any help. Thanks! :)
(don't pay attention to the class name)
package ouzanFirstProject;
import java.util.Scanner;
public class convertDecToBinary {
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
int paymentPerHour , entryHour = 0 , exitHour = 0;
float totalHour= (exitHour-entryHour)/100;
boolean workedAtWeekend;
float salary = 0;
System.out.println("Please enter the hour you arrived to work (HHMM)");
entryHour=in.nextInt();
System.out.println("Please enter the hour you exit from work(HHMM)");
exitHour=in.nextInt();
System.out.println("Please enter payment per hour (between 28.00 and 100.00):");
paymentPerHour=in.nextInt();
while(paymentPerHour>0) {
if(paymentPerHour<28 ||paymentPerHour>100) {
System.out.println("Please enter payment per hour");
paymentPerHour=in.nextInt();
}
if(paymentPerHour>=28 &&paymentPerHour<=100) {
continue;
}
}
System.out.println("Did you work on weekend ? (True/False)");
workedAtWeekend=in.hasNext();
if(workedAtWeekend){
salary= (float) ((totalHour)*0.20+100);
}
else if (totalHour>=9) {
salary=(float) ((float)(totalHour)*paymentPerHour*1.5);
if(totalHour>11) {
salary = (float)((float)(totalHour)*paymentPerHour*2);
}
}
else if(totalHour<9) {
salary=(float)((float)(totalHour)*paymentPerHour*0.1);
if(totalHour<=1) {
salary= 0;
}
if(totalHour>=15) {
System.out.println("You cant work more than 15 hours a day");
}
if(totalHour<0) {
salary=Math.abs(totalHour)*paymentPerHour;
}
}
System.out.println("You've been working for: "+totalHour+" Hours"+",And your payment is: "+salary);
}
}
You should not use continue; in the loop. It will force the loop to go to the next iteration even if the conditions are met. Instead you should use break; which will terminate the loop if the conditions are met. Also you should not add the condition paymentPerHour>0 because it will skip the loop if the user enters a negative number (thx to Idle_Mind for this one). See the code sample:
while(true)
{
if(paymentPerHour>=28 &&paymentPerHour<=100) {
break; // This will terminate the loop if the conditions are met
}
// This part will only run if the conditions are not met
System.out.println("Please enter payment per hour");
paymentPerHour=in.nextInt();
}
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;
I'm struggling with dealing of inventory scan for my game, it basically search for the user inventory if "Flying Broom" if present(it was collected in another method and upload the code is too long), if not it will run the method challengedragon() again; else, it will proceed to the next challenge if the item is present.I was think of inserting method as parameter but it is not possible. This is what I have now. :
public class Main {
String Flyingbroom = "Flying broom";
public static void main(String[] args) {
Player_inventory p = new Player_inventory();
challengedragon();
}
public void challengedragon() {
System.out.println("a Hungarian Horntail dragon! Let's start the battle! You have four options to beat the dragon: ");
System.out.println("1: Fly away with your broom");
System.out.println("2: Fight the dragon");
System.out.println("3: Just run to the egg and get it");
System.out.println("4: Hide behind a rock");
System.out.println("5: Go back to Hogwart");
System.out.println("Your choice is: ");
Scanner in = new Scanner(System.in);
int dragonfightchoice = in .nextInt();
if (dragonfightchoice == 1) {
{
p.Scanitem(Flyingbroom,
"Good choice! You managed to kill the Hungarian Horntail dragon and to get the golden egg",
"You dont have the broom. Try to search for the broom",
playerHP);
proceedtonextchallengelake();
} else if (dragonfightchoice == 2) {
System.out.println("The Hungarian Horntail dragon fired you. - 70HP. ");
playerHP -= 70;
challengedragon();
} else if (dragonfightchoice == 3) {
System.out.println("Bad idea... You lose 100 HP");
playerHP -= 100;
challengedragon();
} else if (dragonfightchoice == 4) {
System.out.println("The dragon found you. You lose 30 HP");
playerHP -= 30;
challengedragon();
} else if (dragonfightchoice == 5) {
Hogwart();
} else {
invalid();
challengedragon();
}
}
For my inventory class:
public void Scanitem(String item, String trueouputext, String textifconditionisnotmet) {
if (inv.contains(item) == true) {
System.out.println(trueouputext);
} else if (inv.contains(item) == false) {
System.out.println(textifconditionisnotmet);
}
public static ArrayList<String> inv = new ArrayList<String>();
Do you guys have any recommendation?
Are there additional steps to populate the inventory (variable inv)?
Also, wouldn't you want ScanItem to answer true or false, depending on whether the item was found? Then you would have something like this:
public boolean scanitem(String item) {
return ( inv.contains(item) );
}
if ( p.scanItem(flyingBroom) ) {
System.out.println("Good choice! You managed to kill the Hungarian Horntail dragon and to get the golden egg");
} else {
System.out.println("You dont have the broom. Try to search for the broom");
}
That will get you closer to what you want. However, there are two other issues which you'll need to put into your code:
You will need a loop of some sort, instead of calling challengeDragon from inside of itself.
Somehow, the return value from scanItem must be used to decide whether to loop.
Currently, you do a nested call of a method each time the player does something, this means that sooner or later you'll run out of the stack. A better idea for the framework for your text-based adventure is to have some kind of a description of the current game's state. The state could be represented as an object that contains the following information:
where's the player currently at (on which step, at which "crossing" etc.)
the player's stats (HP, available skills etc.)
the contents of the player's inventory
some previously made choices affecting the game
Then, the code could be written as a simple loop that does the following:
process player's input
change the state according to the player's input
present the player with available options according to the new state
wait for the next input
repeat
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 create an air traffic control system, where it generates a random amount of fuel and also a random amount of planes. I have these two elements done, however the issue is, in the output box it all shows and works perfectly. My issue is that I'm telling it, if there is no planes coming in to call the string no planes and if there is a plane then KLM. I can't get it to write to the main class with all the front end.
I've edited out some of the coding in the screen as I'm using Netbeans drag and drop front end:
enter public void StartSimulation()
{
Start pointer = new Start();
Plane incoming = new Plane();
//Needs a condition in here that checks if the plane and fuel has been
//Generated and also loop to keep up with the constant generated planes and fuel
jTextArea1.setText(incoming.planeName);
I have tried where the condition thing is the following:
if (incoming.nextPlaneLanding != 167) this generates the first thing over and over again in the output box. I've also tried setting a boolean in the plane class but again, it has had no effect even with the following condition around it. if (incoming.completed = true)
This is the stuff I have in my plane class:
class Plane
extends TimerTask
{
public int nextPlaneLoop = 0;
public int planes;
public int fuel;
public String planeName;
#Override
public void run()
{
if(nextPlaneLoop <=167)
{
//Currently only running 1 or 0 planes...
planes = (int) (Math.random()*((2-1)+1));
System.out.println("Random generated plane amount: "+planes);
System.out.println("Method called, one whole day loop");
//Adds to the plane in the airspace loop
nextPlaneLoop++;
System.out.println("Loop incrementing: "+nextPlaneLoop);
if(planes == 0)
{
System.out.println("No fuel is required as no planes are coming in");
planeName = "No incoming plane";
System.out.println("Planes name is: "+planeName);
System.out.println(" ");
}
else
{
//Amount of fuel
fuel = 30 + (int)(Math.random()*((120-30)+1));
System.out.println("Random fuel: "+fuel);
planeName = "KLM AirFrance";
System.out.println("Planes name is: "+planeName);
System.out.println(" ");
}
}
else
{
this.cancel();
System.out.println("Not in loop any more. End of day");
}
}
}
Can anyone suggest have to how to get the names to display on to the screen so I can then try and add them into a queue in the actual airport class.
I think the Observer pattern might work well for you. In Java, this is implemented via Observer and Observable.