2 Replies Latest reply: Feb 11, 2008 9:12 AM by 807601 RSS

    calculator problem - how to check decimal point

    807601
      in a calculator, it shouldn't allow double decimal points for a number, eg, 5..7. To prevent this, i used code
      if (e.getSource()==btnDec) {
                  if (((display.getText()).indexOf("."))==-1) {
                      display.setText(display.getText()+".");
                  } 
      }
      but in this way, i can't do calculations such as 5.3+3.2, how can i get around this problem?
        • 1. Re: calculator problem - how to check decimal point
          807601
          mujingyue wrote:
          in a calculator, it shouldn't allow double decimal points for a number, eg, 5..7. To prevent this, i used code
          if (e.getSource()==btnDec) {
          if (((display.getText()).indexOf("."))==-1) {
          display.setText(display.getText()+".");
          } 
          }
          That doesn't really solve the problem you described. Actually it's not quite clear what problem that code is supposed to solve...it adds a decimal point on the end, but why bother?

          If you want to check for double decimal points, you could just do indexOf twice. Or, since you'll probably be parsing the number anyway, you could just parse it and catch any exceptions that arise from a double decimal point.

          Edited by: paulcw on Feb 10, 2008 2:53 PM
          • 2. Re: calculator problem - how to check decimal point
            807601
            mujingyue wrote:
            in a calculator, it shouldn't allow double decimal points for a number, eg, 5..7. To prevent this, i used code
            if (e.getSource()==btnDec) {
            if (((display.getText()).indexOf("."))==-1) {
            display.setText(display.getText()+".");
            } 
            }
            but in this way, i can't do calculations such as 5.3+3.2, how can i get around this problem?
            Well most calculators don't display the entire operation anyways. The user would type in 5.3, hit plus, and as soon as they hit 3, the 5.3 would disappear. So there would never be two decimal points and the code you posted is fine.

            But if you're writing a calculator that displays the entire operation, you'll need to be writing token parsing methods anyways to determine where operators are located. So, do something like read the display from left to right, and as soon as you run across an operator (+,-, etc) you create a token out of the preceeding substring. So if display.getText() is "5.3+3.2", you read until you find the "+", then make a separate String out of "5.3", and check THAT string for two decimal points.