0

I'm trying to use another class to return data from another class. This class will either return a password, or a key, depending on the arguments sent to the class.

This is the function in the class that returns the data:

public static String main(String args[]){
        if (!args.equals(null)){
            String gen = generatePassword(args[1]);
            return gen;
        }else{
            String gen = generateRandomString();
            return gen;
        }
    }

My error is:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at me.GaryIsASloth.KeyGenerator.main(KeyGenerator.java:34)

With 34 referring to:

if (!args.equals(null)){

The arguments provided will either be "pass", following "true"/"false" which will tell the class whether to include special characters or not. Or for the key the args will be null.

I had the class working perfectly when I had it working with the key, and then after modification it worked fine with the password too. However I can't get it to work with both, dependant on the arguments. I've tried null check and length check. What can I do?

Jack Evans
  • 13
  • 5

3 Answers3

0

When checking for null you cannot check something.equals(null) as equals is a method and it cannot be called on null. Null is not an object. Secondly, elements in the arrays numbered starting from 0 so the first element will be arg[0].

public static String main(String args[]){
        String gen;
        if (args != null){
            gen = generatePassword(args[0]);
        }else{
            gen = generateRandomString();
        }
        return gen;
    }
Mikhail Chibel
  • 1,865
  • 1
  • 22
  • 34
0

This here:

 if (!args.equals(null)){
            String gen = generatePassword(args[1]);
            return gen;

just because args is not null, does this mean it has 2 elements?

this here is not so a good idea:

String main(String[] args)

because java has a method that looks like that so that coincidence is not allowing you to compile

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

Instead of checking if (!args.equals(null)) do it like this if (args != null)

Then you should check if you have correct number of arguments, if you want to access args[1]

if(args.length == 2)