2

I am doing work with text field i make a program in which user type i in text field it converts into int i but the problem is when user type i it doesn't convert into int i.The Condition does not work correctly why its happening.

public class A extends JFrame{

    private JTextField entervar;
    private JButton button;
    public A(){
        getContentPane().setLayout(null);

        entervar = new JTextField();
        entervar.setToolTipText("variable must be 'i'");

        entervar.setBounds(37,26,89,28);
        getContentPane().add(entervar);


        button = new JButton("Click");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                String p = entervar.getText();

                try {
                    int i;
                    if ( p.equals("i") ) {
                        i = Integer.parseInt(p);
                    }

                }
                catch (Exception e) {

                    JOptionPane.showMessageDialog (null, "Enter Variable Must be i");

                }
            }

        });
        button.setBounds(108,121,89,28);
        getContentPane().add(button);
        setSize(400,400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    }
}

Main:

public class Main {

    public static void main(String[] args) {
        A obj = new A();

    }
}
8
  • 1
    People may be more willing to help if you make your code more readable by indenting it properly (by putting more spaces in front of the appropriate lines – see the help for details.) Commented Jun 13, 2015 at 12:24
  • Do you mean to say when a user enters i it should be converted to 1 and when a user enters ii then it should be converted to 2? Commented Jun 13, 2015 at 12:33
  • @Blip when user enter i then it convert into to int i variable Commented Jun 13, 2015 at 12:36
  • could you explain what you meant be int i variable in your previous comment? Your allow the user to enter String "i" and want it magically converted to int? Commented Jun 13, 2015 at 12:47
  • @Blip yes i really want this Commented Jun 13, 2015 at 13:00

1 Answer 1

1

p.equals("i") means user enters "i" in the text field. SO it can't be converted to number "i" is not number.

Read about JFormattedTextField. You can set NumberModel for int and get integer directly.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.