【问题标题】:Returning float array method返回浮点数组方法
【发布时间】:2015-03-26 15:25:46
【问题描述】:

我正在尝试将一个浮点数组返回到我的主类,以便我可以打印和比较该数组。

传入类的'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 个数字。

【问题讨论】:

    标签: java arrays return


    【解决方案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 的实例并在其上调用(然后是非静态的)函数。然后,这些函数可以将它们将要处理的Strings 作为参数,或者您可以将单个String 作为构造函数参数。

    【讨论】:

      【解决方案2】:
          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();
          }
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-05-07
        • 1970-01-01
        • 1970-01-01
        • 2016-06-21
        • 2017-05-06
        • 2021-09-30
        • 2018-03-15
        • 1970-01-01
        相关资源
        最近更新 更多