簡體   English   中英

返回浮點數組方法

[英]Returning float array method

我試圖將float數組返回到我的主類,以便可以打印和比較該數組。

傳遞給類的'str'由全局字符串聲明,並取自我的主類上的用戶輸入

主要

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用作構造函數參數。

    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();
    }

按照我想要的方式工作。 謝謝。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM