1

Good evening all,

I am running into a compilation issue with some code for an introductory java class. The application at hand creates a calculator. When trying to compile, I am receiving an error stating that I have an "unreachable statement", leading me to believe I am stuck in a loop somewhere (again, I am in an introductory course, so my assumption may be wrong). I have looked over the code countless time and can't locate the issue. The compiler is pointing to line 99, keypad.add(keys[12]); // subtract, as the source of the error. I have also added "/ERROR/" to the end of this line to help point it out. Beyond assistance in locating the source of this compilation error, could you also tell me if there is any technique I should employ beyond the meticulous combing of the code to find this type of error?

import java.awt.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
import java.text.DecimalFormat;
import javax.swing.JOptionPane;

public class Calculator extends Frame implements ActionListener
{
    private Button keys[];
    private Panel keypad;
    private TextField lcd;
    private double opl;
    private boolean first;
    private boolean foundKey;
    private boolean clearText;
    private int lastOp;
    private DecimalFormat calcPattern;

    public Calculator()
    {
        // create an instance of the menu
        MenuBar mnuBar = new MenuBar();
        setMenuBar(mnuBar);

        // construct and populate the File menu
        Menu mnuFile = new Menu("File", true);
        mnuBar.add(mnuFile);
            MenuItem mnuFileExit = new MenuItem("Exit");
            mnuFile.add(mnuFileExit);

        // construct and populate the Edit menu
        Menu mnuEdit = new Menu("Edit", true);
        mnuBar.add(mnuEdit);
            MenuItem mnuEditClear = new MenuItem("Clear");
            mnuEdit.add(mnuEditClear);
            mnuEdit.insertSeparator(1);
            MenuItem mnuEditCopy = new MenuItem("Copy");
            mnuEdit.add(mnuEditCopy);
            MenuItem mnuEditPaste = new MenuItem("Paste");
            mnuEdit.add(mnuEditPaste);

        // construct and populate the About menu
        Menu mnuAbout = new Menu("About", true);
            mnuBar.add(mnuAbout);
            MenuItem mnuAboutCalculator = new MenuItem("About Calculator");
            mnuAbout.add(mnuAboutCalculator);

        // add the ActionListener to each menu item
        mnuFileExit.addActionListener(this);
        mnuEditClear.addActionListener(this);
        mnuEditCopy.addActionListener(this);
        mnuEditPaste.addActionListener(this);
        mnuAboutCalculator.addActionListener(this);

        // assign an ActionCommand to each menu item
        mnuFileExit.setActionCommand("Exit");
        mnuEditClear.setActionCommand("Clear");
        mnuEditCopy.setActionCommand("Copy");
        mnuEditPaste.setActionCommand("Paste");
        mnuAboutCalculator.setActionCommand("About");

        // constuct components and initialize beginning values
        lcd = new TextField(20);
            lcd.setEditable(false);
        keypad = new Panel();
        keys = new Button[16];
        first = true;
        opl = 0.0;
        clearText = true;
        lastOp = 0;
        calcPattern = new DecimalFormat("########.########");

        // consturct and assign captions to the Buttons
        for (int i=0; i<=9; i++)
            keys[i] = new Button(String.valueOf(i));

        keys[10] = new Button("/");
        keys[11] = new Button("*");
        keys[12] = new Button("-");
        keys[13] = new Button("+");
        keys[14] = new Button("=");
        keys[15] = new Button(".");

        // set Frame and keypad layout to grid layout
        setLayout(new BorderLayout());
        keypad.setLayout(new GridLayout(4,4,10,10));

        for (int i=7; i<=10; i++) // 7, 8, 9, divide
            keypad.add(keys[i]);

        for (int i=4; i<=6; i++) // 4, 5, 6
            keypad.add(keys[i]);

        keypad.add(keys[11]); // multiply

        for (int i=1; 1<=3; i++) // 1, 2, 3
            keypad.add(keys[i]);

        keypad.add(keys[12]); // subtract /*ERROR*/

        keypad.add(keys[0]); // 0 key

        for (int i=15; i>=13; i--) // decimal point, =, +
            keypad.add(keys[i]);

        for (int i=0; i<keys.length; i++)
            keys[i].addActionListener(this);

        add(lcd, BorderLayout.NORTH);
        add(keypad, BorderLayout.CENTER);

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

    } // end of constructor method

    public void actionPerformed(ActionEvent e)
    {
        // test for menu item clicks
        String arg = e.getActionCommand();
        if (arg == "Exit")
            System.exit(0);

        if (arg == "Clear")
        {
            clearText = true;
            first = true;
            opl = 0.0;
            lcd.setText("");
            lcd.requestFocus();
        }

        if (arg == "Copy")
        {
            Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
            StringSelection contents = new StringSelection(lcd.getText());
            cb.setContents(contents, null);
        }

        if (arg == "Paste")
        {
            Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
            Transferable content = cb.getContents(this);
            try
            {
                String s = (String)content.getTransferData(DataFlavor.stringFlavor);
                lcd.setText(calcPattern.format(Double.parseDouble(s)));
            }
            catch (Throwable exc)
            {
                lcd.setText("");
            }
        }

        if (arg == "About")
        {
            String message = "Calculator ver.1.0\nOpenExhibit Softwar\nCopyright 2007\nAll rights Reserved";
            JOptionPane.showMessageDialog(null,message,"About Calculator", JOptionPane.INFORMATION_MESSAGE);
        }

        // test for button clicks
        foundKey = false;

        // search for the clicked key
        for (int i=0; i<keys.length && !foundKey; i++)
        {
            if(e.getSource() == keys[i])
            {
                foundKey = true;
                switch(i)
                {
                    // number and decimal point buttons
                    case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 15:
                    if(clearText)
                    {
                        lcd.setText("");
                        clearText = false;
                    }
                    lcd.setText(lcd.getText() + keys[i].getLabel());
                    break;

                    // operator buttons
                    case 10: case 11: case 12: case 13: case 14:
                        clearText = true;

                        if (first) // first operand
                        {
                            if(lcd.getText().length()==0) opl = 0.0;
                            else opl = Double.parseDouble(lcd.getText());

                            first = false;
                            clearText = true;
                            lastOp = i; // save the last operator
                        }
                        else // second operand
                        {
                            switch(lastOp)
                            {
                                case 10: // divide button
                                    opl /= Double.parseDouble(lcd.getText());
                                    break;
                                case 11: // multiply button
                                    opl *= Double.parseDouble(lcd.getText());
                                    break;
                                case 12: // minus button
                                    opl -= Double.parseDouble(lcd.getText());
                                    break;
                                case 13: // plus button
                                    opl += Double.parseDouble(lcd.getText());
                                    break;
                            } // end of switch(lastOp)
                            lcd.setText(calcPattern.format(opl));
                            clearText = true;

                            if(i==14) first = true; // equal button
                            else lastOp = i; // save last operator
                        } // end else
                        break;
                } // end of switch(i)
            } // end of if
        } // end of for
    } // end of actionPerformed

    public static void main(String args[])
    {
        // set frame properties
        Calculator f = new Calculator ();
        f.setTitle("Calculator Application");
        f.setBounds(200,200,300,300);
        f.setVisible(true);

        // set image properties and add to frame
        Image icon = Toolkit.getDefaultToolkit().getImage("calcImage.gif");
        f.setIconImage(icon);

    } // end of main
} // end of class

As always, thanks for the help.

Jerry

Jerry
  • 61
  • 1
  • 5
  • I would suggest that you create a Swing GUI, not an AWT. Also you cannot compare Strings via `==`. Use the `equals(...)` or `equalsIgnoreCase(...)` method instead. i.e., instead of `if (arg == "Clear")` do `if (arg.equalsIgnoreCase("Clear"))`. – Hovercraft Full Of Eels Oct 20 '13 at 23:42
  • @HovercraftFullOfEels thanks for the input. I will try to keep that in mind for future use. With that being said, I am required to create applications a very specific way for this class to best enable me to see and use a wide spectrum of different packages, techniques, etc. – Jerry Oct 20 '13 at 23:57
  • ?? Please clarify the requirements. Is this for school? Are you absolutely required to use AWT and not Swing? If not do you feel that there are things that AWT allow you to do and not Swing? As for my other recommendation about Strings, you'd better change your current code or it will likely not work. – Hovercraft Full Of Eels Oct 21 '13 at 00:00
  • @HovercraftFullOfEels The code worked fine as written. Regarding the requirements, this is for school. And yes, for this particular lab, I am required to use AWT over Swing. Moreover, the text we use has the specific code we are to use to develop the application. Granted, it is not always the best way to do it, but it is a good way to introduce me to the various techniques I can use. Once my lab is complete, my instructor will run my code and the "correct" code (per the textbook) through a comparative tool to ensure they match. That leaves me with essentially no flexibility for efficiency. – Jerry Oct 21 '13 at 00:12
  • Thanks for the information. Then of course you will need to follow the requirements, thought it does make me question the judgement of your instructors. Good luck! – Hovercraft Full Of Eels Oct 21 '13 at 00:17

2 Answers2

2

There is a small typo in the loop just before that statement. See if you can spot it:

for (int i=1; 1<=3; i++) // 1, 2, 3
    keypad.add(keys[i]);

Your test is 1<=3, which is always true, because 1 is always less than or equal to 3. I think what you meant is:

for (int i=1, i<3; i++)
    keypad.add(keys[i]);
tbodt
  • 16,609
  • 6
  • 58
  • 83
  • Correct. I noticed it immediately after posting and tried to post an answer before anyone spent too much time on it. As soon as SO allows me, I'll mark you answer as correct. Thanks for your time! – Jerry Oct 20 '13 at 23:41
0

The moment I posted the question, I saw my issue. In the lines just prior to my issue, I had typed:

for (int i=1; 1<=3; i++) // 1, 2, 3
            keypad.add(keys[i]);

when I had meant to type:

for (int i=1; i<=3; i++) // 1, 2, 3
            keypad.add(keys[i]);

1<=3 and i<=3 clearly aren't the same.

Thanks again.

Jerry
  • 61
  • 1
  • 5