简体   繁体   English

为什么 Java 字符串数组在第一个单元格中将字符串附加到 null ?

[英]Why is Java string array appending a string to null in first cell?

Here is my class below, that compares elements in two string arrays, and returns the word with the highest frequency in both arrays.下面是我的 class,它比较两个字符串 arrays 中的元素,并返回 arrays 中频率最高的单词。 However as visible from the output, the first index is appending none to null in spite of initializing both arrays with the String none.然而,从 output 可以看出,第一个索引没有附加到null ,尽管使用String none. none arrays。 Can someone kindly let me know what I am doing wrong that is leading to this?有人可以让我知道我做错了什么导致这种情况吗?

public class HelloWorld{
    
    public String[] pro;
    public String[] con;
    String proSplitter;
    String conSplitter;
    
    public HelloWorld() {
        this.pro = new String[9];
        this.con = new String[9];
        for(int i=0;i<this.pro.length;i++)
        {
            this.pro[i]="none";
            this.con[i]="none";
        }
    }

    public String[] getPro() {
        return pro;
    }

    public String[] getCon() {
        return con;
    }

    public void setPro(String pros, int proIndex) {
        pro[proIndex] = pros;
    }

    public void setCon(String cons, int conIndex) {
        con[conIndex] = cons;
    }
    
    public String[] proWord(){
        for(int i=0;i<9;i++)
        {
            proSplitter = proSplitter + pro[i] + ",";
        }
        for(int i=0;i<9;i++)
        {
            conSplitter = conSplitter + con[i] + ",";
        }
        String[] values = proSplitter.split(",");
        for(int i=0;i<values.length;i++)
        {
            values[i] = values[i].trim();
        }
        String[] values1 = conSplitter.split(",");
        for(int i=0;i<values1.length;i++)
        {
            values1[i] = values1[i].trim();
        }

        int [] fr = new int [values.length];
        int visited = -1;

        for(int i = 0; i < values.length; i++){
            int count = 1;
            for(int j = i+1; j < values.length; j++){
                if(!values[i].equalsIgnoreCase("none"))
                {
                    if(values[i].compareTo(values[j])==0){
                        count++;
                        //To avoid counting same element again
                        fr[j] = visited;
                    }
                }
            }
            if(fr[i] != visited)
                fr[i] = count;
        }

        int max = fr[0];
        int index = 0;

        for (int i = 0; i < fr.length; i++)
        {
            if (max < fr[i])
            {
                max = fr[i];
                index = i;
            }
        }

        int [] fr1 = new int [values1.length];
        int visited1 = -1;

        for(int i = 0; i < values1.length; i++){
            int count1 = 1;
            for(int j = i+1; j < values1.length; j++){
                if(!values1[i].equalsIgnoreCase("none"))
                {
                    if(values1[i].compareTo(values1[j])==0){
                        count1++;
                        //To avoid counting same element again
                        fr1[j] = visited1;
                    }
                }
            }
            if(fr1[i] != visited1)
                fr1[i] = count1;
        }
        for(int i = 0;i<values.length;i++)
        {
            System.out.println("pro = "+values[i]);
        }
        for(int i = 0;i<values1.length;i++)
        {
            System.out.println("con = "+values1[i]);
        }
        int max1 = fr1[0];
        int index1 = 0;

        for (int i = 0; i < fr1.length; i++)
        {
            if (max1 < fr1[i])
            {
                max1 = fr1[i];
                index1 = i;
            }
        }

        String sentence[] = new String[2];
        if(values[index].equalsIgnoreCase(values1[index1])) {
            sentence[0] = "balanced";
        }else {
            sentence[0] = values[index];
            sentence[1] = values1[index1];
        }
        return sentence;
    }
    public static void main(String[] args){
        
        HelloWorld tracker = new HelloWorld();
        
        tracker.setPro("Apple, Pear", 1);
        tracker.setCon("Banana", 1);
        tracker.setPro("Apple", 2);
        tracker.setCon("Water Melon", 2);
        tracker.setPro("Guava", 3);
        tracker.setCon("Ball", 3);
        tracker.setPro("Apple", 4);
        tracker.setCon("Mango, Plum", 4);
        
        String[] arr = tracker.proWord();
        System.out.println("pro = "+arr[0]);
        System.out.println("con = "+arr[1]);
    }
}

The output being generated is:正在生成的 output 是:

pro = nullnone
pro = Apple
pro = Pear
pro = Apple
pro = Guava
pro = Apple
pro = none
pro = none
pro = none
pro = none
con = nullnone
con = Banana
con = Water Melon
con = Ball
con = Mango
con = Plum
con = none
con = none
con = none
con = none
pro = Apple
con = nullnone

As mentioned by Arnaud , the immediate problem is that you're leaving proSplitter uninitialized, so its value is null .正如Arnaud所提到的,直接的问题是你让proSplitter未初始化,所以它的值是null Then, when you come to append a string to it with proSplitter = proSplitter + pro[i] + ",";然后,当你来到 append 时,给它一个字符串proSplitter = proSplitter + pro[i] + ","; , proSplitter will be converted (effectively) to "null" , and then stuff is appended to the end. , proSplitter将(有效地)转换为"null" ,然后将内容附加到末尾。 So, instead, make it "" initially.因此,相反,最初将其设为""

However, you've got another problem here, which is that you're mutating a member variable each time you invoke that method - so it's not null (or empty) second time around, it still contains what was there previously.但是,这里还有另一个问题,即每次调用该方法时都会改变一个成员变量——所以第二次不是 null (或空),它仍然包含以前的内容。

The fix for that is straightforward: instead of using a member variable, declare these as local variables.解决方法很简单:不使用成员变量,而是将它们声明为局部变量。

You've also got the problem that you're effectively duplicating the code to count the most frequent thing in an array: this is what methods are for, to allow you to run the same code over different inputs.您还遇到了一个问题,即您正在有效地复制代码以计算数组中最常见的事物:这就是方法的用途,允许您在不同的输入上运行相同的代码。

You can also make use of library methods.您还可以使用库方法。 For example:例如:

String mostFrequent(String[] array) {
  int maxFreq = 0;
  String maxFreqS = "";
  for (String s : array) {
    if (s.equalsIgnoreCase("none")) continue;

    int freq = Collections.frequency(Arrays.asList(array), s);
    if (freq > maxFreq) {
      maxFreq = freq;
      maxFreqS = s;
    }
  }
  return maxFreqS;
}

(There are lots of inefficiencies here. The point is more about writing this as a method, to remove the duplication). (这里有很多效率低下的地方。重点是把它写成一种方法,以消除重复)。

Then you can use this inside your existing method, and it will be a whole lot easier for others - and you - to read.然后你可以在你现有的方法中使用它,它会更容易让其他人 - 和你 - 阅读。

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

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