Matt Herbstritt
Matt Herbstritt

Reputation: 4862

IF statement inside ActionPerformed method in JAVA

I'm trying to build a basic game where the user's knowledge of State capitals is tested. At this stage I'm just trying to set up some basic functionality for the buttons.

I'm trying to get it so that when the user types in a string which corresponds to a correct answer the program displays "correct!". I've tried using an IF ELSE statement but even when I type in the right answer it outputs "WRONG!". It's probably something simple but I can't spot it. If someone could point me in the right direction that would be much appreciated. I'm very much a beginner so perhaps this completely the wrong way to go about it but here is what I have so far:

public class Main {

    public static void main(String[] args){

        Gui a = new Gui();

    }

}

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Gui extends JFrame{
    private static final long serialVersionUID = 1L;

        JPanel row1 = new JPanel();
        JLabel instructions = new JLabel("What is the capital of Alabama?");

        JPanel row2 = new JPanel();
        JLabel aLabel = new JLabel("Answer: ");
        JTextField aField = new JTextField(14);

        JPanel row3 = new JPanel();
        JButton submit = new JButton("Submit");
        JButton reset = new JButton("Reset");

    public Gui() {

        super("State Capitals Game");
        setLookAndFeel();
        setSize(400, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        setResizable(false);

        setLayout(new GridBagLayout());
        GridBagConstraints gc = new GridBagConstraints();

        gc.insets = new Insets(5,5,5,5);

        gc.gridx = 0;
        gc.gridy = 0;
        add(instructions, gc);

        gc.gridx = 0;
        gc.gridy = 1;
        add(aLabel, gc);

        gc.gridx = 0;
        gc.gridy = 2;
        add(aField, gc);

        gc.gridwidth = 3;
        gc.fill = GridBagConstraints.HORIZONTAL;
        gc.gridx = 0;
        gc.gridy = 4;
        add(submit, gc);

        ///this is where I'm stuck////

        submit.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                String userIP = aField.getText();

                String mg = "Montgomery";
                if(userIP == mg){
                    System.out.println("correct!");
                }else{
                    System.out.println("WRONG!");
                }

            }
        });

        gc.gridwidth = 3;
        gc.fill = GridBagConstraints.HORIZONTAL;
        gc.gridx = 0;
        gc.gridy = 5;
        add(reset, gc);

        reset.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                reset.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "pressed");
                aField.setText("");             
            }
        });
    }

    private void setLookAndFeel() {

        try {
            UIManager.setLookAndFeel(
                "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
            );
        } catch (Exception exc) {
            // ignore error
        }

    }

}

Upvotes: 1

Views: 3866

Answers (7)

John Snow
John Snow

Reputation: 5334

When comparing strings you should use equals() method:

String mg = "Montgomery";
                if(userIP.equalsIgnoreCase(mg)){ // like this
                    System.out.println("correct!");
                }else{
                    System.out.println("WRONG!");
                }

Else you will not be comparings the content of the strings, but comparing refrence which is not what you want

EDIT: Actually, what you probably want is to use equalsIgnoreCase(), since else if the user enters "montgomery" it will throw a false since equals is case-sensitive. You can find the api here

Upvotes: 2

COD3BOY
COD3BOY

Reputation: 12102

DONT USE == to compare String it compares references, not values.

use .equals instead.

Read upon this answer/s for more detailed explanation.

Upvotes: 1

cpater
cpater

Reputation: 1099

Ok first you should not compare Strings with == ! User equals() instead.

In your case if (mp.equals(userIP)) { ...

Upvotes: 1

Balwinder Pal
Balwinder Pal

Reputation: 97

You can compare as

if(userIP.equals(mg))

Upvotes: 1

Bogdan Emil Mariesan
Bogdan Emil Mariesan

Reputation: 5647

The solution is simple when comparing String objects you must use the .equals() method.

So you would have:

if(str1.equals(str2)) { 
//code goes here 
}

Actually the equals method must be generally used when comparing any type of java objects. But take note that for some a custom comparator must be created, or override the compareTo method. But this is just extra info.

Upvotes: 1

duffymo
duffymo

Reputation: 308813

Classic mistake: use equals to compare strings, not ==.

Upvotes: 1

Péter Török
Péter Török

Reputation: 116266

You should not compare Strings using ==, but with equals, e.g.

if(userIP.equals(mg)){

The == equality operator tests for physical equality (i.e. are the left and right operands referring to the same object), not for value equality (i.e. are the left and right operands referring to objects having the same value).

Upvotes: 1

Related Questions