In my project "scientific calculator", im using 2 textfields in my GUI app. the problem now (or actually what i dislike) is the user has to use the 2 textfields even if he needs a function of only 1 parameter as trig functions and roots.
when i enter 1 value in the first textfield and leave the other blank, the program doesnt give any output.
Is there any way so i can use only 1 textfield for functions which take 1 parameter?
3 2958
You'll need to give us more details. For single operand functions like sin and 1/x, a "normal" calculator would get the single operand from the display and replace the display with the results. For double operand functions like x mod y and x**y, you get the x from the display when the user presses the function button and you get the y from the display when the user presses = and display the results. So, having textfields doesn't make sense.
For double operand functions like x mod y and x**y, you get the x from the display when the user presses the function button and you get the y from the display when the user presses = and display the results. So, having textfields doesn't make sense.
first: did u mean i should use a stack so i get the operand (y) which comes immediately before the equal sign and the operand (x) that comes immediately before the operator ??
second: how can i use a textfield more than once instead of having multiple textfields??
> should use a stack ?
You only need to have a class-level variable for the first operand and get the second operand from the textfield. That's sort of a stack, but a very small one.
> how can i use a textfield more than once
Take a look at the code I wrote for a simple calculator and try to understand it first, then think about how to add some scientific buttons. Notice that when an operator key is first pressed, I get the number from the textfield and store it in dDisplay, then on subsequent operator presses, I combine dDisplay with the current contents of the textfield.
Note, this is just a very simple calculator. If you want to have parentheses keys, then you will have to use a stack and the code will be more confusing. -
/*
-
* Chapter 6: Calculator
-
* Programmer: Sam Barrett
-
* Date: 24 Oct 2007
-
* Filename: Calculator.java
-
* Purpose: This program creates a calculator with a menu.
-
* Change Notes: Created an array of 'key caps' to make button creation easier.
-
* Did all of the button stuff in a single loop.
-
* Used the first letter of the menu & keys in a single switch statement.
-
* Corrected the code so that it works like a regular calculator.
-
* (Their code for = was wrong)
-
* Made the button font readable and the buttons square.
-
* Changed some variable names to ones that I liked better.
-
* Demoted the class-level variables that did not need to be class-level.
-
* Made it more modular.
-
*/
-
import java.awt.*;
-
import java.awt.datatransfer.*;
-
import java.awt.event.ActionEvent;
-
import java.awt.event.ActionListener;
-
import java.awt.event.WindowAdapter;
-
import java.awt.event.WindowEvent;
-
import java.text.DecimalFormat;
-
import javax.swing.JOptionPane;
-
-
public class Calculator extends Frame implements ActionListener
-
{
-
private TextField answerField;
-
private boolean isFirstOperand = true;
-
private boolean isClearPending = true;
-
private char cLastOp;
-
private double dDisplay = 0.0;
-
private DecimalFormat fmtDisplay = new DecimalFormat("########.########");
-
private String[] sKeyCaps = {"7","8","9","/",
-
"4","5","6","*",
-
"1","2","3","-",
-
"0",".","=","+"};
-
public Calculator()
-
{
-
//Create Menu
-
MenuBar mnuBar = new MenuBar();
-
this.setMenuBar(mnuBar);
-
Menu mnuFile = new Menu("File", true);
-
mnuBar.add(mnuFile);
-
MenuItem mnuFileExit = new MenuItem("Exit");
-
mnuFileExit.addActionListener(this);
-
mnuFile.add(mnuFileExit);
-
Menu mnuEdit = new Menu("Edit", true);
-
mnuBar.add(mnuEdit);
-
MenuItem mnuEditClear = new MenuItem("Clear");
-
mnuEditClear.addActionListener(this);
-
mnuEdit.add(mnuEditClear);
-
MenuItem mnuEditCopy = new MenuItem("Copy");
-
mnuEditCopy.addActionListener(this);
-
mnuEdit.add(mnuEditCopy);
-
MenuItem mnuEditPaste = new MenuItem("Paste");
-
mnuEditPaste.addActionListener(this);
-
mnuEdit.add(mnuEditPaste);
-
Menu mnuAbout = new Menu("About", true);
-
mnuBar.add(mnuAbout);
-
MenuItem mnuAboutCalc = new MenuItem("About Caculator");
-
mnuAboutCalc.addActionListener(this);
-
mnuAbout.add(mnuAboutCalc);
-
-
//Create Components
-
answerField = new TextField(20);
-
answerField.setEditable(false);
-
-
//Setup Frame & Layouts & buttons
-
this.setLayout(new BorderLayout());
-
Panel keysPanel = new Panel();
-
keysPanel.setLayout(new GridLayout(4,4,10,10));
-
Font f = new Font("Verdana", Font.BOLD, 20);
-
Button[] keys = new Button[16];
-
for (int i=0; i<16; i++)
-
{
-
keys[i] = new Button(sKeyCaps[i]);
-
keys[i].setFont(f);
-
keys[i].addActionListener(this);
-
keysPanel.add(keys[i]);
-
}
-
this.add(answerField, BorderLayout.NORTH);
-
this.add(keysPanel, BorderLayout.CENTER);
-
-
clearCalculator();
-
-
this.addWindowListener(
-
new WindowAdapter()
-
{
-
public void windowClosing(WindowEvent e)
-
{ System.exit(0); }
-
}
-
);
-
}
-
public void actionPerformed(ActionEvent e)
-
{
-
String sItem = e.getActionCommand();
-
char cFirst = sItem.charAt(0);
-
switch (cFirst)
-
{
-
case 'E': // Exit
-
System.exit(0);
-
break;
-
case 'C': // Clear or Copy
-
if (sItem == "Clear")
-
clearCalculator();
-
else if (sItem == "Copy")
-
{
-
Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
-
StringSelection contents = new StringSelection(answerField.getText());
-
cb.setContents(contents, null);
-
}
-
break;
-
case 'P': // Paste
-
Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
-
Transferable contents = cb.getContents(this);
-
try
-
{
-
String s = (String)contents.getTransferData((DataFlavor.stringFlavor));
-
answerField.setText(fmtDisplay.format(Double.parseDouble(s)));
-
}
-
catch (Throwable ex)
-
{
-
clearCalculator();
-
}
-
break;
-
case 'A': // About
-
JOptionPane.showMessageDialog(this,
-
"Calculator ver. 1.0\nCornerStone Software\nCopyright 2007\nAll rights reserved",
-
"About Calculator", JOptionPane.INFORMATION_MESSAGE);
-
break;
-
case '0': case '1': case '2': case '3': case '4': case '5': // Numbers
-
case '6': case '7': case '8': case '9': case '.':
-
if (isClearPending) // Start of a new operand
-
{
-
answerField.setText("");
-
isClearPending = false;
-
}
-
answerField.setText(answerField.getText() + sItem);
-
break;
-
case '+': case '-': case '*': case '/': case '=': // Operators
-
if (isFirstOperand)
-
processFirstOp(cFirst);
-
else
-
processNextOp(cFirst);
-
break;
-
}
-
}
-
-
public void clearCalculator()
-
{
-
isFirstOperand = true;
-
answerField.setText("");
-
answerField.requestFocus();
-
}
-
public void processFirstOp(char cOp)
-
{
-
String s = answerField.getText();
-
if (s=="")
-
dDisplay = 0.0;
-
else
-
dDisplay = Double.parseDouble(s);
-
isClearPending = true;
-
isFirstOperand = false;
-
cLastOp = cOp;
-
}
-
-
public void processNextOp(char cOp)
-
{
-
String s = answerField.getText();
-
if (s!="")
-
{
-
Double d = Double.parseDouble(s);
-
switch (cLastOp) // Note, = falls thru: nothing to do but set ClearPending
-
{
-
case '+':
-
dDisplay += d;
-
break;
-
case '-':
-
dDisplay -= d;
-
break;
-
case '*':
-
dDisplay *= d;
-
break;
-
case '/':
-
dDisplay /= d;
-
break;
-
}
-
answerField.setText(fmtDisplay.format(dDisplay));
-
isClearPending = true;
-
}
-
cLastOp = cOp;
-
}
-
-
public static void main(String[] args)
-
{
-
//Setup the frame
-
Calculator frm = new Calculator();
-
frm.setTitle("Calculator Application");
-
frm.setBounds(200, 200, 250, 300);
-
frm.setVisible(true);
-
-
//Setup an icon
-
Image icon = Toolkit.getDefaultToolkit().getImage("calcImage.gif");
-
frm.setIconImage(icon);
-
}
-
}
-
Sign in to post your reply or Sign up for a free account.
Similar topics
by: R.G. Vervoort |
last post by:
I would like to select an option in a pulldown, select a record in a mysql
database depending on the pulldown selection and then put the data from the
record in the textfields.
I can retrieve...
|
by: Ed |
last post by:
Hi,
I have an html page with a div element within a form for dynamically
creating textfields.
The problem is when I click a link on the page, or the submit button,
then click the back button,...
|
by: anirban.anirbanju |
last post by:
hi there,
i've some serious problem to add rows dynamically in a table.
my table contains 5 cell.
| check | from_value | to_value | color_text | color_value |...
|
by: rohayre |
last post by:
Im a long time java developer and actually have never done anything
with java scripting. I'd like to write a short simple script for
calculating a date in the future based on today's date and a...
|
by: haran22 |
last post by:
verify and tell me what runtime error in this pgm
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.sql.*;
public class screen extends Applet implements...
|
by: nicky77 |
last post by:
Hi there, newish to javascript so grateful for any help.
I am creating a test generator and have an array of textfields ("answer") created by a simple piece of PHP code. As you can see, I have...
|
by: star111792 |
last post by:
Hello all,
i m doing networking in java. i m trying to build a client/server appplication in which i m trying to create a simple login page. tasks that im trying to do are in following sequence:
...
|
by: Kevin R |
last post by:
How do you create those small textfields that I see for inputing passwords
and such?
Kevin
|
by: f3dde |
last post by:
Hi there,
I have a question about forms in MS Access..
Is it possible in any way at all, to add info in 2 textfields and save it as 1 record.
Detail:
I have a record with 3 fields....
|
by: DolphinDB |
last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation.
Take...
|
by: DolphinDB |
last post by:
Tired of spending countless mintues downsampling your data? Look no further!
In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
|
by: ryjfgjl |
last post by:
ExcelToDatabase: batch import excel into database automatically...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
by: Vimpel783 |
last post by:
Hello!
Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
|
by: ArrayDB |
last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
|
by: PapaRatzi |
last post by:
Hello,
I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
|
by: Shællîpôpï 09 |
last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
|
by: Faith0G |
last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
| |