0
  JMenuItem mItem[] ={copy,paste}; 
  for(int b=0;b<mItem.length;b++)
  {
  mItem[b].addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e)
       {
        String mItemCommand = e.getActionCommand();
        JTextArea copypaste = new JTextArea(scr.getText());


        if(mItemCommand=="Copy"){
        copypaste.select(0,scr.getText().length());
        copypaste.copy();

        }

        if(mItemCommand=="Paste"){
        copypaste.setText("");
        copypaste.paste();
        String num =copypaste.getText();
        try{double n=Double.parseDouble(num);
          if(num.indexOf(".")!=-1)
           isDecimal = false;
                isFirstDigit = false;
                if( n-((long)n)>0.0)  // I just didn't understand codes starting from here
                scr.setText(""+n);
                else
                scr.setText(""+((long)n));
                if(n>=Long.MAX_VALUE || n<=Long.MIN_VALUE){

                scr.setText("0");}
                }catch(NumberFormatException ex){}
          }
4
Contributors
3
Replies
32
Views
2 Years
Discussion Span
Last Post by Taywin
0

As far as I can tell, the person who wrote this code was trying to copy a number that was represented as a String and get rid of any decimals that it had.

1

I don't know where you got that code, but it's awful.
n as name for a variable ... doesn't really tells what it is or supposed to be.

}catch(NumberFormatException ex){}

about the worst thing you can do.

indentation should be better, just to make it more readable.

if(mItemCommand=="Paste"){

(same for the "Copy" check) ... clearly written by someone who doesn't know the basics of how Strings (and other objects) should be compared in Java.

my advice: don't just copy some code you find somewhere in order to try and learn to program. chances are that it is crappy code, like the code you posted here.

1

Horrible way of checking...

if(n-((long)n)>0.0) // check if the number contains decimal places
  scr.setText(""+n); // it does, write it out as is
else
  scr.setText(""+((long)n)); // it doesn't, display w/o decimal
if(n>=Long.MAX_VALUE || n<=Long.MIN_VALUE) { // check if out of `long` range
  scr.setText("0");  // it is out of range, display 0
}

Seriously, the checking for decimal should be done when it is still in String form (before converting to a double). The code is bad both in styling (as stultuske stated) and algorithm... (i.e. The check for value of n to be within long range comes after the part that attempts to convert double to long.)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.