In: Computer Science
Write the following methods in a Java project:
a) A Java method to determine and return the sum of first three numbers, where three numbers are received as parameters.
b) A Java method to determine and return the highest of N integers. The number of integers is received as a parameter. The method should prompt the user to enter the N numbers, then it return the highest.
c) A Java method to determine and return an appropriate value indicating if a number K is even, where K is received as a parameter.
d) A Java method to determine and return an appropriate value indicating if a word is present in a file, where the filename and word is received as parameters.
e) Test the above methods from the main method.
import java.util.*;
import java.io.*;
class MedhodsDemo
{
Scanner input=new Scanner(System.in);
int sumNumbers(int a,int b,int c)
{
return (a+b+c);
}
int highestNumber(int N)
{
int number=0,highest=0;
for(int i=1;i<=N;i++)
{
System.out.print("Enter number "+i+" : ");
number=input.nextInt();
if(i==1)
{
highest=number;
}
if(highest<number)
{
highest=number;
}
}
return highest;
}
String checkEven(int number)
{
String ans="";
if(number%2==0)
{
ans=number +" is an even number.";
}
else
{
ans=number +" is not an even number.";
}
return ans;
}
String searchWordFromFile(String searchWord,String
fileName)
{
int count=0;
try
{
String words[]=null;
String s;
File f1=new File(fileName);
FileReader fr=new FileReader(fileName);
BufferedReader br=new BufferedReader(fr);
if(!(f1.exists()))
{
System.out.println("File is not found!!");
System.exit(0);
}
while((s=br.readLine())!=null)
{
words=s.split(" ");
for(String w:words)
{
if(w.equals(searchWord))
{
count++;
}
}
}
br.close();
fr.close();
}
catch(Exception e1)
{
System.out.println(e1);
}
return "The word is "+count+" times present.";
}
}
class Main
{
public static void main(String args[])
{
MedhodsDemo md=new MedhodsDemo();
Scanner input=new Scanner(System.in);
int no1,no2,no3,N,number;
System.out.println("\nMethod : 1\n");
System.out.print("Enter number 1 : ");
no1=input.nextInt();
System.out.print("Enter number 2 : ");
no2=input.nextInt();
System.out.print("Enter number 3 : ");
no3=input.nextInt();
System.out.println("Sum of three numbers :
"+md.sumNumbers(no1,no2,no3));
System.out.println("\nMethod : 2\n");
System.out.print("Enter number of Integers : ");
N=input.nextInt();
System.out.println("Highest of N integers :
"+md.highestNumber(N));
System.out.println("\nMethod : 3\n");
System.out.print("Enter a number : ");
number=input.nextInt();
System.out.println(md.checkEven(number));
System.out.println("\nMethod : 4\n");
System.out.print("Enter a word : ");
String searchWord=input.next();
System.out.print("Enter a file name with an extension : ");
String fileName=input.next();
System.out.println(md.searchWordFromFile(searchWord,fileName));
}
}