Write the following methods in a Java program : 1- A Java method Avg that return
ID: 3881862 • Letter: W
Question
Write the following methods in a Java program :
1- A Java method Avg that returns the Average of multiples of a number N. The method input parameters are an array size , an array A of numbers , and the number N. (2 marks)
2- A Java method Sum that returns the sum of numbers greater than a number N. The method input parameters are an array size , an array A of numbers , and the number N. (2 marks)
3- A Java method OddArray that prints an array of odd numbers less than a value N given as parameter. (2 marks)
4- A Java method called AboveAverage(...) of type integer that finds and returns how many numbers in an array A as parameter are above the average of the array. (2 marks)
5- Test the above methods from the main method using the samples given in the class. (2 marks)
6- A Java method StringInFile that returns the number of times a string is present in a file. The filename and the string are the parameters of the method. (2 marks)
Explanation / Answer
Here is the java code containing all the required functions :
import java.io.*;
class Solution
{
// part 1
public static int Avg(int size, int[] ar, int N)
{
int av=0;
int count=0;
for(int i=0;i<size;i++)
{
if(ar[i]%N==0)
{
av=av+ar[i];
count++;
}
}
av=av/count;
return av;
}
// part 2
public static int Sum(int size, int[] ar, int N)
{
int s=0;
for(int i=0;i<size;i++)
{
if(ar[i]>N)
s=s+ar[i];
}
return s;
}
// part 3
public static void OddArray(int N)
{
for(int i=1;i<N;i=i+2)
{
System.out.print(i+" ");
}
System.out.println();
}
// part 4
public static int AboveAverage(int[] ar)
{
int n=ar.length;
int avg=0;
for(int i=0;i<n;i++)
{
avg=avg+ar[i];
}
avg=avg/n;
int num=0;
for(int i=0;i<n;i++)
{
if(ar[i]>avg)
{
num++;
}
}
return num;
}
//part 6
public static int StringInFile(String filname, String str) throws IOException
{
FileReader fileReader = new FileReader(filname);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
int count=0;
while((line = bufferedReader.readLine()) != null)
{
System.out.println(line);
count = count + line.split(str, -1).length-1;
}
System.out.println(count);
bufferedReader.close();
return count;
}
// part 5
public static void main (String[] args) throws IOException
{
int[] ar={2, 5, 7, 4};
int size=4;
System.out.println(Avg(size, ar, 2));
System.out.println(Sum(size, ar, 5));
OddArray(9);
System.out.println(AboveAverage(ar));
System.out.println(StringInFile("file.txt","hey"));
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.