仍在尝试使用 Java 进行编程,下面是我已经提交给大学的多种方法的最近作业的代码。
我的问题是,是否可以简化代码以使其更有效,而不是通过更长的路线进行处理。
1:打印数组的最大值。
2:打印数组的最小值。
3:打印Array的平均值。
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;
}
}