Question

The following code uses a Scanner object to read a text file called dogYears.txt. Notice that...

The following code uses a Scanner object to read a text file called dogYears.txt. Notice that each line of this file contains a dog's name followed by an age. The program then outputs this data to the console. The output looks like this:

Tippy 2
Rex 7
Desdemona 5

1. Your task is to use the Scanner methods that will initialize the variables name1, name2, name3, age1, age2, age3 so that the execution of the three println statements below will result in the desired output.

  String name1, name2, name3;
  int age1, age2, age3;
  Scanner inputData = new Scanner(new FileReader("dogYears.txt"));

//code here

System.out.println(name1+" "+age1);
  System.out.println(name2+" "+age2);
  System.out.println(name3+" "+age3);

2. Complete the Java program below so that it reads the text file dogNames.txt and writes its contents to another text file, "doggoneData.txt".

The file dogNames.txt contains just the single word "Tippy", so the output in "doggoneData.txt" should simply look like this:

Tippy

Your task is to complete the code below by using the variable name along with the appropriate Scanner and PrintWriter methods.

  String name;
  Scanner inputFile = new Scanner(new FileReader("dogNames.txt"));   
  PrintWriter outputFile = new PrintWriter("doggoneData.txt");

//code here

inputFile.close();
  outputFile.close();

3. Complete the Java program below so that it reads the text file dogYears.txt and writes its contents to another text file "doggoneData.txt". Here the input file gives ages in dog years, and the output file reports these figures in human years (so Tippy is 2 in the input file, and 14 - 7 times older - in the output file.)

The output in the file "doggoneData.txt", which gives dog ages in human years, should be formatted like this:

Tippy 14
Rex 49
Desdemona 35

Your task is to complete the code below by using the appropriate Scanner and PrintWriter methods.

  String name1, name2, name3;
  int age1, age2, age3;
  Scanner inputFile = new Scanner(new FileReader("dogYears.txt"));   
  PrintWriter outputFile = new PrintWriter("doggoneData.txt");   

//code here

inputFile.close();
  outputFile.close();

4. Suppose an external file is made up entirely of integers. In the model we've been using in this unit, the file is actually read in, line by line, as a sequence of Strings. Use String method split inside processLine() to produce individual tokens that look like numbers, but are actually Strings that are composed of digits. To convert each token from String format to integer format, you need to use the static parseInt() method from the Integer class. Thus

int birthYear = Integer.parseInt("1983");

correctly stores the integer 1983 into the birthYear integer variable.

For this assignment you should create a complete processLine method in the EchoSum class, so that it transforms each number in each line to integer format, and then sums the entries on the line and prints their sum on a separate line. For example, if the external text file looks like this:

1 2 3 4 
3 4 7 1 11
2 3



your program should display this:

10
26
5


import java.io.*;

public class EchoSum extends Echo
{

  public EchoSum (String datafile) throws IOException
  {
    super(datafile);
  }

  // Prints the sum of each line.
  public void processLine(String line){

//code here

} //end method
} //end class

5. For this problem we extend the Echo class to a class called EchoNoSpace. Here the external text file is written to the console as before, but now all spaces are removed first before lines are displayed. Thus a line like

The best things in life are free

becomes

Thebestthingsinlifearefree

The code for doing this uses split from the String class. The links below give the classes that participate in the solution, and the answer block below provides the implementation for the processLine() method in that derived class.

The EchoNoSpace class has an addtional integer attribute, wordCount, which is initialized to 0 in the class constructor. After the file has been processed, this variable should hold the exact number of words (tokens) in the file. The EchoTester code at the link below reports this value as follows:

System.out.println("wordCount: " + e.getWordCount());

For this assignment, edit the processLine() code in the answer box so that the EchoTester's main() method reports the correct value for the number of words in the file. Important: your code should count non-empty words only. Remember that split may place empty strings - strings of length 0 - in the array words, and thus your code must be able to ignore such entries.

import java.io.*;

public class EchoNoSpace extends Echo
{

  // the number of the words counted
  private int wordCount;

  public EchoNoSpace (String datafile) throws IOException
  {
    super( datafile);
    wordCount=0;
  }

  // Prints the given line without any spaces.
  // Overrides the processLine method in Echo class
  public void processLine(String line){

String result = "";

String[] words = line.split(" ");

for(String w : words)

{

result = result + w;

}

System.out.println(result);

}

  // returns the number of words in the file
  public int getWordCount(){
    return wordCount;
  } //end method
} //end class

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Task 1

code


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


public class Main {

public static void main(String[] args)
{
  
try
{
String name1, name2, name3;
int age1, age2, age3;
Scanner inputData = new Scanner(new FileReader("dogYears.txt"));
name1=inputData.next();
age1=inputData.nextInt();
name2=inputData.next();
age2=inputData.nextInt();
name3=inputData.next();
age3=inputData.nextInt();
  
System.out.println(name1+" "+age1);
System.out.println(name2+" "+age2);
System.out.println(name3+" "+age3);
}
catch (FileNotFoundException e) //if inputData name is not fount then it will print the message
{
System.out.println("File is not found!");
}
}
  
}

output

o Read File simple - NetBeans IDE 8.0.1 Eile Edit View Navigate Source Refactor Run Debug Profile Team Tools Window Help 200

Task 2


import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.Scanner;


public class Main1
{
public static void main(String[] args) throws FileNotFoundException
{
String name;
Scanner inputFile = new Scanner(new FileReader("dogNames.txt"));   
PrintWriter outputFile = new PrintWriter("doggoneData.txt");
//code here
name=inputFile.next();
outputFile.write(name);
inputFile.close();
outputFile.close();
}
}

output

- 0 doggoneData - Notepad File Edit Format View Tippy Help Ln 1, Col 1 4 Type here to search 100% R A x PENG 11:48 31-08-2019

Task 3

code


import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.Scanner;


public class Main2 {

public static void main(String[] args) throws FileNotFoundException
{
String name1, name2, name3;
int age1, age2, age3;
Scanner inputFile = new Scanner(new FileReader("dogYears.txt"));   
PrintWriter outputFile = new PrintWriter("doggoneData.txt");   
name1=inputFile.next();
age1=inputFile.nextInt();
name2=inputFile.next();
age2=inputFile.nextInt();
name3=inputFile.next();
age3=inputFile.nextInt();
outputFile.write(name1+" "+age1*7+"\r\n");
outputFile.write(name2+" "+age2*7+"\r\n");
outputFile.write(name3+" "+age3*7+"\r\n");
inputFile.close();
outputFile.close();
}
  
}
output

- 0 Help doggoneData - Notepad File Edit Format View Tippy 14 Rex 49 Desdemona 35 Ln 1, Col 1 4 Type here to search 9 100% op

for task 4 the Eco class needed you did not provide the Eco class. so I cant do the task 4.

If you have any query regarding the code please ask me in the comment i am here for help you. Please do not direct thumbs down just ask if you have any query. And if you like my work then please appreciates with up vote. Thank You.

Add a comment
Know the answer?
Add Answer to:
The following code uses a Scanner object to read a text file called dogYears.txt. Notice that...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • composed the following java code to read a string from a text file but receiving compiling...

    composed the following java code to read a string from a text file but receiving compiling errors. The text file is MyNumData.txt. Included the original java script that generated the output file. Shown also in the required output results after running the java program. I can't seem to search for the string and output the results. Any assistance will be greatly appreciated. import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; public class Main {   public static void main(String[] args) {     System.out.print("Enter the...

  • Trying to practice this assignment Argument list: the *yahoonews.txt Data file: yahoonews.txt Wr...

    Trying to practice this assignment Argument list: the *yahoonews.txt Data file: yahoonews.txt Write a program named WordCount.java, in this program, implement two static methods as specified below: public static int countWord(Sting word, String str) this method counts the number of occurrence of the word in the String (str) public static int countWord(String word, File file) This method counts the number of occurrence of the word in the file. Ignore case in the word. Possible punctuation and symbals in the file...

  • QUESTION The ReadFile class opens and reads a text file. The WriteFile class opens and writes...

    QUESTION The ReadFile class opens and reads a text file. The WriteFile class opens and writes to a file. Compile and run these programs. There are several ways to read/write text files. The examples shown here are just one way of achieving this. Look at the API for the BufferedReader class. The readline() method is a simple way to read the text file line by line. It returns null when the end of the file has been reached. https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html Look...

  • Assignment 3: Word Frequencies Prepare a text file that contains text to analyze. It could be...

    Assignment 3: Word Frequencies Prepare a text file that contains text to analyze. It could be song lyrics to your favorite song. With your code, you’ll read from the text file and capture the data into a data structure. Using a data structure, write the code to count the appearance of each unique word in the lyrics. Print out a word frequency list. Example of the word frequency list: 100: frog 94: dog 43: cog 20: bog Advice: You can...

  • Please help me fix my errors. I would like to read and write the text file...

    Please help me fix my errors. I would like to read and write the text file in java. my function part do not have errors. below is my code import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.FileWriter; import java.io.IOException; public class LinkedList {    Node head;    class Node    {        int data;        Node next;       Node(int d)        {            data = d;            next = null;        }    }    void printMiddle()    {        Node slow_ptr...

  • Ask the user for the name of a file and a word. Using the FileStats class,...

    Ask the user for the name of a file and a word. Using the FileStats class, show how many lines the file has and how many lines contain the text. Standard Input                 Files in the same directory romeo-and-juliet.txt the romeo-and-juliet.txt Required Output Enter a filename\n romeo-and-juliet.txt has 5268 lines\n Enter some text\n 1137 line(s) contain "the"\n Your Program's Output Enter a filename\n romeo-and-juliet.txt has 5268 lines\n Enter some text\n 553 line(s) contain "the"\n (Your output is too short.) My...

  • JAVA Code: Complete the program that reads from a text file and counts the occurrence of...

    JAVA Code: Complete the program that reads from a text file and counts the occurrence of each letter of the English alphabet. The given code already opens a specified text file and reads in the text one line at a time to a temporary String. Your task is to go through that String and count the occurrence of the letters and then print out the final tally of each letter (i.e., how many 'a's?, how many 'b's?, etc.) You can...

  • I am trying to read from a file with with text as follows and I am...

    I am trying to read from a file with with text as follows and I am not sure why my code is not working. DHH-2180 110.25 TOB-6851 -258.45 JNO-1438 375.95 CS 145 Computer Science II IPO-5410 834.15 PWV-5792 793.00 Here is a description of what the class must do: AccountFileIO 1. Create a class called AccountFileIO in the uwstout.cs145.labs.lab02 package. (This is a capital i then a capital o for input/output.) a. This class will read data from a file...

  • I need help running this code. import java.util.*; import java.io.*; public class wordcount2 {     public...

    I need help running this code. import java.util.*; import java.io.*; public class wordcount2 {     public static void main(String[] args) {         if (args.length !=1) {             System.out.println(                                "Usage: java wordcount2 fullfilename");             System.exit(1);         }                 String filename = args[0];               // Create a tree map to hold words as key and count as value         Map<String, Integer> treeMap = new TreeMap<String, Integer>();                 try {             @SuppressWarnings("resource")             Scanner input = new Scanner(new File(filename));...

  • How to write a Java file out that that reads from numbers.txt with these numbers 2...

    How to write a Java file out that that reads from numbers.txt with these numbers 2 6 7 9 5 4 3 8 0 1 6 8 2 3 and write to a file called totalSum.txt that looks like: 2+6+7+9=24 and so on using this code import java.io.*; import java.util.Scanner; public class FileScanner {    public static void main(String[] args)    {        /* For Homework! Tokens*/        Scanner file = null;        PrintWriter fout= null;   ...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT