Consider the following code. For some reason, even after hitting the NO button, it's exiting the do while loop. I recently introduced the recentPurchaseAmount variable and it stopped working after that. Even removing that is not making it work now.
Variables like purchaseAmount , recentPurchaseAmount are double type initialized to 0.0. itemNo, itemCheck are integer type variables.
do {
purchaseAmount = Double.parseDouble(JOptionPane.showInputDialog(
"Enter the Item Purchase Amount"));
recentPurchaseAmount = recentPurchaseAmount + purchaseAmount;
if (onepty.budgetAmountVerify(recentPurchaseAmount)) {
itemNo++;
itemCheck = JOptionPane.showConfirmDialog(null,
"Finished Purchasing Items Purchase Amount?",
"Say Yes or No", JOptionPane.YES_NO_OPTION);
remainingBal = onepty.remainingBalance(recentPurchaseAmount);
}
} while(itemCheck == JOptionPane.YES_OPTION);
JOptionPane.showMessageDialog(null,
"Total items purchased are " + itemNo +
"\n and the remaining balance is : " +remainingBal+"" ,
"This is the Title",JOptionPane.INFORMATION_MESSAGE);
while(itemCheck == JOptionPane.NO_OPTION);will be a more suitable condition.
Related
I am a first-year computer science student. Coding in java is pretty new to me but I have achieved solutions to some of my problems. I have a question I'm struggling with, it asks me to use JOptionPane as a selection method. I know how to use the default selection dialog box but my question requires me to use JOptionPane to show choices(eg 1, withdraw 2, deposit 3, print details), and then it requires me to press 1, 2 or 3 to run that instruction. I have failed to find a way to input choice please may I be assisted :)`
public String setTown(){
weightSelection w1 = new weightSelection();
String [] towns = {"Durban","Pretoria","Cape Town"};
String input = (String) JOptionPane.showInputDialog(null, "Please select townoption",
"The Choice of a Lifetime", JOptionPane.QUESTION_MESSAGE, null, // Use
// default
// icon
towns, // Array of choices
towns[1]); // Initial choice
choice = input;
System.out.println(choice);
w1.setWeight();`
If you write
String [] towns = {"1. Durban","2. Pretoria","3. Cape Town"};
and the dialog opens the User might only need to press 1 or 2 or 3 on the keyboard.
Because the optionpane has the focus it recieves the keyhits and have a natural behaivor in selecting matching options to that keyhit.
Unfortunately the user have to hit "return" or click "ok" to confirm the selection and close the dialog.
Here is another example you could try
String dialogmessage = "Please choose a dessert";
String[] desserts = {"Cheesecake","Ice Cream","Mousse","Carrot cake"}
String dessert = (String)JOptionPane.showInputDialog(dialogcombo.this, dialogmessage, dialogtitle, JOptionPane.QUESTION_MESSAGE, null, dessert, dessert[0]);
if(dessert == null){
showStatus("You clicked cancel");}
else{showStatis("Your Choice was: " + dessert);}
Hope this helps
Code is running smoothly and has no errors, though my output for t1.choice is null
he is the code
System.out.println("");
System.out.println("Your Recipt" + "\n"+ "**********************" + "\n" + "Town: "+ " " + t1.choice );
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;
So I am very new to this and I am trying to get the variables to add up during the process of the code in order to print the total at the end, in doing so, I need it to read the selection from the JOptionPane that the user entered and add the value to the total at the end. The code is almost complete but is missing the calculation of the variables.
Q: How do I get the value of any variable based on what the user selects from the JOptionPane and add it to the cumulative total to println at the end?
An ex is as follows:
(Sorry if it isn't formatted correctly, I am working on learning how it should look)
int addons = 0;
do{
addons = JOptionPane.showConfirmDialog(null, "Would the customer like to add Salad, Smoothie, Sundae or Cone?");
if (addons == JOptionPane.NO_OPTION);
else if (addons == JOptionPane.YES_OPTION){
String[] choices2 = { "Salad $"+salad, "Smoothie$"+smoothie, "Sundae $"+sundae, "Cone $"+cone};
String extras = (String) JOptionPane.showInputDialog(null, "Which addon?",
"Extras", JOptionPane.QUESTION_MESSAGE, null, // Use
choices2, // Array of choices
choices2[0]); // Initial choice
count++;//Add item to count
System.out.println(extras);
} //close YES_OPTION parameters
} //close do parameters
while(addons == JOptionPane.YES_OPTION); // Exit do while loop6
I'm trying to make a simple text based adventure as an exercise on beginner java, but I've ran into a problem, and after a long time of searching I decided to just ask it.
I want to know how to refire this loop after IF statement has been answered, eg. user inputs: "Help", help tab shows up and user can enter another command.
I'm clueless as to why this doesn't work, so any help would be much appreciated.
boolean loopone = false;
do {
System.out.println(name + " is standing in a forest, covered in slime goo.");
String cmdone = in.next();
if (cmdone.equals("Help")) {
System.out.println("---------Help---------");
System.out.println("Type: [Help] to view help");
System.out.println("Type: [Turn] to turn, syntax: [Turn (direction)] left, right and backward are the possible directions");
System.out.println("Type: [Enter] to go through an entrance");
System.out.println("Type: [Slay] to kill stuff");
System.out.println("Type: [Take] to take stuff");
System.out.println("Typing: [/rocket smallbrains] has no effect here");
return;
}
else if (cmdone.equals("Enter")){
System.out.println("Enter what?");
String conone = in.next();
if (conone.equals("Forest") || conone.equals("The forest")){
System.out.println("You're already in the forest, dummy!");
}
else{
System.out.println("I don't know where that is");
}
}
else if (cmdone.equals("Turn right")){
System.out.println("You turn right");
}
continue;
}while (loopone = false);
One issue is you need to make this:
}while (loopone = false);
this:
}while (loopone == false);
Otherwise, you just need to make sure that you are setting loopone to false in each of the if statements. When you want to exit, you set loopone to true (loopone = true).
I am doing some practice work by expanding on a homework project I recently wrote. This is not for a grade, but I want to add some error checking to my code.
The program requires you to enter a name, select from a dropdown, select from a listbox and to select a radio button. My goal is to populate an error messagebox if any of the required items is blank.
The code I have so far for the error checking is below, but Im not sure how to take the individual lacking item and populate that to the message box since all of the error checking is in a single "if" statement.
Error checking code:
// Listener to handle the print button.
class ButtonListener implements ActionListener
{
ButtonListener() {}
public void actionPerformed(ActionEvent e)
{
JFrame frame1 = new JFrame("Show Message Dialog");
// Checks for required entries
if (error == 0 || name == "" || flag == 0)
{
JOptionPane.showMessageDialog(frame1,
"You must complete the form: " + missing, "ERROR",
JOptionPane.ERROR_MESSAGE);
}
else
{
// Get values from fields
setText();
System.out.println("Passenger's Name: " + name + "\n");
System.out.println("Age Group: " + ageValue + "\n");
for (int i = 0; i < value.length; i++)
{
System.out.println("Destination: " + value[i] + "\n");
}
System.out.println("Departure Day: " + day + "\n");
}
}
}
Thanks!
It looks like they can actually have multiple things wrong, so why only show one? I'm normally a C# dev so I'm not going to try to get the syntax right on typing this myself, but here's the concept:
Create a collection of some sort, like a list of strings.
Make 3 if statements, one for each of those errors, and put the field
names in for each one that fails. if (name.isEmpty()) {
errorList.Add("name"); }
Check to see if the count of items in the list is greater than 0. If
it is throw your error and put the name of the bad fields from the
collection into the string that you generate.