java - 返回 float 组方法

标签 java arrays return

我试图将 float 组返回到我的主类,以便我可以打印和比较该数组。

传递到类中的“str”由全局字符串声明,并取 self 的主类上的用户输入

主要内容

public static void main (String[] args) {
    Scanner sc = new Scanner(System.in);

    String input = null;

    System.out.print("Please enter a sentence or enter quit to end program: ");
    input = sc.nextLine();

    while(!input.equals("quit"))
    {       
        System.out.println("The number of characters in the string is: " + BloorS.count(input));
        System.out.println("The number of Spaces in the string is: " + Bloor_S.sCount(input));
        System.out.println("The number of words in the string is: " + Bloor_S.wCount(input));
        Bloor_S.print();

        Bloor_S.freq(); //Change
        System.out.println();
        System.out.print("Please enter a sentence or enter quit to end program: ");
        input = sc.nextLine();
    }
    sc.close();
}

public static float[] freq() {
    char[] let = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
    float [] freq = new float[26];

    int a, b; 

    char[] char1 = str1.toUpperCase().toCharArray();

    for (b = 0; b < str1.length(); b++)
    {
        for (a = 0; a < 26; a++)
        {
            if (let[a] == char1[b])
            {
                freq[a]++;
            }
        }
    }

    for (int f = 0; f < 26; f++)
    {
        freq[f] = freq[f] / strCount;
    }

    return freq;
}

所以在 //Change 线上,我想使用类似的东西

for (int i = 0; i < 26; i++)
{
    System.out.printf("%6.2f", Bloor_S.freq[i]);
    System.out.printf("%3c", '|');
    System.out.println();
}

这样我就可以一次打印出数组 1 个数字。

最佳答案

您的总体想法似乎不错,但您应该只调用 Bloor_S.freq() 一次并将结果保存到变量中。然后使用该变量。它看起来像这样:

float[] freq = Bloor_S.freq();
for (int i = 0; i < 26; i++)
{
    System.out.printf("%6.2f", freq[i]);
    System.out.printf("%3c", '|');
    System.out.println();
}

请注意,使用这么多静态函数不太像 Java。面向对象的方法是创建 Bloor_S 的实例并调用该实例(当时是非静态的)函数。然后,函数可以将它们将要处理的 String 作为参数,或者您可以将单个 String 作为构造函数参数。

关于java - 返回 float 组方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29282450/

相关文章:

c# - 使用 DllImport 将返回的 char* 从 C++ 传递到 C#

java - Stripe : How do i know whether card is 3d secure and how to charge it

java - Java 中是否有 EXIT_SUCCESS 和 EXIT_FAILURE 的替代品?

java - 如何使用 Maven 部署 HTML 和 WAR?

java - 使用retainAll()查找 HashMap 之间的交集

php - 如何丢弃 $_FILES 数组中的空 HTML 表单输入

javascript - 数组键和填充

php - 返回值与传递对象引用

java - Android 的 rawQuery() 错误

java - 在现有库中添加 javadoc