How to add ActionEvent to Two JTextFields - java

Question is: How do i add code to ensure that a table number (tableNumberJTextField) and waiter name (waiterNameJTextField) have been entered? If one or all fields are empty Use a JOptionPane to inform user that both fields must contain Information
At the moment i have:
private void calculateBillJButtonActionPerformed(
ActionEvent event )
{
if(event.getSource() == tableNumberJTextField)
{
}
else
{
JOptionPane.showInputDialog("Information missing");
}
} // end method calculateBillJButtonActionPerformed
Would i need another IF...Else and a JOptionPane in there for WaiterName as well as tableNumberJTextField seen in the code above OR am i completely doing this wrong????
FULL QUESTION THAT I HAVE TO DO IS:
calculateBillJButtonActionPerformed method (which immediately follows dessertJComboBoxItemStateChanged) and add code to ensure that a table number (tableNumberJTextField) and waiter name (waiterNameJTextField) have been entered. If one of these fields is empty, display a JOptionPane informing the user that both fields must contain information. Otherwise, call the calculateSubtotal method, which you implement in the next step, to calculate the subtotal of the bill. The calculateSubtotal method takes no arguments and returns a double containing the subtotal, which you should display in subtotalJTextField. Calculate and display the tax and the total of the bill in JTextFields taxJTextField and totalJTextField, respectively. The tax rate is specified in a constant TAX_RATE.

Presumably, the actionPerformed you're showing is for a button. If so, just check for text in the fields:
String tableNumber = tableNumberJTextField.getText().trim();
String waiterName = waiterNameJTextField.getText().trim();
if (tableNumber.length() == 0 || waiterName.length() == 0)
{
// show an error
}
else
{
// do a calculation
}

Related

Displaying Double in a different class and calculating by clicking on buttons [duplicate]

i am trying to create such calculation within a texArea which i calculate in one class, and i pass this onto a different class to perform the next calculation with only clicking buttons. So if i click on 'm10py' , whatever i have in the TextArea will be decreased by 0.10. I tried everything but it just doesnt seem to work. It doesnt throw any errors but the total in the TextArea stays still.
My main class where it performs the basic calculation.
public void actionPerformed(ActionEvent e) {
double frontM = 9.50;
double middleM = 7.30;
double backM = 6.70;
double vipM = 12.90;
//double total1 = Double.parseDouble(output.getText());
if (frontR.isSelected() && e.getSource() == calculate) {
double total = Integer.parseInt(frontT.getText()) * frontM;
output.setText(pounds.format(total));
} else if (middleR.isSelected() && e.getSource() == calculate) {
double total = Integer.parseInt(middleT.getText()) * middleM;
String total2 = String.valueOf(total);
output.setText(total2);
} else if (backR.isSelected() && e.getSource() == calculate) {
double total = Integer.parseInt(backT.getText()) * backM;
output.setText(pounds.format(total));
} else if (vipR.isSelected() && e.getSource() == calculate) {
double total = Integer.parseInt(vipT.getText()) * vipM;
output.setText(pounds.format(total));
} else if (e.getSource() == cancel) {
frontT.setText("1");
middleT.setText("1");
backT.setText("1");
vipT.setText("1");
output.setText("");
}
if (e.getSource() == payment) {
Payment paymentJ = new Payment();
paymentJ.output.setText(output.getText());
}
}
Second class which the calculation is passed on to a different textArea. I didnt do it for every button because i couldnt manage to the calculation.. ;
public void actionPerformed(ActionEvent e) {
Main main = new Main();
// double totalR = Double.parseDouble(output.getText());
String cost = main.output.getText();
double cost2 = Double.parseDouble(cost);
double total;
total = cost2;
double m10py = 0.10;
double m20py = 0.20;
double m50py = 0.50;
double m1p = 1.00;
double m2p = 2.00;
double m5p = 5.00;
double m10po = 10.00;
double m20po = 20.00;
if (e.getSource() == m10p) {
total = total - m10py;
String total2 = String.valueOf(total);
output.setText(total2);
}
}
I'm fairly new to this so please dont go have a go at me. I just need to know what is wrong with this. Thanks
One thing I do know is that you've got a serious reference problem going on. For example in your first posted actionPerformed method:
if (e.getSource() == payment) {
Payment paymentJ = new Payment(); // ***** line 1 ****
paymentJ.output.setText(output.getText()); // ***** line 2 ****
}
On line 1 above you create a new Payment object, called paymentJ, and on line 2 you change its state, by calling output.setText(...). I'm guessing that output is some text component, and you're trying to change the text that it displays, but here's the problem -- while paymentJ refers to a Payment object, it's not the Payment object that is being displayed, which is a completely distinct separate object, and changing the state of the non-displayed one created here by trying to change the text it displays, will have no effect on the output text component in the actualy displayed Payment object.
Similarly in your second posted actionPerformed method:
Main main = new Main();
// double totalR = Double.parseDouble(output.getText());
String cost = main.output.getText(); // ***** line 1 ****
double cost2 = Double.parseDouble(cost); // ***** line 2 ****
On line 1 above you create a new Main object, called cost, and on line 2 you query its state, by calling output.getText(). But again the Main instance created here is not the same Main object that is being displayed, and again this means that you have at least two (or more) Main objects, only one of which is being displayed, and the data that your extracting from the one created locally here will not reflect the changes made to the one that's displayed. You can test this by placing a println after you extract the text, for example:
Main main = new Main();
// double totalR = Double.parseDouble(output.getText());
String cost = main.output.getText();
System.out.println("cost is currently: " + cost); // ***** add this ****
double cost2 = Double.parseDouble(cost);
I will bet that you'll see a default value that is held by the text component returned, and not a value that was entered by the user or was displaying in the currently visualized Main GUI.
What to do?
Well for one, you could make the output fields static. That would be a quick and easy solution, but unfortunately it would be quick, easy and very very wrong, since this would break OOPs principles, making your code very difficult to test, enhance and inherit.
Better would be to pass references in where needed, for instance pass a reference to the displayed Payment object into the object that has that first actionPerformed method, and then call the appropriate methods on that object, and likewise pass a valid reference to the displayed Main object into the object whose code is displayed in your lower code snippet. This will allow you to query and modify the states of valid displayed objects. How to do this? I can't tell you specifically how to do this without a better and working code example from you (as per my comments). Generally, you could pass references around using constructor and setter method parameters.
Best would be to make your code more M-V-C or Model-View-Controller like, but this may be overkill for this program and may be beyond your current level of coding at this time.
For more help, for better help, please improve your question.
Based on your new code,
your Payment class should extend JDialog, not JFrame since a GUI should only have one main window
You will want to pass Main into Payment via Payment paymenetJ = new Payment(this);
You will need to change the Payment constructor to accept this: public Payment(Main main)
And inside the constructor use the parameter to set a field: this.main = main;
Then use this main field instead of creating a new Main object.

for loop jumps to last number in java android development

Hi I am making an android App, I want to add some values to a database and I want to do N times so I used a for loop as seen below:
private void addCodeToDataBase() {
for (int i = 1; i <= 100; i++) {
//indexnumber is a TextView
indexNumber.setText("Please enter the TAN code for Index number " + i);
//tanCode is an EditText
if (tanCode.getText().toString() != null) {
//index here is just an int so i can use the i inside the onClick
index = i;
//add is a button
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String codeText = tanCode.getText().toString();
dbHandler.addcode(index, codeText);
}
});
} else {
Toast.makeText(addcode.this, "Please enter your code !!!", Toast.LENGTH_LONG).show();
}
}
}
but what I am facing here is the for loop jumps to 100 at the first run, What I mean is the text will show :
Please enter the TAN code for Index number 100
it skips 99 numbers!! how would I fix it ?
It's Because your for loop executes so fast that you can't notice that the change of the text.First i is 0,and then it becomes 1,then the text will be "Please enter the TAN code for Index number 1" ......
your loop is working correctly but it is replacing text on each iteration that's why you think that it is jumping on last value please use break point and debug you will see each value on each iteration or use log in which you will see each value
It's not easy to imagine what your code does without seeing your declarations of indexNumber, tanCode, index, and, in particular, add. So, e.g., we don't know how often your if condition yields true.
However, most probably, the problem is that your assignment add.setOnClickListener(...) is just iterated with no user interaction in between. Now if you repeatedly assign something to your add (whatever that is), the last assignment will win.
If you want 100 buttons, you'll need to have an array or List of buttons to press, where each has a different tan code. If you want one button that repeatedly asks for the different tans, then you have to assign the data for click i + 1 only after click i has been handled, i.e. in the on click listener.
To give more specific help, we would need to know how your user interface should look (how many widgets of what kind) and how each widget should behave.

How can I approach this vending machine?

I have an assignment in Java to make a vending machine that displays items and prices using the printf tool and requests the user to enter the money they have. It then asks the user to make a selection with a character, exiting if they type x and prompting for another try if they type in an invalid character. It also keeps a running total of the money they have left and doesn't allow them to buy something they don't have the money for. After user 1 is done, it is then open for the next user to enter the amount of money they have and choose an item but with the items the first user chose absent. This cycle repeats until nothing is left in the machine or a user ends the program. Each user should be able to buy as many of each item as they want (one by one) until there is no more of that item.
I'd use a class to indicate a type of item.
public class Item { // or without public
private String name;
private char choice;
private double price;
private int amount; // or name it *quant*-what I can't spell that word
// Constructors, getters, setters, etc.
}
And you can use a list to handle them. This initializes items in the vender:
List<Item> items = new ArrayList<>();
items.add(new Item("Milk", 'a', 2.00, 5));
// Add other items
And this prints all items:
for(Item item : items)
System.out.printf(/* format string */, item.getName(), /* other arguments */);
And this handles actual purchase:
boolean foundItem = false;
for(Item item : items) {
if(item.getChoice() == choice) {
foundItem = true;
// Handle not enough money, not enough amount, etc. or sell it
}
}
if(!foundItem) {
// Invalid entry
}
And this it our main:
public static void main(String s) {
// Initialize items in the vender
// Initialize other things needed
while(/* has items to sell */) {
// Read a double as customer's money
// `break;` if is a program-exit request
while(true) {
// Print current items
// Read a character as customer choice, to lower case
// `break;` if is an customer-exit request
// Handle the actual purchase request
}
// Print customer exit message
}
// Print program exit message
}
Well, it's your responsibility to fill in the blank.
It seems like your while(choice==...) loop never ends.
The variable choice is never altered within the loop and so once you get in you'll never come out.
You should be prompting the user to enter a new choice inside the loop.

how can i get my program to accept more than 9 digit numbers?

I am currently writing a small app that test prime numbers. It's gui based but I'm having one problem. I have added some constraints to the program where users can only enter numbers by using the numberformatexception handler but whenever a user enters a number that is more than 9 digits long, it no longer considers it a number. Is there a solution to this problem? I have left my code below.
static void validation() // This is what happens when the "Check" button is clicked
{
// Retrieve information from the fields and print it out on the Frame
if (jtfX.getText().trim().length() == 0) // Check if the field is empty
{
jlSolution.setText("You have not entered anything yet");
}
else // Otherwise...
{
try // In general....
{
if (Long.parseLong(jtfX.getText()) < 0) // Check if it is a negative value
{
jlSolution.setText("The number you entered is less than zero");
}
else // If it isn't...
{
jlSolution.setText(new Algorithm(Integer.parseInt(jtfX.getText())).check()); // ....then check if this number is prime.
}
}
catch (NumberFormatException nfe) // ... always catch those who refuse to follow simple rules!
{
jlSolution.setText("Numerical values only please. " + "You entered: " + jtfX.getText());
}
}
}
Assuming the class Algorithim is a custom written class, you could replace the integer argument in its constructor with a BigInteger to hold larger values.
You would update your jlSolution field like so:
Algorithm algorithm = new Algorithm(new BigInteger(jtfX.getText()));
jlSolution.setText(algorithm.check());

Java Error When attempting to use the return from a method as an item in an if statement

I keep getting the following errors:
Cannot find symbol
Variable find
cannot find symbol
method getdata(int)
I am sure I am making this way more difficult than it is, but I am not sure how make this work so that the return from searching through the array, can be seen and evaluated by the if statement.
//assigns manager identification
manID = keyboard.nextInt();
//Fibonacci binary array for passwords
int[] passWArray = {00000000,00000001,00000001,00000010,00000011,00000101,00001000,00001101};
//item = find.getdata(manID);
if (getdata(manID) != -1)
{
//Do work here
dblPayRate = 10.85;
dblGrossPay = (intHours * dblPayRate) + (15.00);
dblTaxes = dblGrossPay * 0.19;
dblGrossPay -= dblTaxes;
//Print information to user
System.out.print("\n\n$" + df2.format(dblTaxes) +
" was withheld from this paycheck in taxes after working "+ intHours + " hours.\n\n");
System.out.print("The amount \"Employer Here\" owes you is $" + df2.format(dblGrossPay) + "\n");
}
else
{
// Dialog box for incorrect password
JOptionPane.showMessageDialog(null, "Invalid Entry! Contact the BOFH!");
//exits program (Note: needed for any JOptionPane programs)
System.exit(0);
}
}// end of long if statement for >50 hours
}//end of main method
public int find(int[] passWArray, int manID)
{
//search for manID in passWArray array
for (int index = 0; index < passWArray.length; index++)
if ( passWArray[index] == manID )
return manID;
//-1 indicates the value was not found
return -1;
}// end of find method
Change
if (getdata(manID) != -1)
into
if (find(passWArray , manID) != -1)
BTW those numbers don't magically become binary because they only contain 0's and 1's. Here's a hint:
int thirteen = Integer.parseInt("00001101", 2)
EDIT: in response to your next error
For now make the method static:
public static int find(int[] passWArray, int manID)
Eventually you might want to think about your 'Object-Oriented design' and just use the main() method as an entry point. Within main you create an instance of a class and let it do its work. In this way you can use the powers of O-O like encapsulation and inheritance and don't have to make everything static.
EDIT2: Afterthought
Your program seems to have the following 'actions':
user interaction
authentication
calculation
And there seem to be the following 'things' in your domain:
user
password
keyboard
display (command line and screen)
calculation
A good rule of thumb for an O-O design is to convert some of the 'things' and 'actions' already present in your domain into classes. A good class has a single responsibility and shares as little as possible of its data and methods with other classes (this is called information hiding).
Here's a class diagram that comes to mind:
User (represents a user, contains a single field 'password')
Authenticator (authenticates a user, contains the list of allowed passwords)
Console (all user interaction, either use System.out/in or Swing, but don't mix them)
Calculator (it calculates shit)

Categories

Resources