Question

In: Computer Science

Modify the HighArray class to implement the method specified below, which reads integer data from a...

  1. Modify the HighArray class to implement the method specified below, which reads integer data from a file to fill the array. The first integer read from the file should indicate the number of integers contained in the file which can be read into the array.



/**
* Read integers into array from named file. First element in
* file is a count of number of integers contained in the file.
*
* @param fileName   name of file containing integer data
*/
void readIntFile(String fileName)

Note: Use the void insert(int value) method defined in the class to add each integer to the array as it is loaded from the file.

Here is a sample code to read data from file

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;

public class FileReaderSample {

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

        Scanner in = new Scanner(System.in);

        System.out.println("Please enter file name");

      String s = in.nextLine();

        Scanner input = new Scanner(new File(s));

        int[] arr = new int[100];

        int i = 0;

        while (input.hasNextInt()) {

            int next = input.nextInt();

            arr[i] = next;

            i++;

        }// end while

        int nElems = i;

// Print the array contents

       System.out.println("Array Contents");

        for (i = 0; i < nElems; i++) {

            System.out.println(i + "\t" + arr[i]);

        }// end for

    }// end main

Solutions

Expert Solution

Short Summary:

Implemented the program as per requirement

Attached source code and sample output

**************Please do upvote to appreciate our time. Thank you!******************

Source Code:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

/**This class reads integer data from a file to fill the array**/
public class HighArray {

   /**
   * Read integers into array from named file. First element in
   * file is a count of number of integers contained in the file.
   *
   * @param fileName name of file containing integer data
   */
   void readIntFile(String fileName)
   {
       Scanner input =null;
       try {
           //Create file with given File name
           input = new Scanner(new File(fileName));
       } catch (FileNotFoundException e) {
           e.printStackTrace();
       }


       int i = 0;
       int[] arr = null ;
       int arraySize=0;

       while (input.hasNextInt()) {
           //First element in the array is size of the array, as it contains no of elements
           if(i==0)
           {
               arraySize=input.nextInt();
               arr = new int[arraySize];
           }
           else
           {
               //Load array from second element
               int next = input.nextInt();
               //Start from zero'th index
               arr[i-1] = next;
           }
           i++;

       }// end while

       // Print the array contents

       System.out.println("*******Array Contents******");

       for (i = 0; i < arraySize; i++) {

           System.out.println(i + "\t" + arr[i]);

       }// end for
       input.close();
   }// end Method

   //Main method to test the above method
   public static void main(String[] args)
   {
       //Create object for HighArray
       HighArray obj=new HighArray();
       Scanner in=new Scanner(System.in);
       //Get file name input from user
       System.out.print("Please enter the file name: ");
       obj.readIntFile(in.nextLine());
       in.close();
   }
}

Code Screenshot:

Output:

InputFile.txt

Output:


**************Please do upvote to appreciate our time. Thank you!******************


Related Solutions

Complete the class code below and include a method named partition which takes an integer array...
Complete the class code below and include a method named partition which takes an integer array and a partition integer as parameters and then partitions the original array into two new arrays where elements of the first array are all less than or equal to the partition integer and the second array are all greater than the partition integer. The method should print the original array, followed by the lower partition and finally the upper partition. Nothing should be returned...
Design and implement an application that reads an integer value and prints the sum of all...
Design and implement an application that reads an integer value and prints the sum of all even integers between 2 and the input value, inclusive. Print an error message if the input value is less than 2 and prompt accordingly so that the user can enter the right number. Your program file will be called YourLastNameExamQ2
Write a Java program which reads a positive integer from the command line, then displays the...
Write a Java program which reads a positive integer from the command line, then displays the sum of all even values up to and including the value provided, followed by the sum of all odd values up to and including the value provided. validate that the command line argument is an integer greater than 0 to validate the type, you can use Integer.parseInt() with a try/catch for NumberFormatException use one or more for loops to perform the even and odd...
Details: Create a class called CompareArrays that determines if two specified integer arrays are equal. The...
Details: Create a class called CompareArrays that determines if two specified integer arrays are equal. The class should have one static methods: public static boolean compare(int[] arrayOne, int[] arrayTwo) – Which compares the two arrays for equality. The two arrays are considered equal if they are the same size, and contain the same elements in the same order. If they are equal, the method should return true. Otherwise, the method should return false. NOTE: You are not allowed to use...
Write a recursive method to implement Binary Search of a sorted integer array. Signature of method...
Write a recursive method to implement Binary Search of a sorted integer array. Signature of method could be public int BinarySearch(int target, int low, int high)
Write a recursive method to implement Binary Search of a sorted integer array. Signature of method...
Write a recursive method to implement Binary Search of a sorted integer array. Signature of method could be public int BinarySearch(int target, int low, int high)
Modify Example 5.1 to add a ReadAccount method to the BankAccount class that will return a...
Modify Example 5.1 to add a ReadAccount method to the BankAccount class that will return a BankAccountconstructed from data input from the keyboard. Override ReadAccount in SavingsAccount to return an account that refers to a SavingsAccount that you construct, again initializing it with data from the keyboard. Similarly, implement ReadAccount in the CheckingAccount class. Use the following code to test your work. public static void testCode()         {             SavingsAccount savings = new SavingsAccount(100.00, 3.5);             SavingsAccount s = (SavingsAccount)savings.ReadAccount();...
Implement a generic utility to summarize a table of data. In particular, for specified columns, find...
Implement a generic utility to summarize a table of data. In particular, for specified columns, find the minimum, average, and maximum value for each of those columns and print out a nicely-formatted report. Hint: You might want to process one line at a time maintaining, in a dictionary, the running stats for each column. For example: stats = '{'test1': {'min': 80.5, 'sum':845.0, 'max':100.0}, 'test2': {...}, ...etc.' If you also maintain a row counter, you’ll be able to calculate the averages...
Using the provided ChangeCalculator class, implement the recursive method calculateChange(int) which will dispense change for a...
Using the provided ChangeCalculator class, implement the recursive method calculateChange(int) which will dispense change for a given amount of money. The method will display and return the total number of combinations of quarters, dimes, nickels, and pennies that equal the desired amount and all of the combinations as well. Avoid duplication. If you choose to use a data structure, it must be one that we've covered and you must thoroughly justify why it was the best choice (based on run-time...
In Python b) Modify your program that reads 3 grades from the user (and computes the...
In Python b) Modify your program that reads 3 grades from the user (and computes the average and letter grade) so that it uses a while loop to read the 3 grades. In the loop body, you will just read one grade and update other variables appropriately. The loop header will ensure 3 iterations. c) Modify your program in part b so that it asks the user how many grades there are and uses a while loop to read that...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT