67.5k views
3 votes
Alright, ladies and gentlemen, this Computer Science review question has me stumped. The directions are as follows:

This question involves a class named TextFile that represents a text file.
public class TextFile
{
private String fileName;
private ArrayList words;
// constructors not shown

// postcondition: returns the number of bytes in this file
public int fileSize()
{
}
// precondition: 0 <= index < words.size()
// postcondition: removes numWords words from the words ArrayList beginning at
// index.
public void deleteWords(int index, int numWords)
{
}
// precondition: 0 <= index <= words.size()
// postcondition: adds elements from newWords array to words ArrayList beginning
// at index.
pub lic voidaddWords(int index, String[] newWords)
{
}
// other methods not shown
}
Complete the fileSize() method. The fileSize() is computed in bytes. In a text file, each character in each word counts as one byte. In addition, there is a space in between each word in the words ArrayList, and each of those spaces also counts as one byte.

For example, suppose the words ArrayList stores the following words:
{ Mary had a little lamb; its fleece was white as snow. }
The fileSize() method would compute 4 + 3 + 1 + 6 + 5 + 4 + 6 + 3 + 5 + 2 + 5 as the sum of the lengths of each String in the ArrayList. The value returned would be this sum plus 10, because there would also be 10 spaces in between the 11 words.
Complete the fileSize() method below:
// postcondition: returns the number of bytes in this file
public int fileSize()
{

}

After looking over the instructions, I'm practically brainless in regards to where I'm supposed to go from here. I need to return the results of the fileSize method and I have no idea how to do it. If anyone could help me out, it'd be greatly appreciated!

1 Answer

4 votes

Answer:

The function is simple, seeing the condition, as it is the array list and not array. An array list provides a size method, and this can be much awesome here.

public int fileSize()

{

TextFile t1=new Textfile();

int size= t1.words.size();

return size;

}

Step-by-step explanation:

We are creating an instance of a class here for working on word ArrayList. The ArrayList has a size method in java. And hence we can use that above to find the size of the ArrayList. Also remember words is a private varianle here, and hence it should be called from within the class,to ensure its within the scope.

User Ryan Kennedy
by
4.7k points