简体   繁体   English

检查字符串数组是否已填充或为空

[英]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 . 我知道rule将包含5 Numbers I wanted to save them in a String Array with 5 spots so I can use them later. 我想将它们保存在String Array with 5 spotsString Array with 5 spots以便以后使用。 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) 但是我总是收到NullPointerException,否则将跳过if情况(长度== 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: 在为您提供的示例中, rule[0]包含null ,您可以通过添加以下代码行来看到自己:

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

returns true (try it !) 返回true (尝试!)

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 ): 如果需要的话,将返回true并进入for循环。请参见以下可compile (使用javac myEmpty.java )并run (使用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 ! 您的if if (rule[0].equals("")) { 失败仅是因为rule[0]不包含您要检查的值 "" Keep in mind that "" and null are not the same, and use your if clauses accordingly ! 请记住, ""null不相同, 请相应地使用if子句

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. 考虑使用固定数组,请尝试使用ArrayList并将值添加到列表中。 The ArrrayList-class will adjust the length of the list automaticly. ArrrayList类将自动调整列表的长度。

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. 我想象的NullPointerException来自以下事实:您创建了一个字符串数组,但尚未使用任何值初始化它们。 They will default to null if you don't give them a value...hence the NPE. 如果您不给它们一个值,它们将默认为null ...因此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. 另外,如果要检查字符串是否包含字符,请使用isEmpty()方法。 It returns true if the length is 0 else it returns false. 如果长度为0,则返回true,否则返回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 您已经假定索引为0的元素不为null,并且对索引为0的元素调用equals()matches()方法会导致NullPointerException

Thrown when an application attempts to use null in a case where an object is required. 当应用程序在需要对象的情况下尝试使用null时抛出。 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. 将null的长度视为数组。
  4. Accessing or modifying the slots of null as if it were an array. 访问或修改null插槽,就好像它是一个数组一样。
  5. Throwing null as if it were a Throwable value. 将null抛出,就好像它是一个Throwable值一样。

Instead try like this 像这样尝试

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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