By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,034 Members | 822 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,034 IT Pros & Developers. It's quick & easy.

Calculator without a decimal point

P: 23
This was originally just a calculator without a decimal point. After I added the decimal, it now tells me invalid second number.


Expand|Select|Wrap|Line Numbers
  1. //GUI Calculator Program
  2.  
  3. import javax.swing.*;
  4. import java.awt.*;
  5. import java.awt.event.*;
  6. import java.io.*;
  7.  
  8. public class Calculator extends JFrame implements ActionListener
  9. {
  10.     private JTextField displayText = new JTextField(30);
  11.     private JButton[] button = new JButton[20];
  12.  
  13.     private String[] keys = {"7", "8", "9", "/",
  14.                             "4", "5", "6", "*",
  15.                             "1", "2", "3", "-",
  16.                             "0", "C", "=", "+",
  17.                 ".", " ", " ", " "};
  18.  
  19.     private String numStr1 = "";
  20.     private String numStr2 = "";
  21.  
  22.     private char op;
  23.     private boolean firstInput = true;
  24.  
  25.     public Calculator()
  26.     {
  27.         setTitle("My Calculator");
  28.         setSize(230, 250);
  29.         Container pane = getContentPane();
  30.  
  31.         pane.setLayout(null);
  32.  
  33.         displayText.setSize(200, 30);
  34.         displayText.setLocation(10, 10);
  35.         pane.add(displayText);
  36.  
  37.         int x, y;
  38.  
  39.         x = 10;
  40.         y = 40;
  41.         for (int ind = 0; ind < 20; ind++)
  42.         {
  43.             button[ind] = new JButton(keys[ind]);
  44.             button[ind].addActionListener(this);
  45.             button[ind].setSize(50, 30);
  46.             button[ind].setLocation(x, y);
  47.             pane.add(button[ind]);
  48.             x = x + 50;
  49.             if((ind + 1) % 4 == 0)
  50.             {
  51.                 x = 10;
  52.                 y = y + 30;
  53.             }
  54.         }
  55.  
  56.         this.addWindowListener(new WindowAdapter()
  57.                       {
  58.                            public void windowClosing(WindowEvent e)
  59.                            {
  60.                                 System.exit(0);
  61.                            }
  62.                     }
  63.         );
  64.  
  65.         setVisible(true);
  66.         setDefaultCloseOperation(EXIT_ON_CLOSE);
  67.     }
  68.  
  69.     public void actionPerformed(ActionEvent e)
  70.     {
  71.         String resultStr;                                   //Step 1
  72.         String str = String.valueOf(e.getActionCommand());  //Steps 1 and 2
  73.  
  74.         char ch = str.charAt(0);                            //Steps 1 and 3
  75.  
  76.         switch (ch)                                          //Step 4
  77.         {
  78.         case '0': case '1': case '2':                       //Step 4a
  79.         case '3': case '4': case '5':
  80.         case '6': case '7': case '8':
  81.         case '9': case '.':if (firstInput)
  82.                   {
  83.                      numStr1 = numStr1 + ch;
  84.                      displayText.setText(numStr1);
  85.                   }
  86.                   else
  87.                   {
  88.                       numStr2 = numStr2 + ch;
  89.                       displayText.setText(numStr2);
  90.                   }
  91.                   break;
  92.         case '+': case '-': case '*':                       //Step 4b
  93.         case '/': op = ch;
  94.                   firstInput = false;
  95.                   break;
  96.         case '=': resultStr = evaluate();                   //Step 4c
  97.                   displayText.setText(resultStr);
  98.                   numStr1 = resultStr;
  99.                   numStr2 = "";
  100.                   firstInput = false;
  101.                   break;
  102.         case 'C': displayText.setText("");                  //Step 4c
  103.                   numStr1 = "";
  104.                   numStr2 = "";
  105.                   firstInput = true;
  106.         }
  107.     }
  108.  
  109.     private String evaluate()
  110.     {
  111.         final char beep = '\u0007';
  112.  
  113.         try
  114.         {
  115.             int num1 = Integer.parseInt(numStr1);
  116.             int num2 = Integer.parseInt(numStr2);
  117.             int result = 0;
  118.  
  119.             switch (op)
  120.             {
  121.             case '+': result = num1 + num2;
  122.                       break;
  123.             case '-': result = num1 - num2;
  124.                       break;
  125.             case '*': result = num1 * num2;
  126.                       break;
  127.             case '/': result = num1 / num2;
  128.             }
  129.  
  130.             return String.valueOf(result);
  131.         }
  132.         catch(ArithmeticException e)
  133.         {
  134.             System.out.print(beep);
  135.             return "E R R O R: " + e.getMessage();
  136.         }
  137.         catch(NumberFormatException e)
  138.         {
  139.             System.out.print(beep);
  140.             if (numStr1.equals(""))
  141.                return "E R R O R: Invalid First Number" ;
  142.             else
  143.                return "E R R O R: Invalid Second Number" ;
  144.         }
  145.         catch(Exception e)
  146.         {
  147.             System.out.print(beep);
  148.             return "E R R O R";
  149.         }
  150.     }
  151.  
  152.     public static void main(String[] args)
  153.     {
  154.         Calculator C = new Calculator();
  155.     }
  156. }



Please Help
Jan 22 '07 #1
Share this Question
Share on Google+
19 Replies


10K+
P: 13,264
Sorry Texas for the late reply. You were previously dealing with integers(without the decimal point).
To capture integers Integer.parseInt was used which was adequate. When you added the decimal point, Integer.parseInt was no longer sufficient. You now need Double.parseDouble and change your variables from int type to double type. I have made these changes below.


Expand|Select|Wrap|Line Numbers
  1. import javax.swing.*;
  2. import java.awt.*;
  3. import java.awt.event.*;
  4. import java.io.*;
  5.  
  6. public class Calculator extends JFrame implements ActionListener {
  7.     private JTextField displayText = new JTextField(30);
  8.     private JButton[] button = new JButton[20];
  9.     private String[] keys = {"7", "8", "9", "/",
  10.                             "4", "5", "6", "*",
  11.                             "1", "2", "3", "-",
  12.                             "0", "C", "=", "+",
  13.                 ".", " ", " ", " "};
  14.     private String numStr1 = "";
  15.     private String numStr2 = "";
  16.     private char op;
  17.     private boolean firstInput = true;
  18.     public Calculator() {
  19.         setTitle("My Calculator");
  20.         setSize(230, 250);
  21.         Container pane = getContentPane();
  22.         pane.setLayout(null);
  23.         displayText.setSize(200, 30);
  24.         displayText.setLocation(10, 10);
  25.         pane.add(displayText);
  26.         int x, y;
  27.         x = 10;
  28.         y = 40;
  29.         for (int ind = 0; ind < 20; ind++) {
  30.             button[ind] = new JButton(keys[ind]);
  31.             button[ind].addActionListener(this);
  32.             button[ind].setSize(50, 30);
  33.             button[ind].setLocation(x, y);
  34.             pane.add(button[ind]);
  35.             x = x + 50;
  36.             if((ind + 1) % 4 == 0) {
  37.                 x = 10;
  38.                 y = y + 30;
  39.             }
  40.         }
  41.  
  42.         this.addWindowListener(new WindowAdapter() {
  43.             public void windowClosing(WindowEvent e) {
  44.                 System.exit(0);
  45.             }
  46.         });
  47.  
  48.         setVisible(true);
  49.         setDefaultCloseOperation(EXIT_ON_CLOSE);
  50.     }
  51.  
  52.     public void actionPerformed(ActionEvent e) {
  53.         String resultStr;                                   //Step 1
  54.         String str = String.valueOf(e.getActionCommand());  //Steps 1 and 2
  55.         char ch = str.charAt(0);                            //Steps 1 and 3
  56.         switch (ch)                                          //Step 4
  57.         {
  58.         case '0': case '1': case '2':                       //Step 4a
  59.         case '3': case '4': case '5':
  60.         case '6': case '7': case '8':
  61.         case '9': case '.':if (firstInput)
  62.                   {
  63.                      numStr1 = numStr1 + ch;
  64.                      displayText.setText(numStr1);
  65.                   }
  66.                   else
  67.                   {
  68.                       numStr2 = numStr2 + ch;
  69.                       displayText.setText(numStr2);
  70.                   }
  71.                   break;
  72.         case '+': case '-': case '*':                       //Step 4b
  73.         case '/': op = ch;
  74.                   firstInput = false;
  75.                   break;
  76.         case '=': resultStr = evaluate();                   //Step 4c
  77.                   displayText.setText(resultStr);
  78.                   numStr1 = resultStr;
  79.                   numStr2 = "";
  80.                   firstInput = false;
  81.                   break;
  82.         case 'C': displayText.setText("");                  //Step 4c
  83.                   numStr1 = "";
  84.                   numStr2 = "";
  85.                   firstInput = true;
  86.         }
  87.     }
  88.  
  89.     private String evaluate()
  90.     {
  91.         final char beep = '\u0007';
  92.  
  93.         try
  94.         {
  95.             double num1 = Double.parseDouble(numStr1);// Changed here
  96.             double num2 = Double.parseDouble(numStr2);//
  97.             double result = 0;
  98.  
  99.             switch (op)
  100.             {
  101.             case '+': result = num1 + num2;
  102.                       break;
  103.             case '-': result = num1 - num2;
  104.                       break;
  105.             case '*': result = num1 * num2;
  106.                       break;
  107.             case '/': result = num1 / num2;
  108.             }
  109.  
  110.             return String.valueOf(result);
  111.         }
  112.         catch(ArithmeticException e)
  113.         {
  114.             System.out.print(beep);
  115.             return "E R R O R: " + e.getMessage();
  116.         }
  117.         catch(NumberFormatException e)
  118.         {
  119.             System.out.print(beep);
  120.             if (numStr1.equals(""))
  121.                return "E R R O R: Invalid First Number" ;
  122.             else
  123.                return "E R R O R: Invalid Second Number" ;
  124.         }
  125.         catch(Exception e)
  126.         {
  127.             System.out.print(beep);
  128.             return "E R R O R";
  129.         }
  130.     }
  131.  
  132.     public static void main(String[] args)
  133.     {
  134.         Calculator C = new Calculator();
  135.     }
  136. }
Jan 23 '07 #2

P: 23
I cant believe that it was something that I overlooked. A special thanks to r035198x, for not only looking over the code, but for helping me out.
Jan 23 '07 #3

10K+
P: 13,264
I cant believe that it was something that I overlooked. A special thanks to r035198x, for not only looking over the code, but for helping me out.
Just post any Java problems you get anytime. The guys here are always willing to help.
Jan 23 '07 #4

P: 23
further problem now I am getting infinity if I divide by zero. The exception should have caught it and given it an error : / by zero. Now, what have I forgotten?
Jan 24 '07 #5

DeMan
100+
P: 1,806
In your evaluate() method, if the op is division, you should check that num2 != 0.0 (the program does not do this check for you because it is not an invalid number on parsing). you can do something like:

Expand|Select|Wrap|Line Numbers
  1. if(num2 == 0.0)
  2. {
  3.   throw new ArithmeticException("Can't Divide by 0");
  4. }
  5.  
Jan 24 '07 #6

10K+
P: 13,264
further problem now I am getting infinity if I divide by zero. The exception should have caught it and given it an error : / by zero. Now, what have I forgotten?
Tricky one for you this.

Now dividing by (double) 0.0 does not cause an exception. The result is simply Infinity. This is because double are approximations and not exact values so 0.0 is a number as close to zero as possible....

Dividing by (int) 0 is the one that throws the / by zero exception.
Jan 25 '07 #7

P: 23
Tricky one for you this.

Now dividing by (double) 0.0 does not cause an exception. The result is simply Infinity. This is because double are approximations and not exact values so 0.0 is a number as close to zero as possible....

Dividing by (int) 0 is the one that throws the / by zero exception.
Now I'm really confused as to were I would insert the Dividing by (int) 0 or were I would put the throw exception to make this happen? I have tried install it in several places in the code and all I get is error after error. I'm really lost here!
Jan 25 '07 #8

10K+
P: 13,264
Now I'm really confused as to were I would insert the Dividing by (int) 0 or were I would put the throw exception to make this happen? I have tried install it in several places in the code and all I get is error after error. I'm really lost here!
Expand|Select|Wrap|Line Numbers
  1. double num1 = Double.parseDouble(numStr1);// Changed here
  2. double num2 = Double.parseDouble(numStr2);//
  3. double result = 0;
These lines of code guarantee that you are never going to get a / by zero exception because you are now operating on doubles which give Infinity on / by zero rather than on ints which give that exception.

If you want to stop the program from getting infinity as a result then test the result with

Expand|Select|Wrap|Line Numbers
  1. if((result == Double.POSITIVE_INFINITY) || (result == Double.NEGATIVE_INFINITY)) {
  2.         System.out.println("error");
  3. e.t.c
  4. }
Jan 25 '07 #9

P: 23
Okay, I put the statement were thought it should go but it still comes up infinity, any other hints clues suggestions? Or am I just an idiot? See below


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class Calculator extends JFrame implements ActionListener {
private JTextField displayText = new JTextField(30);
private JButton[] button = new JButton[20];
private String[] keys = {"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", "C", "=", "+",
".", " ", " ", " "};
private String numStr1 = "";
private String numStr2 = "";
private char op;
private boolean firstInput = true;
public Calculator() {
setTitle("My Calculator");
setSize(230, 250);
Container pane = getContentPane();
pane.setLayout(null);
displayText.setSize(200, 30);
displayText.setLocation(10, 10);
pane.add(displayText);
int x, y;
x = 10;
y = 40;
for (int ind = 0; ind < 20; ind++) {
button[ind] = new JButton(keys[ind]);
button[ind].addActionListener(this);
button[ind].setSize(50, 30);
button[ind].setLocation(x, y);
pane.add(button[ind]);
x = x + 50;
if((ind + 1) % 4 == 0) {
x = 10;
y = y + 30;
}
}

this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});

setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public void actionPerformed(ActionEvent e) {
String resultStr; //Step 1
String str = String.valueOf(e.getActionCommand()); //Steps 1 and 2
char ch = str.charAt(0); //Steps 1 and 3
switch (ch) //Step 4
{
case '0': case '1': case '2': //Step 4a
case '3': case '4': case '5':
case '6': case '7': case '8':
case '9': case '.':if (firstInput)
{
numStr1 = numStr1 + ch;
displayText.setText(numStr1);
}
else
{
numStr2 = numStr2 + ch;
displayText.setText(numStr2);
}
break;
case '+': case '-': case '*': //Step 4b
case '/': op = ch;
firstInput = false;
break;
case '=': resultStr = evaluate(); //Step 4c
displayText.setText(resultStr);
numStr1 = resultStr;
numStr2 = "";
firstInput = false;
break;
case 'C': displayText.setText(""); //Step 4c
numStr1 = "";
numStr2 = "";
firstInput = true;
}
}

private String evaluate()
{
final char beep = '\u0007';

try
{
double num1 = Double.parseDouble(numStr1);
double num2 = Double.parseDouble(numStr2);
double result = 0;
if((result == Double.POSITIVE_INFINITY) || (result == Double.NEGATIVE_INFINITY))
{
System.out.println("error");

}
switch (op)
{
case '+': result = num1 + num2;
break;
case '-': result = num1 - num2;
break;
case '*': result = num1 * num2;
break;
case '/': result = num1 / num2;
}

return String.valueOf(result);
}
catch(ArithmeticException e)
{
System.out.print(beep);
return "E R R O R:" + e.getMessage();
}
catch(NumberFormatException e)
{
System.out.print(beep);
if (numStr1.equals(""))
return "E R R O R: Invalid First Number" ;
else
return "E R R O R: Invalid Second Number" ;
}
catch(Exception e)
{
System.out.print(beep);
return "E R R O R";
}
}

public static void main(String[] args)
{
Calculator C = new Calculator();
}
}
Jan 25 '07 #10

10K+
P: 13,264
Makes sense to put it after the result is calculated
Expand|Select|Wrap|Line Numbers
  1. switch (op)
  2.             {
  3.             case '+': result = num1 + num2;
  4.                       break;
  5.             case '-': result = num1 - num2;
  6.                       break;
  7.             case '*': result = num1 * num2;
  8.                       break;
  9.             case '/': result = num1 / num2;
  10.             }
  11. }
  12. if((result == Double.POSITIVE_INFINITY) || (result == Double.NEGATIVE_INFINITY))
  13. {
  14. System.out.println("error");
  15. return "E R R O R:" 
  16. }
  17. else {
  18.        return String.valueOf(result);
  19. }
  20.         }
  21.         catch(ArithmeticException e)
  22.         {
  23.             System.out.print(beep);    
  24.             + e.getMessage();
  25.     }
P.S Use code tags for posting code
Jan 25 '07 #11

P: 23
private String evaluate()
{
final char beep = '\u0007';

try
{
double num1 = Double.parseDouble(numStr1);
double num2 = Double.parseDouble(numStr2);
double result = 0;

switch (op)
{
case '+': result = num1 + num2;
break;
case '-': result = num1 - num2;
break;
case '*': result = num1 * num2;
break;
case '/': result = num1 / num2;
}
if ((result == Double.POSITIVE_INFINITY) || (result == Double.NEGATIVE_INFINITY))
{
System.out.print(beep);
return "E R R O R:";
}
else
return String.valueOf(result);
}
catch(ArithmeticException e)
{
System.out.print(beep);
}
catch(NumberFormatException e)
{
System.out.print(beep);
if (numStr1.equals(""))
return "E R R O R: Invalid First Number" ;
else
return "E R R O R: Invalid Second Number" ;
}
catch(Exception e)
{
System.out.print(beep);
return "E R R O R";
}
finally
{
Calculator C = new Calculator();
}
} //line 153 this is the close for try
//line 154
} //line 155 this is te close for privat string

Okay, I am about as frustrated with this thing as I can be. I went back to the book thinking that there had to be a finally statement, but that didn't work I keep getting a missing return statement on line 153
Jan 25 '07 #12

DeMan
100+
P: 1,806
I Don't remember exactly how exceptions work, but I think your "finally" block is incorrect - can the code ever get here? (I think the compiler expects you to return a value here, which would be a fix, but I think the code will never reach this point so you should delete it).

Basically the "finally" is executed irrespective of which exception is thrown, but all of your exceptions have a return line which will stop execution of that method before it gets to finally.....
Jan 25 '07 #13

Ganon11
Expert 2.5K+
P: 3,652
Expand|Select|Wrap|Line Numbers
  1.         catch(ArithmeticException e)
  2.           {
  3.           System.out.print(beep);    
  4.           }
This catch() block has no return statement, so it is possible that there will not be a return - this is why you get an error. Perhaps you should add the line

Expand|Select|Wrap|Line Numbers
  1. return "E R R O R";
as you have in other blocks.
Jan 25 '07 #14

P: 23
I would like to thank everyone for thier input and let you know that I have resolved all issues with this project. New one to come soon. Expect to hear more from me. Thanks again.
Jan 26 '07 #15

10K+
P: 13,264
I would like to thank everyone for thier input and let you know that I have resolved all issues with this project. New one to come soon. Expect to hear more from me. Thanks again.
Mind postin the final version you ended up with?
Jan 26 '07 #16

P: 23
Final code:

Expand|Select|Wrap|Line Numbers
  1. /**
  2. *  Description: This takes the original calculator program that could be used 
  3. *  on integers and converts it to be able to use decimal numbers. Division by 
  4. *  zero creates error resulting in ERROR: / by zero.
  5. */
  6. import javax.swing.*;
  7. import java.awt.*;
  8. import java.awt.event.*;
  9. import java.io.*;
  10.  
  11. public class Calculator extends JFrame implements ActionListener
  12.  {
  13.     private JTextField displayText = new JTextField(30);
  14.     private JButton[] button = new JButton[20];
  15.     private String[] keys =
  16.                            {"7", "8", "9", "/",
  17.                             "4", "5", "6", "*",
  18.                             "1", "2", "3", "-",
  19.                             "0", "C", "=", "+",
  20.                 ".", " ", " ", " "};
  21.     private String numStr1 = "";
  22.     private String numStr2 = "";
  23.     private char op;
  24.     private boolean firstInput = true;
  25.     public Calculator()
  26.      {
  27.         setTitle("My Calculator");
  28.         setSize(230, 250);
  29.         Container pane = getContentPane();
  30.         pane.setLayout(null);
  31.         displayText.setSize(200, 30);
  32.         displayText.setLocation(10, 10);
  33.         pane.add(displayText);
  34.         int x, y;
  35.         x = 10;
  36.         y = 40;
  37.         for (int ind = 0; ind < 20; ind++)
  38.        {
  39.             button[ind] = new JButton(keys[ind]);
  40.             button[ind].addActionListener(this);
  41.             button[ind].setSize(50, 30);
  42.             button[ind].setLocation(x, y);
  43.             pane.add(button[ind]);
  44.             x = x + 50;
  45.             if((ind + 1) % 4 == 0) {
  46.                 x = 10;
  47.                 y = y + 30;
  48.             }
  49.         }
  50.  
  51.         this.addWindowListener(new WindowAdapter() 
  52.             {
  53.      public void windowClosing(WindowEvent e)
  54.                     {
  55.                 System.exit(0);
  56.                     }
  57.             });
  58.  
  59.         setVisible(true);
  60.         setDefaultCloseOperation(EXIT_ON_CLOSE);
  61.     }
  62.  
  63.    public void actionPerformed(ActionEvent e)
  64.    {
  65.         String resultStr;                                   //Step 1
  66.         String str = String.valueOf(e.getActionCommand());  //Steps 1 and 2
  67.         char ch = str.charAt(0);                            //Steps 1 and 3
  68.         switch (ch)                                          //Step 4
  69.       {
  70.         case '0': case '1': case '2':                       //Step 4a
  71.         case '3': case '4': case '5':
  72.         case '6': case '7': case '8':
  73.         case '9': case '.':if (firstInput)
  74.                   {
  75.                   numStr1 = numStr1 + ch;
  76.                   displayText.setText(numStr1);
  77.                   }
  78.                  else
  79.                   {
  80.                   numStr2 = numStr2 + ch;
  81.                   displayText.setText(numStr2);
  82.                   }
  83.                   break;
  84.         case '+': case '-': case '*':                       //Step 4b
  85.         case '/': op = ch;
  86.                   firstInput = false;
  87.                   break;
  88.         case '=': resultStr = evaluate();                   //Step 4c
  89.                   displayText.setText(resultStr);
  90.                   numStr1 = resultStr;
  91.                   numStr2 = "";
  92.                   firstInput = false;
  93.                   break;
  94.         case 'C': displayText.setText("");                  //Step 4c
  95.                   numStr1 = "";
  96.                   numStr2 = "";
  97.                   firstInput = true;
  98.       }
  99.     }
  100.  
  101.     private String evaluate()
  102.     {
  103.         final char beep = '\u0007';
  104.  
  105.         try
  106.         {
  107.             double num1 = Double.parseDouble(numStr1);
  108.             double num2 = Double.parseDouble(numStr2);
  109.             double result = 0;
  110.  
  111.             switch (op)
  112.                {
  113.                case '+': result = num1 + num2;
  114.                       break;
  115.                case '-': result = num1 - num2;
  116.                       break;
  117.                case '*': result = num1 * num2;
  118.                       break;
  119.                case '/': result = num1 / num2;
  120.                }
  121.     if ((result == Double.POSITIVE_INFINITY) || (result == Double.NEGATIVE_INFINITY))
  122.       {
  123.       System.out.print(beep);
  124.       return "E R R O R: / by zero";
  125.       }
  126.         else
  127.       return String.valueOf(result);
  128.       }
  129.         catch(ArithmeticException e)
  130.           {
  131.           System.out.print(beep);
  132.       return "E R R O R:";    
  133.           }
  134.         catch(NumberFormatException e)
  135.           {
  136.           System.out.print(beep);
  137.           if (numStr1.equals(""))
  138.           return "E R R O R: Invalid First Number" ;
  139.             else
  140.           return "E R R O R: Invalid Second Number" ;
  141.           }
  142.         catch(Exception e)
  143.           {
  144.           System.out.print(beep);
  145.           return "E R R O R";
  146.           }
  147.     }
  148.        public static void main(String[] args)
  149.     {
  150.         Calculator C = new Calculator();
  151.     }
  152.  
  153.       }
Jan 26 '07 #17

10K+
P: 13,264
Final code:

/**
* Description: This takes the original calculator program that could be used
* on integers and converts it to be able to use decimal numbers. Division by
* zero creates error resulting in ERROR: / by zero.
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class Calculator extends JFrame implements ActionListener
{
private JTextField displayText = new JTextField(30);
private JButton[] button = new JButton[20];
private String[] keys =
{"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", "C", "=", "+",
".", " ", " ", " "};
private String numStr1 = "";
private String numStr2 = "";
private char op;
private boolean firstInput = true;
public Calculator()
{
setTitle("My Calculator");
setSize(230, 250);
Container pane = getContentPane();
pane.setLayout(null);
displayText.setSize(200, 30);
displayText.setLocation(10, 10);
pane.add(displayText);
int x, y;
x = 10;
y = 40;
for (int ind = 0; ind < 20; ind++)
{
button[ind] = new JButton(keys[ind]);
button[ind].addActionListener(this);
button[ind].setSize(50, 30);
button[ind].setLocation(x, y);
pane.add(button[ind]);
x = x + 50;
if((ind + 1) % 4 == 0) {
x = 10;
y = y + 30;
}
}

this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});

setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public void actionPerformed(ActionEvent e)
{
String resultStr; //Step 1
String str = String.valueOf(e.getActionCommand()); //Steps 1 and 2
char ch = str.charAt(0); //Steps 1 and 3
switch (ch) //Step 4
{
case '0': case '1': case '2': //Step 4a
case '3': case '4': case '5':
case '6': case '7': case '8':
case '9': case '.':if (firstInput)
{
numStr1 = numStr1 + ch;
displayText.setText(numStr1);
}
else
{
numStr2 = numStr2 + ch;
displayText.setText(numStr2);
}
break;
case '+': case '-': case '*': //Step 4b
case '/': op = ch;
firstInput = false;
break;
case '=': resultStr = evaluate(); //Step 4c
displayText.setText(resultStr);
numStr1 = resultStr;
numStr2 = "";
firstInput = false;
break;
case 'C': displayText.setText(""); //Step 4c
numStr1 = "";
numStr2 = "";
firstInput = true;
}
}

private String evaluate()
{
final char beep = '\u0007';

try
{
double num1 = Double.parseDouble(numStr1);
double num2 = Double.parseDouble(numStr2);
double result = 0;

switch (op)
{
case '+': result = num1 + num2;
break;
case '-': result = num1 - num2;
break;
case '*': result = num1 * num2;
break;
case '/': result = num1 / num2;
}
if ((result == Double.POSITIVE_INFINITY) || (result == Double.NEGATIVE_INFINITY))
{
System.out.print(beep);
return "E R R O R: / by zero";
}
else
return String.valueOf(result);
}
catch(ArithmeticException e)
{
System.out.print(beep);
return "E R R O R:";
}
catch(NumberFormatException e)
{
System.out.print(beep);
if (numStr1.equals(""))
return "E R R O R: Invalid First Number" ;
else
return "E R R O R: Invalid Second Number" ;
}
catch(Exception e)
{
System.out.print(beep);
return "E R R O R";
}
}
public static void main(String[] args)
{
Calculator C = new Calculator();
}

}
Might want to work on indenting your code and making use of {} to make your code readable.
Jan 26 '07 #18

P: 23
On the actual code that I have on my system it is all indented, but when I copied it over this is what happened. Again thanks for your help.
Jan 26 '07 #19

10K+
P: 13,264
On the actual code that I have on my system it is all indented, but when I copied it over this is what happened. Again thanks for your help.
Try editing the display options on your control panel some where at the bottom of the control panel page.
Jan 29 '07 #20

Post your reply

Sign in to post your reply or Sign up for a free account.