Question: Open up a new Java project named Statistics and add the starter code below to it: import java.io.*; import java.util.Scanner; public class Statistics { public
- Open up a new Java project named Statistics and add the starter code below to it:
import java.io.*; import java.util.Scanner; public class Statistics { public static void main(String[] args) throws IOException{
int count = 0;
String word, line;
//rest of code goes here
}
}
-
Now, using Eclipse, create a new empty file called sonnet.txt and copy and paste the below sonnet into your file:
Shall I compare thee to a summers day?
Thou art more lovely and more temperate:
Rough winds do shake the darling buds of May,
And summers lease hath all too short a date;
Sometime too hot the eye of heaven shines,
And often is his gold complexion dimm'd;
And every fair from fair sometime declines,
By chance or natures changing course untrimm'd;
But thy eternal summer shall not fade,
Nor lose possession of that fair thou owst;
Nor shall death brag thou wanderst in his shade,
When in eternal lines to time thou growst:
So long as men can breathe or eyes can see,
So long lives this, and this gives life to thee.
- We are going to write some code to count the number of words and the number of lines in this file.
- Declare two new files at the top of your program:
File infile = new File("sonnet.txt");
File outfile = new File("statistics.txt");
- Also declare a new Scanner and connect it to infile.
- Now, let's write a while loop to count up how many words are in the file.
while (input.hasNext()) {
word = input.next();
count++;
}
- Finally, declare a new PrintWriter, connect it to outfile and print out the number of words contained in the file
output.println("The sonnet has " + count + " words");
- Now, close your input file stream.
input.close();
- Now, we need to count the number of lines in the file.
- For this purpose, we are going to need a new input file stream as we already used the previous one to count the number of words in the file (and we cannot reset the input stream to point to the beginning of the file).
- Add the following code to your program below the statement to close fin:
input = new Scanner(infile);
- Next, we are going to write a while loop to count the number of lines in the file.
count = 0; //reset count variable to 0 while (?????) {
//what goes here?
count++; }
- Write an print statement to print out the number of lines in the sonnet.
The sonnet has 14 lines.
- Finally, close input and output and run your program.
- Note that you should get 114 words and 14 lines.
- Did you get the expected result inside of statistics.txt?
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
