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

Sample Question 4.1: Suppose that a data file named test3 has these contents: 37

ID: 3834105 • Letter: S

Question

Sample Question 4.1: Suppose that a data file named test3 has these contents:

37 cat 5.2 ape 4 eleven 42

Trace execution of the program listed below, beginning with main, showing contents of memory, output to the console, and the contents of the file out3:

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

public class Cat1f {             

   public static void main(String[] args) {    

      try {   

         Scanner input = new Scanner(new File("test3"));   

         PrintWriter output = new PrintWriter("out3");   

         do {       

            String s = "";                    try {           

               s = input.next();           

               int x = Integer.parseInt(s);           

               output.println(x);        

            }

            catch(Exception e) {                           System.out.println(s);       

            }   

         } while(input.hasNext());   

         input.close();             output.close();

      }

      catch(Exception e2) {   

         System.out.println("File not found");

      }

   }

}

Explanation / Answer

1) Starting from main() the program counter will come to the try block. i.e., at

Scanner input = new Scanner(new File("test3"));

If the file exist the program will open the file after that at next line it will create another file named out3

After doing above steps the program will come to the body of while part (i.e., in do part) and will read the contents of file word by word (notice the keyword next() )

by this code i.e.,  s = input.next(); the word will be saved into the variable s. After then counter will come to the 2nd line i.e., at int x = Integer.parseInt(s); storing the numbers to the variable x. After doing this task the program counter will come to the next line i.e., at output.println(x); printing only the numbers to the output ile out3 at new line (notice the println). Please note that not every word in the file is a number hence whenever a word is encountered at line Integer.parseInt(s); the program throws an exception which is being caught at next line, now notice in the exception part i.e., in catch block there is a line i.e., System.out.println(s); On coming to this line the program prints each word to the console at new line, that was saved in the variable s . And this process continues untill all the words in the file are read successfully. Hence ,

Output to the console is

cat
5.2
ape
eleven

And contents of the file out3 is.

37
4
42

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote