Work with Files in Java: Searching and Replacing Elements of Array

Submitted by: 
Visitors have accessed this post 160 times.

This article is an example of a typical college assignment. This article describes the opening file processes, and resolves some problems relevant to array usage.

Often, students are asked to implement some assignments that are connected with different array algorithms. Another popular task is the reading of data from file. In this article I'll describe an example of assignment, that is connected with files and arrays in Java. For example:

Your task consist of three questions:

  1. Open a file and read data to an array.
  2. Search an element in array
  3. Replace an element in array

For this task we will create a class that will provide user to input the source text file to read double values to an array.

  1. Open a file.
    First step is to ask user to input the name of file. All the input of the user's data is done in the main method. That's why I'll start the review of the project from the main method.The variables that are defined in this method are:
    1. int size,
    2. index;
    3. double searchNumber,
    4. replaceNumber;
    5. String fileName;

    To ask user for file's name and the size of array we have to create a scanner object to input data.The Scanner class methods that are used int the program are

    • String nextLine() - returns inputed double
    • String nextInt() - returns the next integer from console
    • String nextDouble() - returns the next double from console

    The example of this method is:

    1. //create a scanner to read input
    2. Scanner in = new Scanner(;
    3. System.out.println("Enter the file name (for example array.txt)");
    4. fileName = in.nextLine();
    6. System.out.println("Enter the size of array");
    7. size = in.nextInt();
    9. System.out.println("Enter the number for search in array(in format like 5,4)");
    10. searchNumber = in.nextDouble();

    And now, I call a method to open the file, read data from it and search a number in array:

    1. index = searchIndex(fileName,size,searchNumber);

    The searchIndex method has the next implementation:

    1. public static int searchIndex(String fileName,int size, double searchValue){
    2. double[] array;
    3. int index;
    4. array = readFile(fileName,size);
    5. index = searchArray(array,searchValue);
    6. return index;
    7. }

    It declares an array of doubles and the, the readFile method returns the values that are stored in the txt file to array variable. The readFile method opens a file in the next way:

    1. //method that reads the file
    2. //parameters are file name and size of array
    3. //return value - array of doubles from file
    4. public static double[] readFile(String fileName,int size){
    5. double [] result;
    6. result = new double[size];
    7. //scanner class used to read the file
    8. Scanner scan;
    9. File file = new File(fileName);
    10. try {
    11. scan = new Scanner(file);
    12. int i = 0;
    13. while(scan.hasNextDouble()&&i<size){
    14. result[i] = scan.nextDouble();
    15. ++i;
    16. }
    17. scan.close();
    18. } catch (FileNotFoundException e1) {
    19. System.out.println("can't open file");
    20. System.exit(0);
    21. }
    22. return result;
    23. }

    The first step is to initialize the array of returned values. After this you can try to read data from file. The process of reading data from file can throw exception. So, you always need to surround it with try/catch block to handle exceptions. So, the reading of double values is performed while the file has double values and the array is not full. This method returns the array of doubles, that is used in the next steps.

  2. Searching the index of an element in array
    The next step is to search the index of an element, inputted by user, in the array of doubles. For this purpose searchArray(array,searchValue); is called. Let's take a look on searchArray method implementation:
    1. //a method to find searhNumber index in array
    2. //if the element is found - returns the index of the element
    3. //if there is no element in array returns -1
    4. public static int searchArray(double[] array,double searchNumber){
    5. for(int i = 0; i != array.length; ++i){
    6. if(array[i]==searchNumber)
    7. return i;
    8. }
    9. return -1;

    It's really simple and this method traverse the array and compare elements of the array to the searched value;
    An important moment of the assignment class is the fact, that the results of the question are printed by the special method printResult
    The questions have different types of answer, that's why the same name of methods is used. The difference is only in the list of arguments:

    1. public static void printResult(int numQuestion,String question, int result){
    2. System.out.println("Question " + numQuestion +" Answer");
    3. System.out.println(question + " " + result);
    4. }
    5. public static void printResult(int numQuestion,String notFound){
    6. System.out.println("Question " + numQuestion +" Answer");
    7. System.out.println(notFound);
    8. }
    9. public static void printResult(int numQuestion,double[] array){
    10. System.out.println("Question " + numQuestion +" Answer");
    11. for(int i = 0; i != array.length; ++i){
    12. System.out.format("%7.2f", array[i]);
    13. }
    14. }

    When we obtained the index of searched element, we can print the result of the search:

    1. printIndex(index,searchNumber);
  3. Replacing the element in array with new value
    The next step is to replace the element of array by another element. For this you have to ask user to input the value that is replaced and the new value:
    1. double[] newArray = replaceElements(readFile(fileName,size),searchNumber,replaceNumber);

    When you call this method, you need to pass an array of double to it as the first argument. It's done by readFile(fileName,size) method, that return an array of double, read from file.
    The replaceElements method returns a new array with the modifications, that are made. The replacing of elements consists of 2 part : find replaced element and replace it with new element:

    1. public static double[] replaceElements(double[] array,double find, double replace){
    2. for(int i = 0 ; i!=array.length; ++i){
    3. if(array[i]==find)
    4. array[i] = replace;
    5. }
    6. return array;
    7. }

The data in array.txt:

  1. 2.0 7.0 4.2 3.1 9.4 2.4
  2. -5.7 8.1 9.2 11.9 27.1 0.0 12.7
  3. 15.1 4.02 7.65 84.21 1.1 12.1 21.1

The output of the program is:

Enter the file name (for example array.txt)
Enter the size of array
Enter the number for search in array(in format like 5,4)
Question 1 Answer
The index of element 11.9 is 9
Enter the number to be replaced in array (in format like 5,4)
Enter the new value of replaced number (in format like 5,4)
Question 2 Answer
2,00 7,00 2,12 3,10 9,40 2,40 -5,70 8,10 9,20 11,90

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.