473,772 Members | 2,513 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Calculator without a decimal point

23 New Member
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
19 4031
r035198x
13,262 MVP
Sorry Texas for the late reply. You were previously dealing with integers(withou t the decimal point).
To capture integers Integer.parseIn t was used which was adequate. When you added the decimal point, Integer.parseIn t was no longer sufficient. You now need Double.parseDou ble 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
TexasNewbie
23 New Member
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
r035198x
13,262 MVP
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
TexasNewbie
23 New Member
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
1,806 Top Contributor
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
r035198x
13,262 MVP
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
TexasNewbie
23 New Member
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
r035198x
13,262 MVP
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
TexasNewbie
23 New Member
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.set Size(200, 30);
displayText.set Location(10, 10);
pane.add(displa yText);
int x, y;
x = 10;
y = 40;
for (int ind = 0; ind < 20; ind++) {
button[ind] = new JButton(keys[ind]);
button[ind].addActionListe ner(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.addWindowL istener(new WindowAdapter() {
public void windowClosing(W indowEvent e) {
System.exit(0);
}
});

setVisible(true );
setDefaultClose Operation(EXIT_ ON_CLOSE);
}

public void actionPerformed (ActionEvent e) {
String resultStr; //Step 1
String str = String.valueOf( e.getActionComm and()); //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.set Text(numStr1);
}
else
{
numStr2 = numStr2 + ch;
displayText.set Text(numStr2);
}
break;
case '+': case '-': case '*': //Step 4b
case '/': op = ch;
firstInput = false;
break;
case '=': resultStr = evaluate(); //Step 4c
displayText.set Text(resultStr) ;
numStr1 = resultStr;
numStr2 = "";
firstInput = false;
break;
case 'C': displayText.set Text(""); //Step 4c
numStr1 = "";
numStr2 = "";
firstInput = true;
}
}

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

try
{
double num1 = Double.parseDou ble(numStr1);
double num2 = Double.parseDou ble(numStr2);
double result = 0;
if((result == Double.POSITIVE _INFINITY) || (result == Double.NEGATIVE _INFINITY))
{
System.out.prin tln("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(Arithmeti cException e)
{
System.out.prin t(beep);
return "E R R O R:" + e.getMessage();
}
catch(NumberFor matException e)
{
System.out.prin t(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.prin t(beep);
return "E R R O R";
}
}

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

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

Similar topics

4
1932
by: mwh | last post by:
Hi. If you remember, I posted Expressons Help. Now I am making a calculator with javascript. I can't get this to work: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <title>Calculator</title> <script language="Javascript"> <!-- Begin Hiding var total = 0
4
2517
by: James | last post by:
Hi all, I'm making a mini calculator for fun. My only problem is home to convert the string in the text box to a double so it can be added, subtracted, etc. I'm sure most people know how, but I'm a beginner. Many thanks. James
3
15143
by: PieMan2004 | last post by:
Hi, ive been looking for a solid java community to help me when im tearing out my hair :) Basically ive constructed a GUI that has to represent the same look and functions of the typical windows calculator. Ive made 4 classes 2 do this, my reasoning so it was easier to look through( when programming) rather than getting mixed up in my own code! My questions and problems: Ive been messing around with the windows look and feel,...
24
6341
by: firstcustomer | last post by:
Hi, Firstly, I know NOTHING about Javascript I'm afraid, so I'm hoping that someone will be able to point me to a ready-made solution to my problem! A friend of mine (honest!) is wanting to have on his site, a Javascript Calculator for working out the cost of what they want, for example: 1 widget and 2 widglets = £5.00
14
4968
by: arnuld | last post by:
Stroustrup starts chapter 6 with a programme for desk-calculator: here is a grammer for the langugae accepted by the calcualtor: program: END // END is end-of-input expr_list END expr_list: expression PRINT // PRINT is semicolon expression PRINT expr_list
3
11856
by: itsmichelle | last post by:
This is a very primative code of a java swing calculator. I have assigned all the number buttons and the operator buttons and I can add, subtract, multiply, and divide two numbers together. However, my teacher wants the operators to follow the algebraic order of operations by chaining multiple operations. Such as, 7 + 4 * 2= 15. The operatorListener is the ActionListener for the operator buttons. Thanks for any help you can give me. ...
2
1914
by: deezle | last post by:
Hello, I am trying to get my calculator GUI to +,-,* and /. I have got all of them to work except my division. I was wondering if someone could helpme figure out the problem. Any input would help and I'll leave my code in here ========================================================= package chapfour; /** * * @author Deezle */ import java.awt.*;
1
2544
by: clairelee0322 | last post by:
This program doesn't run because some problem with the reduce fraction. My reduce fraction is all right but when I tried to put that in this program, It has some errors. Or maybe the switch menu is wrong? because I put another swith menu in the main switch menu. I guess the problem is In the division - fraction section the error says something like cases are skipped by something.. I don't remember because I only get the chances to use C++...
4
9709
by: aprillynn82 | last post by:
I can not seem to get the code correct to calculate shipping charges based on weight and distance. The info is: Weight of the Package (in kilograms) / Shipping rate per Mile 2kg or less / $0.01 over 2kg, but not more than 6kg /$0.015 over 6kg, but not more than 10kg /$0.02 over 10kg, but not more than 20kg / $0.025 Input validation: Do not accept values of 0 or less for the weight of the package. Do not accept weights of more thann 20...
0
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10106
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10039
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8937
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7461
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5355
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5484
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4009
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2851
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.