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

huangapple go评论78阅读模式
英文:

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

问题

以下是你提供的代码的翻译部分:

这是我的类它比较两个字符串数组中的元素并返回在两个数组中具有最高频率的单词然而从输出中可以看到尽管使用了String none初始化了两个数组但第一个索引将none附加到null”。请问有人可以告诉我我做错了什么导致出现这种情况吗

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++;
                        //避免再次计数相同的元素
                        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++;
                        //避免再次计数相同的元素
                        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]);
    }
}

生成的输出如下:

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
英文:

Here is my class below, that compares elements in two string arrays, and returns the word with the highest frequency in both 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. 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&lt;this.pro.length;i++)
{
this.pro[i]=&quot;none&quot;;
this.con[i]=&quot;none&quot;;
}
}
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&lt;9;i++)
{
proSplitter = proSplitter + pro[i] + &quot;,&quot;;
}
for(int i=0;i&lt;9;i++)
{
conSplitter = conSplitter + con[i] + &quot;,&quot;;
}
String[] values = proSplitter.split(&quot;,&quot;);
for(int i=0;i&lt;values.length;i++)
{
values[i] = values[i].trim();
}
String[] values1 = conSplitter.split(&quot;,&quot;);
for(int i=0;i&lt;values1.length;i++)
{
values1[i] = values1[i].trim();
}
int [] fr = new int [values.length];
int visited = -1;
for(int i = 0; i &lt; values.length; i++){
int count = 1;
for(int j = i+1; j &lt; values.length; j++){
if(!values[i].equalsIgnoreCase(&quot;none&quot;))
{
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 &lt; fr.length; i++)
{
if (max &lt; fr[i])
{
max = fr[i];
index = i;
}
}
int [] fr1 = new int [values1.length];
int visited1 = -1;
for(int i = 0; i &lt; values1.length; i++){
int count1 = 1;
for(int j = i+1; j &lt; values1.length; j++){
if(!values1[i].equalsIgnoreCase(&quot;none&quot;))
{
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&lt;values.length;i++)
{
System.out.println(&quot;pro = &quot;+values[i]);
}
for(int i = 0;i&lt;values1.length;i++)
{
System.out.println(&quot;con = &quot;+values1[i]);
}
int max1 = fr1[0];
int index1 = 0;
for (int i = 0; i &lt; fr1.length; i++)
{
if (max1 &lt; fr1[i])
{
max1 = fr1[i];
index1 = i;
}
}
String sentence[] = new String[2];
if(values[index].equalsIgnoreCase(values1[index1])) {
sentence[0] = &quot;balanced&quot;;
}else {
sentence[0] = values[index];
sentence[1] = values1[index1];
}
return sentence;
}
public static void main(String[] args){
HelloWorld tracker = new HelloWorld();
tracker.setPro(&quot;Apple, Pear&quot;, 1);
tracker.setCon(&quot;Banana&quot;, 1);
tracker.setPro(&quot;Apple&quot;, 2);
tracker.setCon(&quot;Water Melon&quot;, 2);
tracker.setPro(&quot;Guava&quot;, 3);
tracker.setCon(&quot;Ball&quot;, 3);
tracker.setPro(&quot;Apple&quot;, 4);
tracker.setCon(&quot;Mango, Plum&quot;, 4);
String[] arr = tracker.proWord();
System.out.println(&quot;pro = &quot;+arr[0]);
System.out.println(&quot;con = &quot;+arr[1]);
}
}

The output being generated is :

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

答案1

得分: 1

正如Arnaud所提到的,立即问题是您未初始化proSplitter,因此它的值为null。然后,当您使用proSplitter = proSplitter + pro[i] + &quot;,&quot;;追加字符串时,proSplitter将被转换(实际上)为&quot;null&quot;,然后会添加到末尾。因此,最好的做法是最初将其设置为&quot;&quot;

但是,您在这里还有另一个问题,即每次调用该方法时都会更改成员变量 - 因此它不会在第二次调用时为空(或null),它仍然包含之前的内容。

解决这个问题很简单:不要使用成员变量,而是将它们声明为局部变量。

您还有另一个问题,即实际上您在数组中重复执行了相同的代码以计算最常见的事物:方法的目的是允许您在不同的输入上运行相同的代码。

您还可以使用库方法。例如:

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

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

(这里有很多低效之处。重点是将其编写为方法,以消除重复)。

然后,您可以在现有方法中使用这个方法,这将更容易让其他人和您阅读。

英文:

As mentioned by Arnaud, the immediate problem is that you're leaving proSplitter uninitialized, so its value is null. Then, when you come to append a string to it with proSplitter = proSplitter + pro[i] + &quot;,&quot;;, proSplitter will be converted (effectively) to &quot;null&quot;, and then stuff is appended to the end. So, instead, make it &quot;&quot; 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.

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 = &quot;&quot;;
for (String s : array) {
if (s.equalsIgnoreCase(&quot;none&quot;)) continue;
int freq = Collections.frequency(Arrays.asList(array), s);
if (freq &gt; 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.

huangapple
  • 本文由 发表于 2020年8月10日 16:14:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/63336466.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定