I have to:
-store integers read from a file in an array
-prompt users for values to look up in the array
-print out the first index of the requested value
-print not found if the value is not contained in the array
-continue to look up values until the user enters -999
Here is what I have:
-store integers read from a file in an array
-prompt users for values to look up in the array
-print out the first index of the requested value
-print not found if the value is not contained in the array
-continue to look up values until the user enters -999
Here is what I have:
Code:
public class FindValues
{
public static void main(String[] args)
{
int capacity = 100;
int numElem = 0;
Scanner intxt = null;
try
{
File file = new File("data.txt");
intxt = new Scanner(file);
}
catch (FileNotFoundException ex)
{
System.out.println("File not found.");
}
int [] arr = new int [capacity];
while(intxt.hasNextInt() && numElem < capacity)
{
arr[numElem] = intxt.nextInt();
numElem++;
}
intxt.close();
Scanner in = new Scanner(System.in);
System.out.print("Enter a value (or -999 to quit): ");
int i = 0;
while(in.nextInt() != -999)
{
while(in.nextInt() != arr[i])
{
i++;
}
if(in.nextInt() == arr[i])
{
System.out.println(i);
System.out.print("Enter a value (or -999 to quit): ");
i = 0;
}
if(i == numElem)
{
System.out.println("Not found");
System.out.print("Enter a value (or -999 to quit): ");
i = 0;
}
}
System.out.print("Thank you");
}
}
Comment