简体   繁体   English

如何返回 Java 中创建的数组?

[英]How do I return a created Array in Java?

In this program, I'm supposed to count the amount of times the letters 'A','B' and 'C' are in the string and return that as an array.在这个程序中,我应该计算字母“A”、“B”和“C”在字符串中出现的次数,并将其作为数组返回。 The input is ABBACCCCAC and I'm supposed to get an output of [3, 2, 5] but I'm getting [1, 1, 2, 2, 1, 2, 3, 4, 3, 5]输入是 ABBACCCCAC,我应该得到 [3, 2, 5] 的 output 但我得到 [1, 1, 2, 2, 1, 2, 3, 4, 3, 5]

import java.util.Arrays;
public class HelloWorld{

 public static void main(String []args){
    String str = "ABBACCCCAC";
    int[] arr = new int[str.length()];
    int acount = 0, bcount = 0, ccount = 0;
    
    for(int i =0; i<str.length();i++){
        if(str.charAt(i) == 'A'){
            acount++;
            arr[i] = acount;
        }
        else if(str.charAt(i) == 'B'){
            bcount++;
            arr[i] = bcount;
        }
        else if(str.charAt(i) == 'C'){
            ccount++;
            arr[i] = ccount;
        }
    }
    System.out.print(Arrays.toString(arr));
 }
}

You were close.你很亲密。 Just change your array size to 3 and the indiced to 0,1, and 2.只需将您的数组大小更改为 3 并指示为 0,1 和 2。

   String str = "ABBACCCCAC";
    int[] arr = new int[3];
    int acount = 0, bcount = 0, ccount = 0;
    
    for(int i =0; i<str.length();i++){
        if(str.charAt(i) == 'A'){
            acount++;
            arr[0] = acount;
        }
        else if(str.charAt(i) == 'B'){
            bcount++;
            arr[1] = bcount;
        }
        else if(str.charAt(i) == 'C'){
            ccount++;
            arr[2] = ccount;
        }
    }
    System.out.print(Arrays.toString(arr));

Your could also just increment the array locations directly.您也可以直接增加数组位置。

arr[0]++; // like this.

Right now, you are assigning the counts to the array at each step of the counting, whereas you should have done this at the end of the count.现在,您在计数的每一步都将计数分配给数组,而您应该在计数结束时完成此操作。 Also, note that you created an array the same length of the string, rather than the expected 3 .另外,请注意,您创建了一个与字符串长度相同的数组,而不是预期的3

You should just move the creation of the array to the end, with an array creation expression:您应该使用数组创建表达式将数组的创建移到最后:

String str = "ABBACCCCAC";
int acount = 0, bcount = 0, ccount = 0;

for(int i =0; i<str.length();i++){
    if(str.charAt(i) == 'A'){
        acount++;
    }
    else if(str.charAt(i) == 'B'){
        bcount++;
    }
    else if(str.charAt(i) == 'C'){
        ccount++;
    }
}

int[] arr = new int[] { acount, bcount, ccount }; // <--- here!
System.out.print(Arrays.toString(arr));

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

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