Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I need to develop a program that would take a inputted file, open and read the f

ID: 3565884 • Letter: I

Question

I need to develop a program that would take a inputted file, open and read the file, save every third line in the file into a 2D dynamic array, then take that array and save it into a new file. Also, the array of word should be saved and printed as one paragraph as the inputted code would only have 1 words per line instead of a full line of words.The programs is to be written in C. Please add plenty of comments so I can follow completely and understand what is going on every step of the way.

Points and ratings to the one with clearest code and plenty of comments for explanation. Thank you, I really appreciate it!!!

Explanation / Answer

Declare arrays in Java programs

You need to come up with a meaningful identifier name to call your array
For example,

Declaring arrays follows the same rules as declaring other types of variables, except that an array declaration always contains [ and ] symbols (referred to as "square brackets" and spoken as "array").
With our examples,

int[ ] testScores;
String[ ] studentNames;
double[ ] temperatureReadings;

Declaring arrays in this manner does not cause Java to automatically allocate space for the 5 test scores, the 10 student names, or the 365 temperature readings. We have not told the Java compiler yet how many elements the array will have.

At this point in the program, the values of the testScores, studentNames, and temperatureReadings arrays are set to null (nothing).

Arrays are objects in Java. Like all objects, we need to allocate memory space for the array object with the new operator.

Instantiate arrays in Java programs

Before we can do anything with an array, we need to allocate memory space for it. That means we need to make a decision about the number of elements it will contain.

Often we do not know the exact size of the array. In cases like this, we normally assume the maximum size so we have enough room for all the elements should we need it.

We allocate memory space for arrays with the new operator
With our previous examples,

// Declare and instantiate 5 test scores
int[ ] testScores;
testScores = new int [5];

// Declare and instantiate 8 student names
String[ ] studentNames;
studentNames = new String [8];

It is also possible to declare and instantiate an array in one line of code

// Declare and instantiate 365 temperature readings
double[ ] temperatureReadings = new double [365];

Use user-defined constants to set the size of an array

It would be considered poor programming style to use a literal numeric value for the size of the array inside the square brackets like 5, 8, or 365.

You should always consider declaring a named constant value and using the named constant as the array size.

final int NUMBER_OF_STUDENTS = 5;
testScores = new int [NUMBER_OF_STUDENTS];

Once created, an array size is fixed and cannot be changed.

Use Java variables to set the size of an array

It is possible that the size of the array be a Java variable as well. Your program could determine the size based on a calculation or user input, and use the int variable when allocating space.

import java.util.Scanner;
...
Scanner keyboard = new Scanner(System.in);

// Declare variables
int numberOfDays;
double [] temperatureReadings;

// Read from the user the number of days to record
System.out.print("How many days? ");
numberOfDays = keyboard.nextInt();

// Instantiate the array
temperatureReadings = new double [numberOfDays];

Explain the default values given to the elements of newly instantiated arrays

When an array is created with new, the elements are of the array are given default values.

Use an Array Initializer List

Sometimes we may want to store a small number of fixed values in an array

For example,

We can combine the declaration, instantiation, and initialization in one step

In our examples,

char [] vowels = {'A', 'E', 'I', 'O', 'U'};
int [] primes = {2, 3, 5, 7, 11, 13, 17, 19};
String [] weekdays = {"Mon", "Tues", "Wed", "Thurs", "Fri"};

Notes:

Know how to access the elements of an array through subscripts

Each element in an array has an index, or subscript, that specifies the position of that element in the array.

With Java, arrays always begin with 0 as the index value referring to the first position, 1 as index for the second position, etc.

To access an element in the array, we use bracket notation, known as subscripting, with the appropriate index value.

For example to assign to the first element in our array testScores the value 95

testScores[0] = 95;

This would be spoken as testScores sub zero is assigned the value 95

In addition to just simple integer literal constants, the index can be an integer variable or expression that evaluates to an int value. The following are also legal ways of referencing array elements.

int index = 2;
testScores[index] = 75;
testScores[index + 1] = 100;
testScores[index - 1] = testScores[index] - 5;

Note:
Going outside the bounds of the array causes a run-time error in your program. For example:

testScores[11] = 75;

causes an error named ArrayIndexOutOfBoundsException and produces the following error message when the code executes:

Using for loops to access all the elements in an array

Quite often we want to access sequentially all the elements in an array.

or example, we want to print all the elements or sum all the elements.

A count-controlled loop is an easy way to systematically visit all the elements.

for (int index = 0; index < 5; index++)
{
System.out.println(testScores[index]);
}

will print all five exam scores to the computer screen, one per line.

Use the .length field to refer to an array's length

Remember: arrays are objects. Java provides a handy public field called length for accessing the length of an array. To simplify program maintenance, you should always refer to the length of your array as .length. The previous loop should be re-written as

for (int index = 0; index < testScores.length; index++)
{
System.out.println(testScores[index]);
}

Use an Enhanced for Loop

Java's enhanced for loop simplifies array processing in read-only mode

int [] primes = {2, 3, 5, 7, 11, 13, 17, 19};

for(int val : primes)
{
System.out.println("The next prime number is " + val);
}

Re-assign Array References and Understand Garbage Collection

An array reference can be assigned to another array of the same type.

// Create and initialize a 10 element array

int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

// Reassign numbers to a new array of size 5

numbers = new int[3];

Line 5 instantiates a new 3 element array for numbers. Since the first (10 element) numbers array no longer has a reference to it, it will be garbage collected.

Make a Copy of an array

The following code does not make a separate copy of array numbers

int[] numbers = {5, 10, 15, 20, 25};

// Incorrect way to copy an array

int[] copyOfNumbers = numbers;

Instead, it creates two array references to the same object in memory.

To make a true copy, you need to copy the individual elements from one array to another.

int[] numbers = {5, 10, 15, 20, 25};
int[] copyOfNumbers = new int[5];

// Copy individual elements one-by-one
for (int i = 0; i < numbers.length; i++) {
copyOfNumbers[i] = numbers[i];
}

Arrays are objects in Java and inherit all the methods of class Object.

Write a Simple ExamScores class Using an Array

To get us started, let us look at a simple Java class that contains an int array as an instance field variable, a no-argument constructor method, and two public instance methods.

public class ExamScores
{
private int[] scores = {99, 97, 85};

// No-argument constructor method
public ExamScores()
{
// do nothing
}

// Display all the score values, one per line
public void displayAll()
{
  for (int index = 0; index < scores.length; index++) {
System.out.println(scores[index]);
  }
}

// Returns the total of the score values
public int sumAll()
{
  int sum = 0;
  for (int score : scores) {
sum = sum + score;
  }
  return sum;
}
}

Unit test our ExamScores class

Unit testing refers to process of systematically testing individual methods one at a time rather than waiting and testing an entire program once it is complete.

We can use jGRASP's Interactions tab to unit test the methods of a class independently of an actively running program.

// Create the exam object
ExamScores exam = new ExamScores()

// Unit test the displayAll method
exam.displayAll()

// Unit test the sumAll method
exam.sumAll()

Note: by not including the semicolon after the method call while using jGRASP's interactions tab, the value returned is displayed immediately after the statement is executed.

Pass Arrays as Arguments to Methods

Arrays are objects. Their references can be passed to methods like any other object reference variable.

As an example, we can add another constructor method for ExamScores to pass in an array argument to initialize the scores field

Note: When we have multiple class methods with the same name but different signatures, we say that the class method is overloaded.

// Constructor method accepts an array of test scores
public ExamScores(int[] array)
{
// Instantiate the scores array to the correct size
this.scores = new int[array.length];

// Copy the values from parameter testScores to scores
for(int index = 0; index < array.length; index++) {
  this.scores[index] = array[index];
}
}

We can use jGRASP's Interactions tab to unit test the new constructor method

int [] newScores = {44, 55, 66,88};
ExamScores exam2 = new ExamScores(newScores);
exam2.displayAll()
exam2.sumAll()

Compare Arrays to See If They Are Equal

The == operator determines only whether array references point to the same array object.

if (array1 == array2)     // Wrong way to compare arrays
//do something

To compare the contents of an array, first make sure they are the same length and then check that each element is the same.

// returns true if scores contains same elements as array
public boolean isEqual (int [] array)
{
  if (this.scores.length != array.length) {
return false;
  }

// if we make it this far, the two arrays have the same length
// Next, compare element by element
  for (int index = 0; index < scores.length; index++) {
if (this.scores[index] != array[index]) {
  return false;
}
  }

// if it this far, they contain the same elements
  return true;
}

Return an Array Reference from a Method

A method can return a reference to an array.

The return type of the method must be declared as an array of the right type.

public double[] getArray()
{
double[] array = { 1.2, 2.3, 4.5, 6.7, 8.9 };
return array;
}

Declare and Use Arrays of Objects

Arrays can contain objects.

ExamScores[] cs111Exams = new ExamScores[4];

Since each array element is an object, they need to be instantiated with the new operator.

for (int index = 0; index < cs111Exams.length; index++) {
cs111Exams[index] = new ExamScores();
}

Work with Arrays of Strings

Arrays are not limited to primitive data. An array of String objects can be created:

String[] names = { "Bill", "Susan", "Steven", "Jean" };

If an initialization list is not provided, the new keyword must be used to create the array:

String[] names = new String[4];
names[0] = "Bill";

String objects have several methods, including:

System.out.println(names[0].toUpperCase());  // Convert first word to upper case
char letter = names[3].charAt(0);     // Get first letter of fourth word

Distinguish between the Array length Field & the String length Method

Arrays have a final field named length. String objects have a method named length().

To display the length of each string held in a String array

for (int index = 0; index < names.length; index++) {
System.out.println(names[index].length());
}

Work with Files and Arrays

Since arrays typically contain a large number of values, input and output files are often used to enter or save the contents of arrays.

To demonstrate, let us set up a main method in a class named Demo. We need to import the Java package java.io.* package to work with input and output files and the Java class Scanner to read in input.

Opening and working with files can cause exceptions to be thrown. Java requires either that your program catches the exception (discussed later in Chapter 10) or that you throw the exception. We will take the second approach by using the keyword throws IOException.

import java.util.Scanner;  // get input from keyboard or files
import java.io.*;   // open and write to files

public class Demo
{   
public static void main(String[] args) throws IOException
{
  
}
}

Use Partially Filled Arrays if the Array Size is Unknown or Varies

If the amount of data that an array must hold is unknown or varies, size the array at the largest expected number of elements and

use an int counting variable to keep track of how many values are stored in the array.

// local variables
String[] names = new String[100];  // largest expected size
int count = 0;   // number of values stored

Read the Contents from a File into an Array

Reading the contents of a file into an array is remarkably similar to reading in values from the keyboard.

Assume we have a file named "values.txt" that contains the following 4 lines.

We can read the values into our partially filled array using File and Scanner objects

// Create File and Scanner objects inside main
File file = new File("values.txt");
Scanner inputFile = new Scanner(file);

// Read in the names from the file
while (inputFile.hasNext() && count < names.length) {
names[count] = inputFile.nextLine();
count++;
}

// Remember to close the file ASAP
inputFile.close();

Save the Contents of an Array to a File

You can save the contents of an array to a text file using the PrintWriter class

PrintWriter outputFile = new PrintWriter("values2.txt");

for (int index = 0; index < count; index++) {
outputFile.println(names[index]);
}
outputFile.close();

Use Command-Line Arguments with the main method

A Java program can receive arguments from the operating system command-line.

The main method has a header that looks like this:

public static void main(String[] args)

The main method receives a String array as a parameter. The array that is passed into the args parameter comes from the operating system command-line.
For example:

To pass arguments to the main method, use the Build menu's Run Augments option

Searching and Sorting Arrays

Since real-world arrays typically hold a lot of values, algorithms for efficient searching and sorting are important.

In most cases, searching for an item in an array returns the index in the array that the item is found. -1 is often used to indicate the item is not found.

Explain how the Sequential Search Algorithm works

A search algorithm is a method of locating a specific item in a larger collection of data.

The sequential search algorithm works by using a loop to sequentially step through an array, comparing each element with the desired search value, and stopping when the desired value is found or the end of the array is encountered.

public class Demo
{
public static int sequentialSearch(int[] array, int desiredValue)
{
  for (int index = 0; index < array.length; index++) {
if (desiredValue == array[index]) {
  return index;
}
  }
  // if we every make it this far, value was not found
  return -1;
}
}

In unit testing the sequential search algorithm, it is important to test boundary values in the array.

Explain how the Selection Sort Algorithm works

Sort algorithms sort the elements of an array in ascending (or descending) order.

The selection sort algorithm is simple but inefficient. It works by looping through an array

public static void selectionSort(int[] array)
{
for (int i = 0; i < array.length-1; i++)
{
  int smallest = i; //assume first element is smallest

  for (int j = i + 1; j < array.length; j++) {
if (array[j] < array[smallest]) {
smallest = j;
}
  }
  // Swap smallest element into position
  int temp = array[i];
array[i] = array[smallest];
array[smallest] = temp;
}
}

Explain how the Binary Search Algorithm works

The binary search algorithm requires an array to be sorted in ascending order.

The general algorithm works by

public static int binarySearch(int[] array, int desiredValue)
{
int firstIndex = 0;
int lastIndex = array.length - 1;
int middleIndex;

while (firstIndex <= lastIndex)
{
middleIndex = (firstIndex + lastIndex) / 2;

  if (desiredValue == array[middleIndex]) {
return middleIndex;
  }
  else if (desiredValue < array[middleIndex]) {
lastIndex = middleIndex - 1;
  }
  else {
firstIndex = middleIndex + 1;
  }
}
// if we every make it this far, value is not found
return -1;
}

Declaring and Accessing Two-Dimensional Arrays

A two-dimensional array is an array of arrays. It can be thought of as having rows and columns.

Declaring a two-dimensional array requires two sets of brackets and two size declarators

// Declare and instantiate a 2-dimensional array
int[][] scores = new int[3][4];

// Accessing elements requires 2 subscripts
scores[2][1] = 95;
scores[2][0] = 100;

Using Loops with Two-Dimensional Arrays

Programs that process two-dimensional arrays can do so with nested loops.

To fill the scores array with random integer values from 0 to 9 we could use a doubly-nested for loop

import java.util.Random;
Random generator = new Random();

for (int row = 0; row < 3; row++)
{
for (int col = 0; col < 4; col++)
{
scores[row][col] = generator.nextInt(10);
}
}

We can use an initializer list to declare and initialize a two-dimensional array

// Declare and initialize a 3-row by-4 column two-dimensional array
int[][] numbers = { {1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10} };

// display the array
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 4; col++) {
  System.out.println(numbers[row][col]);
}
}

Use the length Field with 2-Dimensional Arrays

Two-dimensional arrays are arrays of one-dimensional arrays. The length field of the array gives the number of rows in the array.

Each row has a length constant tells how many columns are in that row.

// Declare and initialize 2-dimensional array
int[][] numbers = { { 1, 2, 3, 4 },
  { 5, 6, 7 },
  { 9, 10, 11, 12, 13 } };

for (int row = 0; row < numbers.length; row++) {
for (int col = 0; col < numbers[row].length; col++) {
  System.out.println(numbers[row][col]);
}
}

When the rows of a two-dimensional array are of different lengths, the array is known as a ragged array.

Sum The Elements of a Two-Dimensional Array

Use nested for loops to sum the contents of 2-dimensional arrays.

// Display the row totals
int rowTotal;
for (int row = 0; row < numbers.length; row++) {
rowTotal = 0;
for (int col = 0; col < numbers[row].length; col++) {
rowTotal += numbers[row][col];
}
System.out.println("Row " + row + ": " + rowTotal);
}

Declare Multi-Dimensional Arrays

Java does not limit the number of dimensions that an array may be. More than three dimensions is hard to visualize, but can be useful in some programming problems.

int [][][] threeD = new int [2][3][4];

Use the ArrayList Class

Similar to an array, an ArrayList allows object storage. Unlike an array, an ArrayList object:

import java.util.ArrayList;

ArrayList nameList = new ArrayList();

// To populate the ArrayList, use the add method
nameList.add("James");
nameList.add("Catherine");

//To get the current size, call the size method
nameList.size();  // returns 2

// To access items in an ArrayList, use the get method
String s = (String) nameList.get(1);