Start New Discussion within our Software Development Community

i want to make a calculator in which a user allowed to input two numbers in text fieldand on pressing the particular operation button the operation performed.but how could i restrict user to input only numbers and no strings ??

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class calsc extends Applet implements ActionListener{
Button blist[] = new Button[4];
Label l1;
TextField one,two;
String msg="";

//Initialize the applet
public void init() {   
l1 = new Label ("input only numbers");
Button first = new Button ("+");
Button second = new Button ("-");
Button third = new Button ("/");
Button fourth = new Button ("*");
one = new TextField ("Enter 1st value")
two = new TextField ("Enter 2nd value")
add (l1);
blist[0] = (Button) add(first);
blist[1] = (Button) add(second);
blist[2] = (Button) add(third);
blist[3] = (Button) add(fourth);

for (int i=0;i<4;i++){
public void actionPerformed(ActionEvent ae) {
  if (ae.getSource==blist[0]){
    msg = "" + one.getText()+two.getText();
else  if (ae.getSource==blist[1]){
    msg = "" + one.getText()-two.getText();

else if (ae.getSource==blist[2]){
    msg = "" + one.getText()/two.getText();
    msg = "" + one.getText()*two.getText();

public void paint (Graphic g){
g.drawString (msg,6,100);

is my calculator OK ??
i am allowed to use only text fields, buttons and labels.

if you did a try and catch method of parseing the label text to an integer.

so that if it works it performs the operation else it returns a message to the user saying "this is not a number please input numbers only"

sudo code

one = integer.parse(label.gettext())
two = integer.parse(label2.gettext())

do calculation
error message

This article has been dead for over six months. Start a new discussion instead.