简化Java中多种方法的代码?

时间:2012-12-04 09:43:34

标签: java arrays methods

仍在尝试使用Java编写程序,下面是我已经提交给大学的多种方法中最近作业的代码。

我的查询是,是否可以简化代码,使其更有效,而不是通过更长的路线进行。

1:打印数组的最高值 2:打印阵列的最低值 3:打印阵列的平均值 4:打印字符串中特定单词的出现次数 5:打印字符串的平均字长。

public class MaxMinAverage {
static int[] values = {1, 4, 3, 57, 7, 14, 7, 3, 10, 5, 4, 4, 10, 5, -88};
static String sentence = "the cat sat on the mat and the dog sat on the rug";
public static void main(String[] args) {
    System.out.println("MaxMinAverage.java\n=====================");
    System.out.println("Maximum value = "+getMaximum(values));
    System.out.println("Minimum value = "+getMinimum(values));
    System.out.println("Average Value =" +getAverage(values));
    System.out.println("Frequency of 'the' = "+getFrequency(sentence,"the"));
    System.out.println("Average word length = "+getAverageWordLength(sentence));
    }
    public static int getMaximum(int[]arr){
        int max = 0;
        for(int i = 0; i < values.length; i++){
            if(values[i] > max){
                    max = values[i];
                    }
            }
        return max;
     }
    public static int getMinimum(int[] arr){
        int min = 0;
        for(int i = 1; i < values.length; i++){
            if(values[i] < min){
                    min = values[i];
                    }
            }
        return min;
    }
    public static float getAverage(int[] arr){
        float result = 0;
        for(float i = 0; i < values.length; i++){
             result = result + values[(int) i];
        }
        return result/values.length;
     }
    public static int getFrequency(String sentance, String word){
        String keyword = "the";
        String[] temp;
        String space = " ";
        temp = sentence.split(space);
        int counter = 0;
        for(int i = 0; i < temp.length; i++){
            if(temp[i].equals(keyword)){
                counter++;
            }
        }
        return counter;
    }
    public static float getAverageWordLength(String sentance){
        String characters = sentence.replaceAll("\\W","");
        float total = characters.length();
        float result = 0;
        String[] temp;
        String space = " ";
        temp = sentence.split(space);
        for(int i = 0; i < temp.length; i++){
            result++;   
        }
        return total/result;
    }
}

3 个答案:

答案 0 :(得分:0)

提高效率:

你总是可以在这里使用 DRY(不要重复自己)并创建一个ArrayUtils类,并将所有这些方法保存在那里并对它们进行概括,以便您可以重复使用它们。

public static int getMinimum(int[] arr){
        int min = arr[0];  //change here
        for(int i = 1; i < values.length; i++){
            if(values[i] < min){
                    min = values[i];
                    }
            }
        return min;
    }

max方法的类似更改

答案 1 :(得分:0)

getMaximum你可能想要int max = Integer.MIN_VALUE;在getMinimum中你需要int min = Integer.MAX_VALUE;。否则getMaximum如果数组中的所有元素都小于零(因此返回不在数组中的值)将返回0;如果所有元素都大于零,则返回0(这也是错误的) 。

此外,在getMinimum开始从索引1开始迭代意味着您错过索引0。

此外,您不使用方法的参数,直接使用values数组。假设您调用getMinimum(someOtherArray),您仍然会在values上进行计算。相反,你应该迭代作为参数给出的数组,如下所示:

public static int getMinimum(int[] arr){
    int min = Integer.MAX_VALUE;
    for(int i = 0; i < arr.length; i++){
        if(arr[i] < min){
                min = arr[i];
        }
    }
    return min;
}

当然,这应该适用于所有方法。

答案 2 :(得分:0)

您可以将getMaximumgetMinimumgetAverage的逻辑部分放在同一个循环中(getFrequencygetAverageWordLength在另一个循环中相同)遵循:

public static void getMinMaxAvg(int[] values) {
    if (values == null || values.length == 0) {
        throw new IllegalArgumentException();
    }
    int min = values[0];
    int max = values[0];
    int i = 1;
    int sum = 0;
    for (i = 1; i < values.length; i++) {
        if (values[i] < min) {
            min = values[i];
        } else if (values[i] > max) {
            max = values[i];
        }
        sum += values[i];
    }
    System.out.println("min = " + min);
    System.out.println("max = " + max);
    System.out.println("avg = " + ((float) sum / (i + 1)));
}

public static void getFreqAvg(String sentence, String word) {
    if (sentence == null || sentence.isEmpty()) {
        throw new IllegalArgumentException();
    }
    if (word == null || word.isEmpty()) {
        throw new IllegalArgumentException();
    }
    String[] words = sentence.replaceAll("^ *(.*?) *$", "$1").split(" +");
    int freq = 0;
    int sum = 0;
    int i = 0;
    for (i = 0; i < words.length; i++) {
        if (words[i].equalsIgnoreCase(word)) {
            freq++;
        }
        sum += words[i].length();
    }
    System.out.println("freq of \"" + word + "\" = " + freq);
    System.out.println("avg word length = " + ((float) sum / (i + 1)));
}

public static void main(String[] args) {

    int[] values = { 1, 4, 3, 57, 7, 14, 7, 3, 10, 5, 4, 4, 10, 5, -88 };
    String sentence = " the  cat sat on the mat and the dog sat on the rug ";
    String word = "the";

    getMinMaxAvg(values);
    getFreqAvg(sentence, word);

}

打印:

min = -88
max = 57
avg = 2.8125
freq of "the" = 4
avg word length = 2.642857