-1

I want to code a personal modloader for minecraft (create files , download files, sort files, etc) and the first window which is created is a JOptionPane which asks for a Version (i do not code in java really long, i don´t use spinner, just a "msg dialog" asking for a version). The code is:

public JOptionPane version = new JOptionPane();
public String modversion;

public Version()
{
    showVersion();
}

public static void main(String[] args)
{

}

public void showVersion()
{
    //input = version
    String vers = version.showInputDialog("Welche Version soll modifiziert werden?");

    if (vers.equals(null)) {
            return;
    } else { 
        if(vers.equals("1.5.2") || vers.equals("1.6.2") || vers.equals("1.6.4") || vers.equals("1.7.2") || vers.equals("1.7.10") || vers.equals("1.8") || vers.equals("1.8.9") || vers.equals("1.9") || vers.equals("1.10.2") || vers.equals("1.11.2"))
        {

          //mod version is saved as String (title for the config list)

            modversion = vers;
            return;
        } else  {
           // with incompatible input the method will be repeated
            JOptionPane.showMessageDialog(null, "Diese Version wird leider nicht supportet");
            showVersion();
        }
    }
}

If you just press "Ok", the input would equal "null":

if (vers.equals(null)) {
            return;
    }

but it don´t quit the method, it says NullPointerException. Why doesn´t it just quit the method?

JavaGamer
  • 51
  • 8

2 Answers2

1

You can't call .equals() on a null object.

To check if the vers variable is null, you should use vers == null

Raquel Guimarães
  • 957
  • 1
  • 12
  • 18
1

It's correct that you get an exception here. Here:

if (vers.equals(null)) {

You are trying to call a method on a variable that is null. As you said yourself, vers is null at this point.

To check for null you have to use the == operator.

if(vers == null) { return;}
Dennux
  • 240
  • 1
  • 8