Java calculation

System.out.println(0.1 + 0.2);
OUTPUT:0.30000000000000004
What?
how precise is java anyway?
and is there other exemple like this one?

Well, it is not just java. It is because the way computer represents numbers. We have to learn how to deal with the precision errors and not blaming the computers.
The computer represents numbers in base 2. This can result in loss of precision since often a binary fraction cannot exactly represent a given finite decimal fraction (0.1 for example). All finite binary fractions, however, can be converted to finite decimal fractions.
System.out.println(0.1 + 0.2);As long as the number can be converted to a binary fraction, you should get correct numbers. In the example you gave above, 0.1 is not exact in binary format, so you won't get 0.3.

Similar Messages

  • Programming backspace function in a java calculator.

    I am doing a java calculator.
    I want to program the backspace function, here is the code I have:
    private void jbbackspaceMouseClicked(java.awt.event.MouseEvent evt) {                                        
    // TODO add your handling code here:
    caja=Float.valueOf(jtfpantalla.getText()).floatValue();
    if(caja==0){
    jtfpantalla.setText("0");
    else{
    char caja2;
    caja2=Float.toString(caja);
    caja2.getChars(0,24,caja2,0);
    jtfpantalla.setText(String.valueOf(caja));
    Netbeans sends me 2 errors. I don't know how to use caja, as string or as an array. I want to convert it ,to print the characters of the array except the last character when the backspace button will be pressed.
    I want to count the decimal point as another character, and print the characters except the last two when the decimal point is the penultime in the array.

    I'd suggest that you store the temporary or displayed value in the calculator as a List of characters, or a String, and then don't ever turn it into a number until someone pushes the '=' button.
    That's assuming I know what you're doing, which maybe I don't.

  • Help Please Needed for Java Calculator - ActionListener HELP

    Hi. I am constructing a simple Java calculator and need help with the actionlistener and how it could work with my program. I am not too sure how to begin constructing the actionlistener. I would like to know the best and most simple solution to get this program work the way it should, like a real calculator. If anyone can help me, that would be much appreciated.
    package calculator;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class CalculatorGUI extends JFrame implements ActionListener{
    JTextField screen;
    JButton button7;
    JButton button8;
    JButton button9;
    JButton button4;
    JButton button5;
    JButton button6;
    JButton button1;
    JButton button2;
    JButton button3;
    JButton button0;
    JButton add;
    JButton minus;
    JButton multiply;
    JButton divide;
    JButton equals;
    JButton clear;
    private JTextField m_displayField;
    private boolean m_startNumber = true;
    private String m_previousOp = "=";
    private CalculatorLogic m_logic = new CalculatorLogic();
    public CalculatorGUI() {
    CalculatorGUILayout customLayout = new CalculatorGUILayout();
    getContentPane().setFont(new Font("Helvetica", Font.PLAIN, 12));
    getContentPane().setLayout(customLayout);
    screen = new JTextField("textfield_1");
    getContentPane().add(screen);
    button7 = new JButton("7");
    getContentPane().add(button7);
    button7.addActionListener(this);
    button8 = new JButton("8");
    getContentPane().add(button8);
    button8.addActionListener(this);
    button9 = new JButton("9");
    getContentPane().add(button9);
    button9.addActionListener(this);
    button4 = new JButton("4");
    getContentPane().add(button4);
    button4.addActionListener(this);
    button5 = new JButton("5");
    getContentPane().add(button5);
    button5.addActionListener(this);
    button6 = new JButton("6");
    getContentPane().add(button6);
    button6.addActionListener(this);
    button1 = new JButton("1");
    getContentPane().add(button1);
    button1.addActionListener(this);
    button2 = new JButton("2");
    getContentPane().add(button2);
    button2.addActionListener(this);
    button3 = new JButton("3");
    getContentPane().add(button3);
    button3.addActionListener(this);
    button0 = new JButton("0");
    getContentPane().add(button0);
    button0.addActionListener(this);
    add = new JButton("+");
    getContentPane().add(add);
    add.addActionListener(this);
    minus = new JButton("-");
    getContentPane().add(minus);
    minus.addActionListener(this);
    multiply = new JButton("*");
    getContentPane().add(multiply);
    multiply.addActionListener(this);
    divide = new JButton("/");
    getContentPane().add(divide);
    divide.addActionListener(this);
    equals = new JButton("=");
    getContentPane().add(equals);
    equals.addActionListener(this);
    clear = new JButton("Clear");
    getContentPane().add(clear);
    clear.addActionListener(this);
    setSize(getPreferredSize());
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    public void actionPerformed(ActionEvent event) {
    public static void main(String args[]) {
    CalculatorGUI window = new CalculatorGUI();
    window.setTitle("Calculator");
    window.pack();
    window.show();
    class CalculatorGUILayout implements LayoutManager {
    public CalculatorGUILayout() {
    public void addLayoutComponent(String name, Component comp) {
    public void removeLayoutComponent(Component comp) {
    public Dimension preferredLayoutSize(Container parent) {
    Dimension dim = new Dimension(0, 0);
    Insets insets = parent.getInsets();
    dim.width = 421 + insets.left + insets.right;
    dim.height = 494 + insets.top + insets.bottom;
    return dim;
    public Dimension minimumLayoutSize(Container parent) {
    Dimension dim = new Dimension(0, 0);
    return dim;
    public void layoutContainer(Container parent) {
    Insets insets = parent.getInsets();
    Component c;
    c = parent.getComponent(0);
    if (c.isVisible()) {c.setBounds(insets.left+8,insets.top+8,408,64);}
    c = parent.getComponent(1);
    if (c.isVisible()) {c.setBounds(insets.left+8,insets.top+80,96,56);}
    c = parent.getComponent(2);
    if (c.isVisible()) {c.setBounds(insets.left+120,insets.top+80,96,56);}
    c = parent.getComponent(3);
    if (c.isVisible()) {c.setBounds(insets.left+232,insets.top+80,96,56);}
    c = parent.getComponent(4);
    if (c.isVisible()) {c.setBounds(insets.left+8,insets.top+144,96,56);}
    c = parent.getComponent(5);
    if (c.isVisible()) {c.setBounds(insets.left+120,insets.top+144,96,56);}
    c = parent.getComponent(6);
    if (c.isVisible()) {c.setBounds(insets.left+232,insets.top+144,96,56);}
    c = parent.getComponent(7);
    if (c.isVisible()) {c.setBounds(insets.left+8,insets.top+208,96,56);}
    c = parent.getComponent(8);
    if (c.isVisible()) {c.setBounds(insets.left+120,insets.top+208,96,56);}
    c = parent.getComponent(9);
    if (c.isVisible()) {c.setBounds(insets.left+232,insets.top+208,96,56);}
    c = parent.getComponent(10);
    if (c.isVisible()) {c.setBounds(insets.left+120,insets.top+272,96,56);}
    c = parent.getComponent(11);
    if (c.isVisible()) {c.setBounds(insets.left+344,insets.top+80,72,56);}
    c = parent.getComponent(12);
    if (c.isVisible()) {c.setBounds(insets.left+344,insets.top+144,72,56);}
    c = parent.getComponent(13);
    if (c.isVisible()) {c.setBounds(insets.left+344,insets.top+208,72,56);}
    c = parent.getComponent(14);
    if (c.isVisible()) {c.setBounds(insets.left+344,insets.top+272,72,56);}
    c = parent.getComponent(15);
    if (c.isVisible()) {c.setBounds(insets.left+344,insets.top+336,72,56);}
    c = parent.getComponent(16);
    if (c.isVisible()) {c.setBounds(insets.left+8,insets.top+408,408,72);}
    }

    Yeah, I have a rough idea of what the calculator
    should do, like most people would. Its just that I
    dont know how to implement this in Java. Thats the
    problem. Can anyone provide me with code snippets
    that I can try?No I would rather see you make an effort from what has been discussed here. This is not a Java problem this is a general programming problem.

  • Java Calculator

    I am relatively new to Java programming and am in a Dilemma. I am trying to develop a Java Calculator GUI and I want to include a "memory" button. Any ideas on how I would implement it.
    It needs to be able to store a record and when" memory total"(another button) is pressed it should add all the figures saved by the "Memory" button.
    Thanks in advance for the help
    Ed

    You don't need a database for that.
    Just use an array of floats.
    Or if you prefer, an ArrayList of Floats.
    You just keep adding to the above to store them.
    When you want to total them then you just iterate through them and add them up.

  • Problems with Maths (decimals) In java calculations

    In a normal calculator type in
    (27.8 / 3) * 12 = 111.2
    Do this in Java and I get
    111.20000000000002
    This is causing a problem in my calculations, is this a known bug and how can i get around it ?
    Friendly Regards
    Steven

    Yes i know I will read the article but as I said just
    wanted get this working before i go home today.
    This is how I fixed it anyway
    DecimalFormat threeDecimals = new
    DecimalFormat("0.000");
    thirdOfWk =
    Double.parseDouble(threeDecimals.format(thirdOfWk));
    Thanks for the help guysI think you are going to need to do some rounding otherwise this will not fix all the problems.
    Consider that:
    111.20000000000002
    truncated to 3 decimals is:
    111.200
    But what if the number comes up something like this (I am not sure that it can happen but I would guess that it can):
    123.19999999999998 (instead of 123.2)
    truncated to 3 decimals is:
    123.199
    And I think doremifasollatido is correct and you have another problem (because you are putting the truncated number back into a Double).
    You really need to use BigDecimal or integers. For integers you would need to scale the numbers and then display with decimals.
    Message was edited by:
    jbish

  • Java Calculations base 8 or base 10?

    My colleague was told by out 'Java Experts' who are developers for a prominent Indian outsourcing company that all calculations are carried out in base 8 or is a number was multiple by 10 it will actually multiply the number by 8 as 10 (base 8) is 8 (base 10). So a simple currency conversion becomes either a multiple by 144 to make it pence from pounds. Is that correct? My colleague has deceived to simply move the decimal point by two places which needs more coding then a multiple. Please advice

    My colleague was told by out 'Java Experts' who are developers for a
    prominent Indian outsourcing company that all calculations are
    carried out in base 8 or is a number was multiple by 10 it will actually
    multiply the number by 8 as 10 (base 8) is 8 (base 10). So a simple
    currency conversion becomes either a multiple by 144 to make it
    pence from pounds. Is that correct? My colleague has deceived to
    simply move the decimal point by two places which needs more
    coding then a multiple. Please adviceIt isn't April's fool day yet but your colleague has been tricked already ;-)
    Or did he speak to some 'manager' by accident?
    kind regards,
    Jos (*giggle*)

  • Java Calculator, Minus & multiplication button gets wrong answer?

    import java.awt.event.*;
    import java.applet.Applet;
    import javax.swing.*;
    import java.awt.*;
    public class calc extends JApplet implements ActionListener
         JTextField input = new JTextField("");
         JButton numbers[] = new JButton[10];
         JButton add = new JButton("+");
         JButton equals = new JButton("=");
         JButton minus = new JButton("-");
        JButton multiply = new JButton("*");
        JButton divide = new JButton("/");
        JButton clear = new JButton("AC");
         int num1 = 0;
         int num2 = 0;     
         String oper = " ";
         public void init()
              setLayout(null);
              setBackground(new Color(227,131,125));          
              Design();
         public void Design()
              int x = 1;
              int y= 1;
              int wi = 10;
              int he = 50;
              input.setSize(250,30);
              input.setLocation(10,10);
              add(input);
              add.setSize(80,30);
              add.setLocation(280,50);
              add.addActionListener(this);
              add(add);
              minus.setSize(80,30);
              minus.setLocation(280,90);
              minus.addActionListener(this);
              add(minus);
              multiply.setSize(80,30);
              multiply.setLocation(280,130);
              multiply.addActionListener(this);
              add(multiply);
              divide.setSize(80,30);
              divide.setLocation(280,175);
              divide.addActionListener(this);
              add(divide);
              equals.setSize(80,30);
              equals.setLocation(190,175);
              equals.addActionListener(this);
              add(equals);
             clear.setSize(80,30);
              clear.setLocation(100,175);
              clear.addActionListener(this);
              add(clear);
              while(x<=10)
                   if (x==10)
                   numbers[x-1] = new JButton("0");
                   numbers[x-1].setSize(80,30);
                   numbers[x-1].setLocation(wi,he);
                   //numbers[x-1].setBackground();
                   else
                   numbers[x-1] = new JButton(Integer.toString(x));
                   numbers[x-1].setSize(80,30);
                   numbers[x-1].setLocation(wi,he);
                   wi = wi + 90;
                        if(x%3==0)
                             he = he + 40;
                             wi = 10;
                   numbers[x-1].addActionListener(this);
                   add(numbers[x-1]);          
                   x++;
         public void actionPerformed(ActionEvent act)
              int x = 0;
              while(x<10)
                   if(act.getSource().equals(numbers[x]))
                        if(x==9)
                             input.setText("0");
                        else                    
                        input.setText(Integer.toString(x+1));
                   x++;
              if (act.getSource().equals(add))
                   num1 = Integer.parseInt(input.getText());
              else if(act.getSource().equals(equals))
                   num2 = Integer.parseInt(input.getText());
                   input.setText(Integer.toString(num1 + num2));
                   if (act.getSource().equals(minus))
                   num1 = Integer.parseInt(input.getText());
                   oper = "minus";
              else if(act.getSource().equals(equals))
                   num2 = Integer.parseInt(input.getText());
                   if(oper.equals("minus"))
                        input.setText(Integer.toString(num1 - num2));
                   if (act.getSource().equals(multiply))
                   num1 = Integer.parseInt(input.getText());
                   oper = "multiply";
              else if(act.getSource().equals(equals))
                   num2 = Integer.parseInt(input.getText());
                   if(oper.equals("multiply"))
                        input.setText(Integer.toString(num1 * num2));
    The addition button is working, but i cant seem to make minus and multiply button work, they get wrong answer when i use them.. what could bee the problem with my code

    Sorry, but I don't see a simple fix in this code here (Hopefully I'm wrong and someone else will see this, but I don't) Because of this, I recommend that you fully scrap this code and start over from square one. I don't think that you really "see" your logic here. To help you see what you are trying to do, you need to separate your logic from your GUI. Try to build a non-gui calculator that works via simple console menu. Once you get this working, then use this code to create a GUI calculator.

  • "Exception in thread "main" java.lang.NoClassDefFound: classname" error.

    Here's my code:
    public class Hello
    public static void main( String[] args )
    System.out.println( "Hello!" );
    it compiles but it wont run. it encounters this error: " Exception in thread "main" java.lang.NoClassDefFoundError: Hello"
    Since I am using jdk1.3, my path is "c:\windows;c:\windows\command;c:\progra~1\dell\resolu~1\common\bin;c:\jdk1.3\bin"
    another error I noticed in my computer were these while running Calculator.java:
    Calculator.java:11: cannot resolve symbol
    symbol: class Calc
    location: class Calculator
    Calc calculator;
    Calculator.java:36: cannot resolve symbol
    symbol: class Calc
    location: class Calculator
    calculator = new Calc();
    2 errors
    Yet my Calculator.java, Calculator.class, Calc.java, Calc.class, Calculator.html files are all in one folder.
    Since I am using jdk1.3, my path is "path=c:\windows;c:\windows\command;c:\progra~dell\resolu~1\common\bin;c:\jdk1.3\bin;"
    I would greatly appreciate your help.
    Thank you very much!=)

    hi!
    set the classpath to the relative path "."!
    in the command box type this:
    SET CLASSPATH=.;
    then it should work!
    visit: >> http://www.menzsoft.ch <<
    greets

  • GUI Calculator

    Hello everyone! I'm trying to create a GUI Calculator but cannot get my program to compile. Please could someone assist me, thanks.
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class CalculatorFrame extends JFrame
    private Container contentPane;
    //The componenets used in the calculator
    private JTextField display;
    private JButton addition;
    private JButton subtract;
    private JButton multiply;
    private JButton divide;
    private JButton mod;
    private JButton enter;
    private JButton [] digits;
    //End of components
    //Integer representations for the arithmetic operations needed
    private final static int ADD = 1;
    private final static int SUB = 2;
    private final static int MUL = 3;
    private final static int DIV = 4;
    private final static int MOD = 5;
    //ENd of arithmethic operations
    //Integer holding the operator that the user requested
    private int op;
    //Boolean variable to help perform the calculations
    private boolean firstFilled;
    private boolean clearScreen;
    //Constructor for the class
    public CalculatorFrame()
    contentPane=new Container();
    this.setSize(400,300); //sets the size of the frame
    this.setTitle("MIS 222 Calculator"); //sets the title of the frame
    //allows the "X" box in the upper right hand corner to close the entire application
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    contentPane=this.getContentPane(); //gets the content pane
    //Methods
    addDisplay();
    addDigits();
    addDigitActionListeners();
    addOperation();
    private void addDisplay()
    JLabel displayLab = new JLabel("Answer");
    JPanel north = new JPanel();
    north.add(displayLab);
    contentPane.add(north, "North");
    //diplay was already declared above the constructor
    display = new JTextField(25);
    //adding the components to the panel
    north.add(displayLab);
    north.add(display);
    //adding the panel to frame's content pane
    contentPane.add(north, "North");
    //Declaring the global digits array
    private void addDigits()
    //Add 1 large panel to hold the 3 inner panels
    JPanel digPanel = new JPanel();
    //Set the panel's preferred size so that it will keep everything in line
    digPanel.setPreferredSize(new Dimension(200, 275));
    //Initialize the top 3 digits' JPanel and set its preferrd size
    JPanel topDigits = new JPanel();
    topDigits.setPreferredSize(new Dimension(200,60));
    //Initialize the middle 2 digits' JPanel and set its preferred size
    JPanel midDigits = new JPanel();
    midDigits.setPreferredSize(new Dimension(200,60));
    //Initialize the bottom digits' JPanel and set its preferred size
    JPanel botDigits = new JPanel();
    botDigits.setPreferredSize(new Dimension(200, 75));
    //Initialize the JButton array
    digits = new JButton[11];
    //Initialize each of the top Panel's digit buttons, and add it to the top panel
    for(int i=1; i<4; i++)
    String lab=(new Integer(i)).toString();
    digits=new JButton(lab);
    topDigits.add(digits);
    //Adding the top Digit Panel to the overall digit panel
    digPanel.add(topDigits, BorderLayout.CENTER);
    //Adding the middle Digit Panel to the overall digit panel
    digPanel.add(midDigits, BorderLayout.CENTER);
    //Adding the bottom Digit Panel to the overall digit panel
    digPanel.add(botDigits, BorderLayout.CENTER);
    //Add the overall digit Panel to the Frame's contentpane
    contentPane.add(digPanel, BorderLayout.CENTER);
    //Method created to add the DigitAction Listeners
    addDigitActionListeners();
    //Method created to add all of the DigitActionListeners
    private void addDigitActionListeners()
    for(int i=0; i<10; i++)
    digits.addActionListener(new DigitActionListener(i));
    digits[10].addActionListener(new DigitActionListener("."));
    //DigitActionListener class
    public class DigitActionListener implements ActionListener
    private String myNum;
    public DigitActionListener(int num)
    myNum=""+num;
    public DigitActionListener(String num)
    myNum=num;
    public void actionPerformed(ActionEvent e)
    if(display.getText().equals("Please enter a valid number")|| clearScreen)
    clearScreen=false;
    display.setText("");
    //OperatorActionListener class
    public void OpActionListener implements ActionListener
    private int myOpNum;
    public OpActionListener(int op)
    myOpNum=op;
    public void actionPerformed(ActionEvent e)
    { //Checks to see if the user has already enterd a number
    if(!firstFilled)
    try{
    //Parse the number entered
    String number=display.getText();
    dNum1=Double.parseDouble(number);
    //Sets the flag for the firstFilled to true
    firstFilled=true
    //Sets the op variable so when the "Enter" button is pressed, it will know which operation to perform
    op=myOpNum;
    //Clears the textbox
    display.setText("");
    catch(Exception er)
    display.setText("Please enter a valid number");
    //This is the second number being entered
    else{
    try{
    String number=display.getText();
    String result;
    dNum2=Double.parseDouble(number);
    firstFilled=true;
    op=myOpNum;
    display.setText("");
    catch(Exception er)
    display.setText("Please enter a valid number");
    private void addOperation()
    JPanel opPanel=new JPanel();
    opPanel.setPreferredSize(new Dimension(75,200));
    JButton clear = new JButton("C");
    JButton addition = new JButton("+");
    JButton subtraction = new JButton("-");
    JButton multiply = new JButton("*");
    JButton divide = new JButton("/");
    JButton mod = new JButton("%");
    JButton enter = new JButton("Enter");
    addition.addActionListener(new OpActionListener(ADD));
    subtraction.addActionListener(new OpActionListener(SUB));
    multiply.addActionListener(new OpActionListener(MUL));
    divide.addActionListener(new OpActionListener(DIV));
    mod.addActionListener(new OpActionListener(MOD));
    clear.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    display.setText("");
    firstFilled=false;
    enter.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    double result;
    String answer="";
    String number = display.getText();
    dNum2 = Double.parseDouble(number);
    dNum1=Double.parseDouble(number);
    switch(op)
    case ADD:
    result = dNum1 + dNum2;
    break;
    case SUB:
    result = dNum1 - dNum2;
    break;
    case MUL:
    result = dNum1 * dNum2;
    break;
    case DIV:
    result = dNum1 / dNum2;
    break;
    default:
    result= -1.0;
    break;
    if(result==(int)result)
    answer=(new Integer((int)result)).toString();
    else
    answer=(new Double(result)).toString();
    display.setText(answer);
    clearScreen=true;
    firstFilled=false;
    dNum1=0;
    dNum2=0;
    opPanel.add(clear);
    opPanel.add(addition);
    opPanel.add(subtraction);
    opPanel.add(multiply);
    opPanel.add(divide);
    opPanel.add(mod);
    opPanel.add(enter);
    contentPane.add(opPanel, "East");
    //Creating the frame object
    public class CalculatorMain
    public void main(String[] args)
    CalculatorFrame cf=new CalculatorFrame();
    cf.show();
    ERRORS THAT I HAVE!!:
    javac calculatorframe.javacalculatorframe.java:150: '(' expected
    public void OpActionListener implements ActionListener
    ^
    calculatorframe.java:7: class CalculatorFrame is public, should be declared in a file named CalculatorFrame.java
    public class CalculatorFrame extends JFrame
    ^
    calculatorframe.java:54: cannot resolve symbol
    symbol : method addOperation ()
    location: class CalculatorFrame
    addOperation();
    ^
    3 errors
    >

    Here I did this for someone in the 'new to' forum about 2 weeks back. They had some really awful code they say they got from a java book -cannot recall the author, but I do know his work should be burned and the person executed with a mercy killing (I still haven't recovered from the shock of this and I think most of the regular contributors in these forums could write FAR BETTER books than this clown)
    Hmm... I do rant sometimes. Erm, you're welcome - this is their rebuild;-import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Calculator extends JFrame implements ActionListener{
       JButton []buttons = new JButton[25];
         private JTextField display= new JTextField("0.0",12);
       String status = "    Status : ";
       JLabel label = new JLabel(status);
         private double sum    = 0.0d;
         private String nums   = "";
         private double arg    = 0.0d;
         private double tot    = 0.0d;
         private boolean start = true,div,mult,add,sub;
         private String memory = "0";
       java.text.DecimalFormat df=new java.text.DecimalFormat("#,##0.0####");
       Font f = new Font("Times New Roman", Font.BOLD,14);
       Color midBlue  = new Color(20, 15, 140);
    public Calculator(){
         super();
         setTitle("Java Calculator");
       JPanel mainPan = new JPanel();
       mainPan.setLayout(new BorderLayout() );
       JPanel textPanel = new JPanel();
       textPanel.setBackground(midBlue);
       textPanel.setLayout(new BorderLayout());
       display.setHorizontalAlignment(JTextField.RIGHT);
       label.setForeground(Color.white);
       display.setFont(new Font("",0,14));
       display.setEditable(false);
       display.setBackground(Color.white);
       label.setFont(new Font("Arial",0,12));
       JPanel emptyPan = new JPanel();
       emptyPan.setBackground(midBlue);
       JPanel emptyP1 = new JPanel();
       emptyP1.setBackground(midBlue);
       JPanel emptyP2 = new JPanel();
       emptyP2.setBackground(midBlue);
       textPanel.add("North", label);
       textPanel.add("Center", display);
       textPanel.add("South",emptyPan );
       textPanel.add("East",emptyP1 );
       textPanel.add("West",emptyP2 );
       JPanel butPanel = new JPanel();
       butPanel.setBackground(midBlue);
       butPanel.setLayout(new GridLayout(5, 5, 10, 10));
       String []str = {"","","","CE","C","1","2","3","/","RM","4","5","6",
                      "*","CM","7","8","9","+","M+","0",".","=","-","M-"};
       for(int j=0; j<25; j++) {
          if(j<3) {
             buttons[j] = new JButton(str[j]);
             butPanel.add(buttons[j]);
          else {
             buttons[j] = new JButton(str[j]);
             buttons[j].addActionListener(this);
             buttons[j].setFont(f);
               buttons[j].setBorder(BorderFactory.createRaisedBevelBorder());
             butPanel.add(buttons[j]);
       JPanel emptyPan1 = new JPanel();
       emptyPan1.setBackground(midBlue);
       JPanel emptyPan2 = new JPanel();
       emptyPan2.setBackground(midBlue);
       JPanel emptyPan3 = new JPanel();
       emptyPan3.setBackground(midBlue);
       mainPan.add("North", textPanel);
       mainPan.add("Center", butPanel);
       mainPan.add("South", emptyPan1);
       mainPan.add("East", emptyPan2);
       mainPan.add("West", emptyPan3);
       getContentPane().add(mainPan);
    public void actionPerformed(ActionEvent e){
       String s = e.getActionCommand();
          if ((s.equals("1"))||(s.equals("2"))||(s.equals("3"))||(s.equals("4"))
            ||(s.equals("5"))||(s.equals("6"))||(s.equals("7"))||(s.equals("8"))
            ||(s.equals("9"))||(s.equals("0"))||(s.equals("."))){
               nums += s;
               display.setText(nums);
          if (s.equals("/")){
             arg=Double.parseDouble(display.getText());
             nums="";
             div=true;
          if (s.equals("*")){
             arg=Double.parseDouble(display.getText());
             nums="";
             mult=true;
          if (s.equals("-")){
             arg=Double.parseDouble(display.getText());
             nums="";
             sub=true;
          if (s.equals("+")){
             arg=Double.parseDouble(display.getText());
             nums="";
             add=true;
          if (s.equals("=")){
             tot=Double.parseDouble(display.getText());
             if(div)tot=arg/tot;
             if(mult)tot=arg*tot;
             if(add)tot=arg+tot;
             if(sub)tot=arg-tot;
             display.setText(df.format(tot));
             div=mult=sub=add=false;
    public static void main(String[] args){
        Calculator frame = new Calculator();
        frame.setVisible(true);
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
          Image onFrame = Toolkit.getDefaultToolkit().getImage("flag.gif") ;
        frame.setIconImage(onFrame);
        frame.setLocation(300, 240);
        frame.setResizable(false);
        frame.pack();
    }

  • Trapping and making use of keyboard keys in java

    hello friends,
    wish to seek your advice and help once again. i'm trying to create a 'calculator' application using java. i've created buttons that represent such keys like: '*', '/', '\', '+', '-' etc. and '1', '2', '3', '4', '5' etc. but i don't know what to do so that when i click on the button '2' and then the button '*' and again the button '5' and finally on the button '='; it will know how to multiply '2' with '5' and give me a result of '10' on the textfield. please, any advice from someone will be appreciated. thanks in advance.

    If it's just clicking on a button you're asking, you need to add an actionListener to each button, then in actionPerformed() you need to identify the button to determine what action to take
    e.g. if the button is 0 to 9, displayTextfield += button.getText()
    if the button is +, currentTotal += displayTextfield.getText() etc
    I have a working calculator at a website, which might give you a few ideas. A lot of the code deals with a strip list, and the order of the + - / * = keys
    e.g if I want to deduct 2 from 4, the keystrokes are 4+2- , not like small calculators 4-2=
    http://michael-dunn.freeservers.com/java/Calculator.htm

  • First individual java project, help to get started

    Hi first of let me introduce myself,
    I am Koos, 16.75 years old and from Holland. At school we are learning or suppossed to learn java language, that's how I got interested in java, anyway it isn't going that great so far.
    But I already created my first assignment a tool which counts the letters in a word, in a JFrame of course to make it look better.
    I use Eclipse to program java (what is in you opinion the best program to program in java?) and have of course installed the JDK.
    Now to get to the point, I want to contribute to a site I often visit to make a java calculation applet.
    The main Idea is to make a new window where calculations are done by multiple inputs and outputs. It's doing some simple maths such as percentage, division and multiplication.
    I would like to implement different data (different currency (Eur,Usd,Gbp) and pairs(EurChf,EurGbp GbpChf and UsdCad), and then all options possible,
    from [this tool|http://www.goforex.net/pip-calculator.htm] , could that be possible to automate or is it better to manually put in?
    I will update in an hour or so with a formula, if you would like, I already have the principal in excel so I could upload that if you'd like that.
    Regards,
    Koos

    Hi I have written the part for the window and the input fields but the fields don't show up what's wrong in the code?
    import javax.swing.*;
    public class Window extends JFrame {
         public static void main(String[] args){
              new Window();
         public Window() {
         JFrame frame = new JFrame("Fapturbo LRR calculator");
              this.setSize(500, 400);
              this.setVisible(true);
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JPanel area = new content;
              this.setContentPane(content);
              this.setVisible(true);
              this.setLocationRelativeTo(null)
    class content extends JPanel {
         private JLabel Lotsriskreduction,equity,priceEURGBP,priceEURCHF,priceUSDCAD,priceGBPCHF;
         private JButton Calculate;
         private int inputLRR,inputEQ,inputP1,inputP2,inputP3,inputP4;
         private JTextField input1;
         public content() {
              this.setLayout(null);
              input1 = new JTextField();
              this.add(input1);
              input1.setBounds(24, 80, 210, 20);
              /// Here comes the calculation folowing the formula I posted before including their outputs/
              //in the same kind of field as the input.
              Calculate = new JButton("Calculate");
              Calculation kh = new Calculation();
    }regards,
    Koos

  • Help needed with my messy calculator

    I've got a little java calculator.
    But it's a bit messy and i think it can be programmed in a more compact way.
    So, my question.
    Can anybody here change my very little and messy calculator in a very compact
    and clarifying program?
    Here's my program:
    package org.rekenmachine;
    import java.awt.*;
    import java.applet.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Rekenmachine extends JFrame {
             TextField invoervak1, invoervak2, resultaat;
             Button keer;
             double invoergetal1, invoergetal2, resultaatgetal;
    public Rekenmachine() {
        super.setLayout(new GridLayout(3,3));
        super.setSize(220,150);
        super.setBackground(Color.blue);
        super.setVisible(true); // display "this" frame
        super.setResizable(true);
    public static void main(String[] args) {
    new Rekenmachine(); // instantiate a Rekenmachine
    invoervak1 = new TextField(12);
    invoervak1.setBackground(Color.black);
    invoervak1.setForeground(Color.white);
    invoervak2 = new TextField(12);
    invoervak2.setBackground(Color.black);
    invoervak2.setForeground(Color.white);
    resultaat = new TextField(12);
    resultaat.setBackground(Color.black);
    resultaat.setText("Resultaat");
    resultaat.setForeground(Color.white);
    keer = new Button( "x" );
    keer.addActionListener( new maalHandler() );
    keer.setBounds(new Rectangle(90, 58, 100, 80));
    add(invoervak1);
    add(invoervak2);
    add(resultaat);
    add(keer);
    keer = new Button( "x" );
    keer.addActionListener( new maalHandler() );
    keer.setBounds(new Rectangle(90, 58, 100, 80));
    class maalHandler implements ActionListener
        // Als je op de maalbutton klikt wordt het antwoord van getal1 * getal2
         // weergegeven in het resultaat tekstveld
        public void actionPerformed(ActionEvent e)
            String invoer1 = invoervak1.getText();
            invoergetal1 = Double.parseDouble(invoer1); //parseDouble zet string om naar Double.
            String invoer2 = invoervak2.getText();
            invoergetal2 = Double.parseDouble(invoer2); //parseDouble zet string om naar Double.
            resultaatgetal = invoergetal1 * invoergetal2; // De berekening
            resultaat.setText("" + resultaatgetal);
    } My declarations are written in dutch. If u want i can type them in English.
    Edited by: Beuzer on Dec 15, 2008 8:20 AM

    So, can u give http://www.catb.org/~esr/faqs/smart-questions.html#writewell
    How To Ask Questions The Smart Way
    Eric Steven Raymond
    Rick Moen
    Write in clear, grammatical, correctly-spelled language
    We've found by experience that people who are careless and sloppy writers are usually also careless and sloppy at thinking and coding (often enough to bet on, anyway). Answering questions for careless and sloppy thinkers is not rewarding; we'd rather spend our time elsewhere.
    So expressing your question clearly and well is important. If you can't be bothered to do that, we can't be bothered to pay attention. Spend the extra effort to polish your language. It doesn't have to be stiff or formal ? in fact, hacker culture values informal, slangy and humorous language used with precision. But it has to be precise; there has to be some indication that you're thinking and paying attention.
    Spell, punctuate, and capitalize correctly. Don't confuse "its" with "it's", "loose" with "lose", or "discrete" with "discreet". Don't TYPE IN ALL CAPS; this is read as shouting and considered rude. (All-smalls is only slightly less annoying, as it's difficult to read. Alan Cox can get away with it, but you can't.)
    More generally, if you write like a semi-literate b o o b you will very likely be ignored. So don't use instant-messaging shortcuts. Spelling "you" as "u" makes you look like a semi-literate b o o b to save two entire keystrokes.

  • Error while running EJB Client

    Hi All,
    I have just written a program in EJB for currency conversion. But while running the client , i am getting the following error:
    C:\Java Source Code\EJB>java CalculatorClient
    java.lang.NoSuchMethodError: loadClass0
    at com.sun.corba.ee.internal.util.JDKClassLoader.specialLoadClass(Native
    Method)
    at com.sun.corba.ee.internal.util.JDKClassLoader.loadClass(JDKClassLoade
    r.java:58)
    at com.sun.corba.ee.internal.util.JDKBridge.loadClassM(JDKBridge.java:18
    0)
    at com.sun.corba.ee.internal.util.JDKBridge.loadClass(JDKBridge.java:83)
    at com.sun.corba.ee.internal.javax.rmi.CORBA.Util.loadClass(Util.java:37
    8)
    at javax.rmi.CORBA.Util.loadClass(Unknown Source)
    at javax.rmi.PortableRemoteObject.createDelegateIfSpecified(Unknown Sour
    ce)
    at javax.rmi.PortableRemoteObject.<clinit>(Unknown Source)
    at com.sun.enterprise.naming.SerialContext.getProvider(SerialContext.jav
    a:57)
    etc........
    The files that have been created are in the same folder which are as follows:
    Calculator.java Calculator.class - Remote Interface
    CalculatorHome.java CalculatorHome.class - Home Interface
    CalculatorEJB.java CalculatorEJB.class - EJB class
    ejbClient.jar - Client Jar
    ejb.ear
    The version for J2EE is 1.2.1
    Version for Jdk is 1.4.2
    Operating System - WinXP
    Could somebody pls help?
    Cooljacks

    ... but you did deploy it to an application server, right?

  • Cannot resolve symbol: class EJBObject

    Using javac I get this compile error on this file Calculator.java
    Calculator.java:1: cannot resolve symbol
    symbol : class EJBObject
    location: package ejb
    import javax.ejb.EJBObject;
    ^
    Calculator.java:5: cannot resolve symbol
    symbol : class EJBObject
    location: interface Calculator
    public interface Calculator extends EJBObject {
    Source code for Calculator.java
    import javax.ejb.EJBObject;
    import java.rmi.*;
    public interface Calculator extends EJBObject {
         public long add (int x, int y) throws RemoteException;
         public long subtract (int x, int y) throws RemoteException;

    This code is from a book, so I will assume its a classpath problem. My
    classpath looks like:
    "C\QTJava.zip".;%J2EE_HOME%\lib\j2ee.jar;%J2EE_HOME%\lib\locale
    Also the following enviorment varibales have been set to:
    J2EE_HOME
    C:\Development\Java\j2sdkee1.3.1
    JAVA_HOME
    C:\Development\Java\jdk1.3.1
    Path
    %SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;C:\Program Files\Common Files\Adaptec Shared\System;%JAVA_HOME%\bin;%J2EE_HOME%\bin
    I can run j2EE, like "j2EE -verbose" (no problems)
    also run cloudscape, like "cloudscape -start" (no problems)
    also can run deploytool, like "deploytool" (no problems, & deploy sample ear files from cd book)
    Your help is appreicated.

  • How to display String attribute in a Formatted way ?

    Hi all,
    We are using JDev 10.1.3.1, ADF BC + adf faces.
    In our database, there is a varchar column stored as : "070000001", this is a readonly attribute (updated by stored procedure).
    In jspx, we want to display it as : "07/0000001" .
    How can we do that ? (there is no hints for string attribute ?)
    Thank you for your help,
    xtanto

    you can use a SQL-calculated attribute with an appropriate SQL expression -- using SUBSTR() and string contatentation -- or you can use a java-calculated transient attribute.
    the former will allow the user to query on it. The latter wouldn't.

Maybe you are looking for

  • How to add a check box

    Hi all, How can I add a check box in a interactive report???

  • 10.1.2.0.0 on Linux , lack of "clone" directory in ORACLE_HOME middleware

    Hello everyone. I have installed OAS on Redhat enteprise Linux 4 , as installation type I have chosen MIDDLEWARE only. I'd like to clone this instance to other machine. In cloning guide I found , that I should run first prepare_clone.pl script from O

  • 1131 in autonomous mode. Not sure the below is even possible

    Hi all,   My boss asked me to try and set up an 1131 with 2 SSID's; serve dhcp for both SSID's from the AP and I cant trunk from f0 because the device the AP will connect to cant accept dot1q.  Does anyone know if this is possible?  If so pointing me

  • Traffic Light CLD Critique please

    Have at it. Go ahead be harsh. There may be some extra junk in the project I didn't clean up like some subVIs I ended up not using or elements in my cluster I didn't use, so feel free to ignore those CLA, LabVIEW Versions 2010-2013 Attachments: traff

  • Transaction SPUMG and Exception List

    Hello, I working on a Conversion Unicode project : SAP release 4.7 with BASIS 620 SP 50 It seems that SPUMG transaction was already run (at least) once and Welcome screen is no more displayed. I canu2019t upload umgexceptions xml file : Exception Lis