Write a }++ program which reads array elements from a file and then searches val
ID: 3764319 • Letter: W
Question
Write a }++ program which reads array elements from a file and then searches value entered from the keyboard in the array. Use arrayListType Sequential search function.
template <class elemType>
int arrayListType<elemType>::seqSearch(const elemType& item) const
{
int loc;
bool found = false;
for (loc = 0; loc < length; loc++)
if (list[loc] == item)
{
found = true;
break;
}
if (found)
return loc;
else
return -1;
}
Explanation / Answer
Answer:
import java.io.*;
import java.util.*;
class Texts
{
public static void main(String args[])
{
readIntegers();
sequentialSearch (arrList, searchKey);
}
static void readIntegers()
{
Integer[] array = new Integer[1000];
int i = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter the file name with extention to read array values : ");
File file = new File(input.nextLine());
Scanner inputFile = null;
try
{
inputFile = new Scanner(file);
}
catch (Exception e)
{
System.out.println("File not found!");
}
if (inputFile != null)
{
System.out.print("number of integers in file ""+ file + "" = ");
try
{
while (inputFile.hasNext())
{
if (inputFile.hasNextInt())
{
array[i] = inputFile.nextInt();
i++;
}
else
{
inputFile.next();
}
}
}
finally
{
inputFile.close();
}
System.out.println(i);
for (int v = 0; v < i; v++)
{
System.out.printf("array[%d] = %d ", v, array[v]);
}
ArrayList<Integer> arrList = new ArrayList<Integer>(Arrays.asList(array));
}
}
public static <T> boolean sequentialSearch (Iterable<T> collection, T searchKey)
{
Iterator<T> iter = collection.iterator( );
while (iter.hasNext())
{
if (iter.next( ).equals(searchKey))
{
return true;
}
}
return false;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.