Artem H.

asked • 04/25/21

a program that reads names from a file  However, the program does not work as expected. It gives an ArrayOutOfBounds exception. Correct this without changing the size of the array.


Here is a program that reads names from a file Friends-1.txt  download  and stores them in an array called friends.

It then asks the user for a name and searches the array for the friend. If it finds the name, it prints it, other wise it says "friend not found".

Here is the expected output.

Output 1  

O1.PNG  

However, the program does not work as expected. It gives an ArrayOutOfBounds exception.

Correct this without changing the size of the array

If that error were corrected, then even if it finds the friend, it would say "friend found" as well as "friend not found"


Here is the erroneous program. Denote the area where the errors occur. Explain the errors and your fixes.(10 points)
Replace the faulty lines with your correct code.(10 points) Do not rewrite the entire program.

import java.io.*;

import java.util.*;

class Main {

public static void main(String[] args) throws FileNotFoundException{

String [] friends = new String[10];

fillArray(friends);

findAFriend(friends);

}
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();

for (int i=0;i<friends.length;i++){

if (friends[i]==(f))

{System.out.println("Found your friend "+f);

}

}

System.out.println("Friend not found ");

}

public static void fillArray(String [] friends) throws FileNotFoundException{

int index=0;

Scanner input = new Scanner(new File ("Friends.txt"));

while (input.hasNextLine() {

friends[index]= input.nextLine();

index++;

}

}


1 Expert Answer

By:

Patrick B. answered • 04/25/21

Tutor
4.7 (31)

Math and computer tutor/teacher

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.