儘管仍然試圖在Java中進行編程,但下面是我已經提交給大學的多種方法中最近一次賦值的代碼。簡化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;
}
}
當前的代碼有什麼問題?它看起來很好。 –
您需要分別將'min'和'max'的初始值設置爲'Integer.MAX_VALUE'和'Integer.MIN_VALUE'。 –
如果您正在尋找簡化步驟,請點擊此處http://codereview.stackexchange.com/?as=1 –