Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

A Java method to determine and return the Average of multiple of a number N. the

ID: 3768079 • Letter: A

Question

A Java method to determine and return the Average of multiple of 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

//add file.txt in the solution

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;

public class Test {

public static double average(int N, int[] arr) {

       double sum=0;

       double count=0;

      

       for (int i = 0; i < arr.length; i++) {

           if (arr[i]%N == 0) {

               sum+=arr[i];

               count++;

           }

       }

       return sum/count;

   }

  

   public static int sumOfLastN(int N, int[] arr) {

       int sum=0;

       for (int i = arr.length-N; i < arr.length; i++) {

           sum+=arr[i];

       }

       return sum;

   }

  

public static boolean isMultiple(int N, int M) {

       return (N%M == 0);

   }

  

   public static boolean isWordPresent(String fileName, String word) throws FileNotFoundException {

       Scanner sc = new Scanner(new File(fileName));

      

       while (sc.hasNext()) {

           if (sc.next().equals(word)) {

               return true;

           }

       }

      

       return false;

   }

  

  

   public static void main(String[] args) throws FileNotFoundException {

      

       int[] arr={1,2,3,4,5,6,7,8,9,10};

       int N=3;

       int M=4;

      

       System.out.println("Average of multiple of 3 is: "+average(N, arr));

       System.out.println("Sum of last 3 are: "+sumOfLastN(N, arr));

       System.out.println("if 3 is multiple of 4: "+(isMultiple(N, M) ? "yes" : "no"));

       System.out.println("word einstein in file name file.txt: "+(isWordPresent("file.txt", "einstein") ? "yes" : "no"));

      

      

   }

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote