繁体   English   中英

Java void 转换为 int 数组

[英]Java void into an int array

如何将 void 存储到数组中?

对于我的示例:将(字符串文本)计数为 int[] 字母。

是否有一个快速简便的机会来做到这一点,还是我应该完全重写它?

我真的很感谢你的帮助

我的代码:

public static void main (String [] args){
    String text="E";

    String[] words = split(text);
    int[] letter = count(text);
    someWords(words, letter);
}   

public static int[] count(String text){
    int count;

    for (char letter=(char)65;letter<=90;letter++){
        count=0;

        for (int i=0; i<text.length(); i++){

            if (letter==text.charAt(I) || (letter+32)==text.charAt(I)){
            count++;
            }


        } 
            if (count>0){
            System.out.println(letter+" = "+count);
            }

    }

}

我可能是错的,因为你的问题不是很清楚,但似乎你想要做的是:

public static int[] count(String text){
    int[] counts = new int[26];

    // iterate over each letter:
    for (char letter='A';letter<='Z';letter++){
        int currentIndex = (int) letter - 'A';

        // count the occurrences of the current letter:
        for (int i=0; i<text.length(); i++){
            if (letter==text.charAt(i) || (letter+32)==text.charAt(i)){
                counts[currentIndex]++;
            }
        } 
        // print the count for the current letter if non-zero
        if (counts[currentIndex]>0){
            System.out.println(letter+" = " + counts[currentIndex]);
        }
    }
    return counts;
}

肯定有一种更有效的方法来做到这一点(迭代text的字符并相应地增加计数索引将比检查text所有字符 26 次更快),但该方法有效。

我真的不明白你为什么要这样做,但你可以将int[]作为参数传递。

...
int[] count = new int[1];
count(text, count);
...

public static void count(String text, int[] count){
   ...
   count[0] = ..
}

阅读您的代码,您似乎只想返回整数而不是整数数组(字符串中的字母数)

public static int count(String text){
    int count;

    for (char letter=(char)65;letter<=90;letter++){
        count=0;     // are you sure you want to set the value of count to 0 every time you loop?
        for (int i=0; i<text.length(); i++){

            if (letter==text.charAt(i) || (letter+32)==text.charAt(i)){
            count++;
            }
        } 
        if (count>0){
            System.out.println(letter+" = "+count);
        }
    }
    return count;
}

在你的主要方法中你写:

String[] words = split(text);
int letter = count(text);
    public int count()
{
count = 0;
for ...
...
...
return count;
}

您应该在函数末尾使用 RETURN 字,并在函数名称旁边声明返回类型(int、string 等)。

你只需要旋转一次字符串:

public static int[] count(String text) {
    int[] totals = new int[26];
    for (char c : text.toUpperCase().toCharArray()) {
        int idx = (int)c - (int)'A';
        if ((idx >= 0) && (idx <= 26)) {
           totals[idx]++; 
        }
    }
    return totals;
}

暂无
暂无

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

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