In: Computer Science
Implementation in JAVA:
Code:
// import some neccesary files
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
// class named L2
public class L2 {
// main method or driver method
public static void main(String[] args) throws
FileNotFoundException {
System.out.println("\n Outputs for
File 1 : ");
// path of file L2-1
String
L21="C:\\Users\\Ankit\\Desktop\\L2-1.txt";
// create object of ArrayExaminer
class and pass path string into constructor
ArrayExaminer ae = new
ArrayExaminer(L21);
// call the functions
ae.fillArray();
ae.findLargest();
System.out.println("Array is going
up : "+ae.goingup());
System.out.println("Array is going
down : "+ae.goingdown());
ae.isPeak();
// same done for file 2
System.out.println("\n\n Outputs for File 2 : ");
String
L22="C:\\Users\\Ankit\\Desktop\\L2-2.txt";
ArrayExaminer ae1 = new
ArrayExaminer(L22);
ae1.fillArray();
ae1.findLargest();
System.out.println("Array is going
up : "+ae1.goingup());
System.out.println("Array is going
down : "+ae1.goingdown());
ae1.isPeak();
}
}
// class named ArrayExaminer
class ArrayExaminer{
// instance Variables
String textFilename;
int arr[];
int largest;
int largestindex;
// constructor
public ArrayExaminer(String textFilename ) {
this.textFilename=textFilename;
arr = new int[20];
largest=0;
largestindex=0;
}
// read file and fill into array
public void fillArray() throws FileNotFoundException
{
// create object of File class and
pass path of file
File file = new
File(textFilename);
// Scanner object
Scanner s = new
Scanner(file);
int i=0;
// read file and Store into
array
try
{
while( s.hasNext() )
{
int element =
s.nextInt();
arr[i]=element;
i++;
}
}
finally
{
s.close();
}
// print Array into one line
System.out.println("\nArray :
"+Arrays.toString(arr));
}
// find largest element and its index
public void findLargest() {
for(int i=0;i<arr.length;i++)
{
if(largest<arr[i]) {
largest=arr[i];
largestindex=i;
}
}
System.out.println("The largest
element in Array is : "+largest);
System.out.println("The largest
element index in Array is : "+largestindex);
}
// return is array is going up
public boolean goingup() {
for(int i=1;i<largestindex;i++)
{
if(arr[i-1]>arr[i]) {
return false;
}
}
return true;
}
// return is array is going down
public boolean goingdown() {
for(int
i=largestindex+1;i<arr.length;i++) {
if(arr[i-1]<arr[i]) {
return false;
}
}
return true;
}
// print oeak State of Array
public void isPeak() {
if(goingup() && goingdown()) {
System.out.println("Array has a
peak.");
}
else {
System.out.println("Array Does not has a
peak.");
}
}
}
SAMPLE OUTPUT;
TEXTFILE L2-1;
TEXTFILE L2-2
// PLEASE THUMBS-UP AND RATE POSITIVELY
If you have any doubt regarding this question please ask me in
commnets
// THANK YOU:-)