
Patrick B. answered 04/25/21
Math and computer tutor/teacher
a couple of compile errors, first of all... unbalanced parenthesis and a missing }
the main problem is that you do not know how many friends' names are in the file...
You are assuming there are 10 based on the size of the array...
If the file has MORE than 10 names, you are going to trash the array...
Here are the options:
(1) Stop the reading of the input file after 10 iterations, as I have done below.
I declared the constant MAX_FRIENDS = 10; which is used to stop the while loop;
(2) change the input file so that the # of friends is the first line and THEN the array of friends names.
that way you have the opportunity to allocate the array of EXACTLY the correct size;
Finally the linear search logic had to be redone. The strings must be trimmed of leading and
trailing whitespaces and must be compared with the String.compareTo() method.
NEVER USE == when comparing strings.
Also , a boolean flag must be set when a match is found, so as to break out of the for-loop,
OR report that the name is NOT found in the array
/*******************************************/
import java.io.*;
import java.util.*;
class Main
{
public static final int MAX_FRIENDS = 10;
public static void main(String[] args) throws FileNotFoundException{
String [] friends = new String[Main.MAX_FRIENDS];
try
{
fillArray(friends);
findAFriend(friends);
}
catch (Exception ex)
{
System.out.println(" Error opening and/or reading input file ");
}
}
public static void findAFriend(String [] friends)
{
Scanner console = new Scanner(System.in);
System.out.print("Which friend are you looking for? ");
String f = console.next();
boolean found_flag=false;
for (int i=0; i<friends.length;i++)
{
String friendNameFromArray = friends[i].trim();
String targetFriendName = f.trim();
if (friendNameFromArray.compareTo(targetFriendName)==0)
{
System.out.println("Found your friend "+f);
found_flag=true;
}
} //for
if (!found_flag)
{
System.out.println("Friend " + f + " not found ");
}
}
public static void fillArray(String [] friends) throws FileNotFoundException
{
int index=0;
Scanner input = new Scanner(new File ("Friends.txt"));
while (input.hasNextLine()) //unbalanced parenthesis here!!!
{
friends[index]= input.nextLine();
index++;
if (index>=Main.MAX_FRIENDS) { break; }
}
}
} //missing } for the class!!!