jeudi 2 mars 2017

two if blocks vs if and else if

if(button.getText().equals("Hello")){
     button.setText("Hello World");
}
else if(button.getText().equals("Hello World")){
     button.setText("Hello");
}

the code above works, while the second doesn't:

if(button.getText().equals("Hello")){
     button.setText("Hello World");
}
if(button.getText().equals("Hello World")){
     button.setText("Hello");
}

This one goes straight to the second if block

I don't understand how it is different from the first one, it should go first to the first if block but it just skips it

I hope you can explain me this

here is the full code:

package javaapplication4;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;

public class JavaApplication4 implements ActionListener{
    JFrame frame;
    JButton button;
    public static void main(String[] args){
        JavaApplication4 gui = new JavaApplication4();
        gui.go();
    }

    public void go() {
        frame = new JFrame();
        button = new JButton("Hello");

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(200,300);
        frame.setVisible(true);
        frame.getContentPane().add(button);

        button.addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent ev){
        if(button.getText().equals("Hello")){
            button.setText("Hello World");
        }
        if(button.getText().equals("Hello World")){
            button.setText("Hello");
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire