简体   繁体   中英

Checking if String Array is filled or empty

Hope this is not a duplicate because I already looked up some thread incl. this one , but it didn't help me.

My program is reading in some arguments that are optional by the user. They can add a rule to the game but don't have to. I know that the rule will be containing 5 Numbers . I wanted to save them in a String Array with 5 spots so I can use them later. If the user won't enter a rule there will be a specific rule taken.

String[] rule = new String[5];
//reading in the program arguments and stuff..
//here I want to check whether the rule is taken from the user or not
//don't want to check with a boolean check
if (rule[0].equals("")) {
    String[] newRule = "270-90-315-45-90".split("-");
    for (int i = 0; i < newRule.length; i++) {
        rule[i] = newRule[i];
    }
}

Already tried this:

rule[0].equals("")
rule[0].equals(null)
rule[0].equals("null")
rule[0].matches("")
rule[0].matches("null")
rule.length == 0
rule.equals(null)

But I always get a NullPointerException or the if case will be skipped (length == 0)

Hopeyou can help me.

您没有尝试过显而易见的事情吗?

if (rule[0] == null) {

In the example you provide us with, rule[0] contains the value null which you can see yourself by adding the following line of code:

System.out.println(rule[0]==null);

returns true (try it !)

if (rule[0]==null) {

will return true and get inside the for loop if that is what you want.. See the following class which you can compile (using javac myEmpty.java ) and run (using java myEmpty ):

class myEmpty {
    public static void main(String[] args) {
        String[] rule = new String[5];
        System.out.println(Arrays.toString(rule));
        //reading in the program arguments and stuff..
        //here I want to check whether the rule is taken from the user or not
        //don't want to check with a boolean check
        System.out.println(rule[0] == null);
        if (rule[0] == null) {
            //if ("".equals(rule[0])) {
            String[] newRule = "270-90-315-45-90".split("-");
            System.out.println(Arrays.toString(newRule));
            for (int i = 0; i < newRule.length; i++) {
                rule[i] = newRule[i];
                System.out.println(rule[i]);
            }
        }
    }
}

YOUR if if (rule[0].equals("")) { fails simply because rule[0] does not contain the value "" which you are checking for ! Keep in mind that "" and null are not the same, and use your if clauses accordingly !

So you want to change indices entered by user only.

The best way to do this would be to initialize the array with default values, then override those specified by the user.

String[] rule = "270-90-315-45-90".split("-");
// Now read "program arguments and stuff"

Insted of using an fixed array, try using an ArrayList and add the values to the list. The ArrrayList-class will adjust the length of the list automaticly.

Example:

ArrayList<String> rules = new ArrayList<>();

if (rules.size() == 0) {
    String[] newRule = "270-90-315-45-90".split("-");

    //Instead of newRule.length as a comparison, use the
    //number of rules with a number. Or use a foreach-loop
    //if the number of rules may vary

    for (int i = 0; i < 5; i++) {
        rules.add(newRule[i]);
     }
}

The NullPointerException I imagine is coming from the fact you have created an array of strings but have not initialized them with any values. They will default to null if you don't give them a value...hence the NPE.

Depending on where you are getting your input you could do something like this;

private static final String[] DEFAULT_RULES = {"270", "90", "315", "45","90" };
private static String[] rules;

public static void main(String[] args){

     if(!isValidRule(args)){
       // Potentially also check that the args are digits
       throw new IllegalArgumentException("Must contain 5 rules");
     }

     rules = (args.length > 0) ? args : DEFAULT_RULES; // Used brackets on the ternary operator here for readability. Not essential.

     ...

}

private static boolean isValidRule(String[] rules){
    return rules.length > 0 && rules.length != 5;
}

If you are working with some other non-static method thats taking the input, the same applies. You can perform your string split to get an array based on the delimiter you have specified and then do the same thing.

I don't imagine you would want to be passing around a string containing only hyphens if no rules are passed? Which is what you are hinting at by attempting to check if a string is empty after the split is performed.

Also if you want to check if the string contains characters or not use the isEmpty() method. It returns true if the length is 0 else it returns false. This already achieves what you are needlessly attempting.

In each of your tried options

rule[0].equals("")
rule[0].equals(null)
rule[0].equals("null")
rule[0].matches("")
rule[0].matches("null")
rule.length == 0
rule.equals(null)

You already assumed that your element at 0 index is not null , and calling equals() and matches() method on element at 0th index causing NullPointerException

Thrown when an application attempts to use null in a case where an object is required. These include:

  1. Calling the instance method of a null object.
  2. Accessing or modifying the field of a null object.
  3. Taking the length of null as if it were an array.
  4. Accessing or modifying the slots of null as if it were an array.
  5. Throwing null as if it were a Throwable value.

Instead try like this

if(rule[0] != null){
// Now you can call methods on your `0th` index element

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM