Still trying to get a handle on programming in Java, below is the code to a recent assignment in multiple methods that I’ve already submitted for college.
My query is, is it possible to streamline the code any to make it more effective as opposed going about it via a longer route.
1: Print highest value of an Array.
2: Print lowest value of an Array.
3: Print average value of Array.
4: Print number of occurrences of a specific word in a String.
5: Print the average word length of a string.
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;
}
}
Making it more effective:
You could always use DRY(Don’t repeat yourself) here and create a
ArrayUtilsclass and keep all these methods there and generalize them so that you can reuse them.similar change for
maxmethod