inputData.txt file -15 -57 -75 -93 -42 -1 -9 -63 -77 -12 Problem Statement: The
ID: 3862881 • Letter: I
Question
inputData.txt file
-15
-57
-75
-93
-42
-1
-9
-63
-77
-12
Explanation / Answer
inputData.txt (save the file under D drive .Then the path of the file pointing to it is D:\inputData.txt)
-15
-57
-75
-93
-42
-1
-9
-63
-77
-12
______________________
ReadFileNos.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFileNos {
public static void main(String[] args) {
//Creating an integer type two dimensional array of size 10
int arr[]=new int[10];
//Declaring variables
int i=0,start = 0,last=0,max=0;
Scanner ifsInput =null;
try {
//Scanner object is used to get the inputs entered by the user
ifsInput=new Scanner(System.in);
//getting the inputs enetred by the user
System.out.print("Enter the start value :");
start=ifsInput.nextInt();
System.out.print("Enter the last value :");
last=ifsInput.nextInt();
//Opening the file
ifsInput = new Scanner(new File("D:\inputData.txt"));
//reading the data from the file
while(ifsInput.hasNextInt())
{
arr[i]=ifsInput.nextInt();
i++;
}
max=findMax(arr,start,last);
} catch (FileNotFoundException e) {
//Displaying the exception
System.out.println(e);
}
finally
{
ifsInput.close();
}
System.out.println("The maximum number between "+start+" and "+last+" elements of an array is "+max);
}
//this method will find the maximum value with in the range
private static int findMax(int[] arr, int start, int last) {
if(start>last)
throw new IllegalArgumentException("Empty range");
int maxSoFar=arr[0];
for(int i=start;i<last;i++)
{
if(arr[i]>maxSoFar)
maxSoFar=arr[i];
}
return maxSoFar;
}
}
_____________________
Output#1:
Enter the start value :1
Enter the last value :7
The maximum number between 1 and 7 elements of an array is -1
__________________
Output#2:
Enter the start value :8
Enter the last value :10
The maximum number between 8 and 10 elements of an array is -12
__________________
Output#3:
Enter the start value :1
Enter the last value :5
The maximum number between 1 and 5 elements of an array is -15
___________________Thank You
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.