Write a Java part code to do the following :
** Suppose a file called infile stored in drive D: ,filled with five integers(1000,200,3030,40 and 500)
Note : Use ArrayIndexOutOfBoundsException when you use array in one method.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.*;
public class file
{
//method to search 500 and return its position in the
array
public static int search(int arr[],int size)
{
int i=-1;
try
{
for(i=0;i<size;i++)
if(arr[i]==500)
//compare for 500
break;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array out of Bound");
}
if(i==size) //if not found then
return -1
return -1;
else
return (i+1);
//return the position
}
//method to sort the array
public static void sort(int arr[],int num)
{
int i,j,t;
//selection sort logic
try
{
for(i=0;i<num;i++)
{
for(j=i+1;j<num;j++)
{
if(arr[i]>arr[j])
{ //swap
t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}
}
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array out of Bound");
}
}
public static void main(String[] args) throws
Exception
{
//declare scanner object to read
the file contents
Scanner scanner = new Scanner(new
File("D:\\infile.txt"));
int n,i;
//declare filewriter object to open the file and write the array
contents
FileWriter writer = new FileWriter("D:/outfile.txt");
int arr[] = new int[50]; //declare array with size 50
i=0;
//loop to read the data from file
try
{
while
(scanner.hasNext())
{
n=scanner.nextInt();//read the numbers
arr[i]=n; //assign the number into array
i++;
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array out of Bound");
}
int len = i; //assign number of
elements read from file
System.out.print("\nThe array
elements : ");
for(i=0;i<len;i++) //loop to
print the array elements
System.out.print(arr[i]+" ");
int pos = search(arr,len); //call
search() to know the postion of 500
if(pos==-1)
System.out.print("\n500 is not in the array");
else
System.out.print("\nThe number 500
is at "+ pos + " Position");
//call top sort() method
sort(arr,len);
//loop to write the array elements
into file
for (i = 0; i < len; i++) {
writer.write( arr[i] + "\t"+ "");
}
writer.close();//close the files
scanner.close();
}
}
output
Get Answers For Free
Most questions answered within 1 hours.