A Java method to determine and return the Average or multiple or a number N. the
ID: 3768078 • Letter: A
Question
A Java method to determine and return the Average or multiple or a number N. the method parameters are N and an array of numbers. A Java method to determine and return the sum of last N numbers, where N and the numbers are in an array of a length greater or equal to N are all received as parameters. A Java method to determine and return if a number N is multiple of a number m, where N and M are received as a parameters. A Java method to determine and return an appropriate value indicating if a word is present in a file, where the filename and word are received as parameters. Test the above methods from the main method.Explanation / Answer
import java.io.File;
import java.util.Arrays;
import java.util.Scanner;
/**
* @author Srinivas Palli
*
*/
public class ServiceClass {
public static void main(String[] args) {
int a[] = { 20, 12, 25, 30, 35 };
int n = 5;
System.out.println("Average of Multiple of " + n + " is "
+ multipleAvgOf(a, n));
System.out.println("Last 3 numbers are "
+ Arrays.toString(lastNNumbers(a, 3)));
System.out.println("Is 20 is multiple 10 :" + multipleOFMN(20, 10));
System.out.println("Is Steve is exist in the names.txt file :"
+ searchInFile("names.txt", "Steve"));
System.out.println("Is Rajesh is exist in the names.txt file :"
+ searchInFile("names.txt", "Rajesh"));
}
/**
* @param a
* @param n
* @return
*/
public static double multipleAvgOf(int a[], int n) {
double avg = 0.0;
int sum = 0;
int count = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] % n == 0) {
sum += a[i];
count++;
}
}
avg = (double) sum / (double) count;
return avg;
}
/**
* @param a
* @param n
* @return
*/
public static int[] lastNNumbers(int a[], int n) {
int lastN[] = new int[n];
int count = 0;
for (int i = a.length - 1; i >= a.length - n; i--) {
lastN[count] = a[i];
count++;
}
return lastN;
}
/**
* @param m
* @param n
* @return
*/
public static boolean multipleOFMN(int m, int n) {
if (m % n == 0) {
return true;
} else {
return false;
}
}
/**
* @param fileName
* @param word
* @return
*/
public static boolean searchInFile(String fileName, String word) {
boolean flag = false;
try {
Scanner scanner = new Scanner(new File(fileName));
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (line.contains(word)) {
flag = true;
break;
}
}
} catch (Exception e) {
// TODO: handle exception
}
return flag;
}
}
names.txt:
Bruce Banner
Tony Stark
Natasha Romanoff
Clint Barton
Steve Rogers
Natasha Romanoff
OUTPUT:
Average of Multiple of 5 is 27.5
Last 3 numbers are [35, 30, 25]
Is 20 is multiple 10 :true
Is Steve is exist in the names.txt file :true
Is Rajesh is exist in the names.txt file :false
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.