SlideShare a Scribd company logo
1 of 7
Download to read offline
For the following I have finished most of this question but am having problem with on method. I
just need the void copyNumbers method filled out. The commented out sections describe what it
needs to do. I have it started. Just need it finished.
package reading_with_exceptions;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Reading_With_Exceptions {
// 1.) Create a Scanner from the inputFilename. Catch exceptions from errors.
// 2.) Read the first String from the file and use it to create a PrintStream
// catching appropriate exceptions
// 3.) Using hasNextInt and nextInt, carefully read the count integer.
// I recommend -1 for a count value if it is bad to indicate reading ALL
// 4.) Use copyNumbers method described below to complete the job
// 5.) Close Scanner and PrintStream objects
// 6.) Call printToScreen to copy the output file to the screen
void process(String inputFilename) {
int number_to_read = 0;
try {
Scanner input = new Scanner(inputFilename);
String outputFilename = input.next();
PrintStream os = new PrintStream(new FileOutputStream(outputFilename));
if ( input.hasNextInt()) {
number_to_read = input.nextInt();
}else {
number_to_read = -1;
}
copyNumbers(input, os, number_to_read);
input.close();
os.close();
printToScreen(outputFilename);
}catch (FileNotFoundException e) {
System.out.println("Cannot find file: " + e);
return;
}
}
// The following routine is called to complete the job of copying integers to
// the output file:
// scan - a Scanner object to copy integers from
// ps - A PrintStream to write the integers to
// numIntsToRead - number of integers to read. A value of -1 ==> read all integers
void copyNumbers(Scanner scan, PrintStream ps, int numIntsToRead) {
// hasNext() can be used to see if the scan object still has data
// Note that hasNextInt() can be used to see if an integer is present
// nextInt() will read an integer
// next() can be used to skip over bad integers
while (scan.hasNext()) {
if (numIntsToRead < 0) {
//print out a complaint message and then read as many integers as you find.
scan.nextInt();
}
if (!scan.hasNextInt()) {
// print a complaint message and skip over the data
scan.next();
}
if ( scan < numIntsToRead) {
// complain but do not abort
}
}
}
public static void main(String[] args) {
Reading_With_Exceptions rwe = new Reading_With_Exceptions();
for (int i=0; i < args.length; i++) {
System.out.println("  =========== Processing "+ args[i] + " ========== ");
rwe.process(args[i]);
}
}
// For the last step, we Copy the contents of the file to the screen
private void printToScreen(String filename) {
Scanner scan = null;
try {
FileInputStream fis = new FileInputStream(filename);
scan = new Scanner(fis);
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
}
catch (FileNotFoundException e) {
System.out.println("printToScreen: can't open: " + filename);
}
finally {
if (scan != null)
scan.close();
}
}// end of printToScreen
}
Solution
Please follow the code and comments for description :
CODE :
import java.io.File; // required imports for the code
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Scanner;
public class Reading_With_Exceptions { // class that runs the code
// 1.) Create a Scanner from the inputFilename. Catch exceptions from errors.
// 2.) Read the first String from the file and use it to create a PrintStream
// catching appropriate exceptions
// 3.) Using hasNextInt and nextInt, carefully read the count integer.
// I recommend -1 for a count value if it is bad to indicate reading ALL
// 4.) Use copyNumbers method described below to complete the job
// 5.) Close Scanner and PrintStream objects
// 6.) Call printToScreen to copy the output file to the screen
void process(String inputFilename) { // method that does the processing of the file
int number_to_read = 0;
File file = new File(inputFilename); // reading it to a file as the input form is a string name
try {
String outputFilename;
PrintStream os;
try (Scanner input = new Scanner(file)) { // checking or reading the unput file
outputFilename = input.nextLine();
os = new PrintStream(new FileOutputStream(outputFilename)); // saving the firstline to a output
filename
if (input.hasNextInt()) { // checking for the data in the file
number_to_read = input.nextInt();
} else {
number_to_read = -1;
}
copyNumbers(input, os, number_to_read);
}
os.close(); // closing the stream class
printToScreen(outputFilename); // calling the method to print the data from the output file
} catch (FileNotFoundException e) { // catching the exceptions
System.out.println("Cannot find file: " + e);
}
}
// The following routine is called to complete the job of copying integers to
// the output file:
// scan - a Scanner object to copy integers from
// ps - A PrintStream to write the integers to
// numIntsToRead - number of integers to read. A value of -1 ==> read all integers
void copyNumbers(Scanner scan, PrintStream ps, int numIntsToRead) { // method to copy the
data to the file
// hasNext() can be used to see if the scan object still has data
// Note that hasNextInt() can be used to see if an integer is present
// nextInt() will read an integer
// next() can be used to skip over bad integers
while (scan.hasNext()) { //iterating over the loop to read the data
if (numIntsToRead < 0) {
//print out a complaint message and then read as many integers as you find.
System.out.println("A Message Indicating that reading all the data from the file.");
while(scan.hasNextInt()){
int readNum = scan.nextInt();
ps.print(readNum);
ps.print(" ");
ps.flush();
System.out.println(" Completed Reading the Data.! ");
}
}
if (!scan.hasNextInt()) {
// print a complaint message and skip over the data
System.out.println(" No Data Present in the File to Read.! ");
scan.nextLine();
}
}
}
public static void main(String[] args) { // driver method
Reading_With_Exceptions rwe = new Reading_With_Exceptions();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the Number of Files : "); // prompt for the user the enter the total
number of files
int num = sc.nextInt();
System.out.println("Enter the FileName : "); // prompt to enter the file name with extension
String file[] = new String[num];
sc.nextLine();
for (int x = 0; x < num; x++) {
String filename = sc.nextLine();
file[x] = filename;
}
for (String files : file) {
System.out.println("  =========== Processing " + files + " ========== ");
rwe.process(files); //calling the method to process the data files
}
}
// For the last step, we Copy the contents of the file to the screen
private void printToScreen(String filename) { // method to print the data to the screen
Scanner scan = null;
try {
FileInputStream fis = new FileInputStream(filename);
scan = new Scanner(fis);
System.out.println("Data Present in the Output File is :  ");
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
} catch (FileNotFoundException e) {
System.out.println("printToScreen: can't open: " + filename);
} finally {
if (scan != null) {
scan.close();
}
}
}// end of printToScreen
}
OUTPUT :
Enter the Number of Files :
1
Enter the FileName :
input.txt
=========== Processing input.txt ==========
A Message Indicating that reading all the data from the file.
Completed Reading the Data.!
No Data Present in the File to Read.!
Data Present in the Output File is :
102
3
4
5
6
7
8
9
10
Hope this is helpful.

More Related Content

Similar to For the following I have finished most of this question but am havin.pdf

Complete the following Java code such that it opens a file named Fruit.docx
Complete the following Java code such that it opens a file named Fruit.docxComplete the following Java code such that it opens a file named Fruit.docx
Complete the following Java code such that it opens a file named Fruit.docxljohn878
 
System Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbs
System Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbsSystem Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbs
System Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbsashukiller7
 
Java practical
Java practicalJava practical
Java practicalwilliam otto
 
Hi, I need help with a java programming project. specifically practi.pdf
Hi, I need help with a java programming project. specifically practi.pdfHi, I need help with a java programming project. specifically practi.pdf
Hi, I need help with a java programming project. specifically practi.pdfPRATIKSINHA7304
 
source code which create file and write into it
source code which create file and write into itsource code which create file and write into it
source code which create file and write into itmelakusisay507
 
C++ - UNIT_-_V.pptx which contains details about File Concepts
C++  - UNIT_-_V.pptx which contains details about File ConceptsC++  - UNIT_-_V.pptx which contains details about File Concepts
C++ - UNIT_-_V.pptx which contains details about File ConceptsANUSUYA S
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdfSudhanshiBakre1
 
import java.util.Scanner;Henry Cutler ID 1234 7202.docx
import java.util.Scanner;Henry Cutler ID 1234  7202.docximport java.util.Scanner;Henry Cutler ID 1234  7202.docx
import java.util.Scanner;Henry Cutler ID 1234 7202.docxwilcockiris
 
PAGE 1Input output for a file tutorialStreams and File IOI.docx
PAGE  1Input output for a file tutorialStreams and File IOI.docxPAGE  1Input output for a file tutorialStreams and File IOI.docx
PAGE 1Input output for a file tutorialStreams and File IOI.docxalfred4lewis58146
 
Can someone put this code in a zip file. I tried running it last tim.pdf
Can someone put this code in a zip file. I tried running it last tim.pdfCan someone put this code in a zip file. I tried running it last tim.pdf
Can someone put this code in a zip file. I tried running it last tim.pdffedosys
 
Integration Project Inspection 3
Integration Project Inspection 3Integration Project Inspection 3
Integration Project Inspection 3Dillon Lee
 
2. Write a program which will open an input file and write to an out.pdf
2. Write a program which will open an input file and write to an out.pdf2. Write a program which will open an input file and write to an out.pdf
2. Write a program which will open an input file and write to an out.pdfrbjain2007
 
Systemcall1
Systemcall1Systemcall1
Systemcall1pavimalpani
 
Introduzione al TDD
Introduzione al TDDIntroduzione al TDD
Introduzione al TDDAndrea Francia
 

Similar to For the following I have finished most of this question but am havin.pdf (20)

file.ppt
file.pptfile.ppt
file.ppt
 
15. text files
15. text files15. text files
15. text files
 
srgoc
srgocsrgoc
srgoc
 
Complete the following Java code such that it opens a file named Fruit.docx
Complete the following Java code such that it opens a file named Fruit.docxComplete the following Java code such that it opens a file named Fruit.docx
Complete the following Java code such that it opens a file named Fruit.docx
 
System Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbs
System Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbsSystem Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbs
System Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbs
 
Java practical
Java practicalJava practical
Java practical
 
Hi, I need help with a java programming project. specifically practi.pdf
Hi, I need help with a java programming project. specifically practi.pdfHi, I need help with a java programming project. specifically practi.pdf
Hi, I need help with a java programming project. specifically practi.pdf
 
source code which create file and write into it
source code which create file and write into itsource code which create file and write into it
source code which create file and write into it
 
C++ - UNIT_-_V.pptx which contains details about File Concepts
C++  - UNIT_-_V.pptx which contains details about File ConceptsC++  - UNIT_-_V.pptx which contains details about File Concepts
C++ - UNIT_-_V.pptx which contains details about File Concepts
 
CORE JAVA-1
CORE JAVA-1CORE JAVA-1
CORE JAVA-1
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
 
import java.util.Scanner;Henry Cutler ID 1234 7202.docx
import java.util.Scanner;Henry Cutler ID 1234  7202.docximport java.util.Scanner;Henry Cutler ID 1234  7202.docx
import java.util.Scanner;Henry Cutler ID 1234 7202.docx
 
PAGE 1Input output for a file tutorialStreams and File IOI.docx
PAGE  1Input output for a file tutorialStreams and File IOI.docxPAGE  1Input output for a file tutorialStreams and File IOI.docx
PAGE 1Input output for a file tutorialStreams and File IOI.docx
 
Can someone put this code in a zip file. I tried running it last tim.pdf
Can someone put this code in a zip file. I tried running it last tim.pdfCan someone put this code in a zip file. I tried running it last tim.pdf
Can someone put this code in a zip file. I tried running it last tim.pdf
 
Integration Project Inspection 3
Integration Project Inspection 3Integration Project Inspection 3
Integration Project Inspection 3
 
Java 3 Computer Science.pptx
Java 3 Computer Science.pptxJava 3 Computer Science.pptx
Java 3 Computer Science.pptx
 
IO and threads Java
IO and threads JavaIO and threads Java
IO and threads Java
 
2. Write a program which will open an input file and write to an out.pdf
2. Write a program which will open an input file and write to an out.pdf2. Write a program which will open an input file and write to an out.pdf
2. Write a program which will open an input file and write to an out.pdf
 
Systemcall1
Systemcall1Systemcall1
Systemcall1
 
Introduzione al TDD
Introduzione al TDDIntroduzione al TDD
Introduzione al TDD
 

More from arihantplastictanksh

If a protein is destined to be a part of the cell membrane or to lea.pdf
If a protein is destined to be a part of the cell membrane or to lea.pdfIf a protein is destined to be a part of the cell membrane or to lea.pdf
If a protein is destined to be a part of the cell membrane or to lea.pdfarihantplastictanksh
 
How do angiosperms increase the likelihood that their embryos arc mov.pdf
How do angiosperms increase the likelihood that their embryos arc mov.pdfHow do angiosperms increase the likelihood that their embryos arc mov.pdf
How do angiosperms increase the likelihood that their embryos arc mov.pdfarihantplastictanksh
 
How is FOIL used in factoring polynomialsSolutionFOIL method .pdf
How is FOIL used in factoring polynomialsSolutionFOIL method .pdfHow is FOIL used in factoring polynomialsSolutionFOIL method .pdf
How is FOIL used in factoring polynomialsSolutionFOIL method .pdfarihantplastictanksh
 
How did social revolution relate to warfare developmentSolution.pdf
How did social revolution relate to warfare developmentSolution.pdfHow did social revolution relate to warfare developmentSolution.pdf
How did social revolution relate to warfare developmentSolution.pdfarihantplastictanksh
 
Does native Con A exist as a monomer, dimer, trimer, or tetramer.pdf
Does native Con A exist as a monomer, dimer, trimer, or tetramer.pdfDoes native Con A exist as a monomer, dimer, trimer, or tetramer.pdf
Does native Con A exist as a monomer, dimer, trimer, or tetramer.pdfarihantplastictanksh
 
Explain role ambiguity in terms of supportive leader behavior.So.pdf
Explain role ambiguity in terms of supportive leader behavior.So.pdfExplain role ambiguity in terms of supportive leader behavior.So.pdf
Explain role ambiguity in terms of supportive leader behavior.So.pdfarihantplastictanksh
 
Explain the benefit of designing a foundation with LRFD as opposed to.pdf
Explain the benefit of designing a foundation with LRFD as opposed to.pdfExplain the benefit of designing a foundation with LRFD as opposed to.pdf
Explain the benefit of designing a foundation with LRFD as opposed to.pdfarihantplastictanksh
 
Expand upon selectionSortType so that you are no longer bound to a l.pdf
Expand upon selectionSortType so that you are no longer bound to a l.pdfExpand upon selectionSortType so that you are no longer bound to a l.pdf
Expand upon selectionSortType so that you are no longer bound to a l.pdfarihantplastictanksh
 
describe the three major categorical theories of language developmen.pdf
describe the three major categorical theories of language developmen.pdfdescribe the three major categorical theories of language developmen.pdf
describe the three major categorical theories of language developmen.pdfarihantplastictanksh
 
Compare the capabilities of the Microsoft Access, Microsoft SQL Serv.pdf
Compare the capabilities of the Microsoft Access, Microsoft SQL Serv.pdfCompare the capabilities of the Microsoft Access, Microsoft SQL Serv.pdf
Compare the capabilities of the Microsoft Access, Microsoft SQL Serv.pdfarihantplastictanksh
 
case study of a female with a parasitic disease Here is a Microbiolog.pdf
case study of a female with a parasitic disease Here is a Microbiolog.pdfcase study of a female with a parasitic disease Here is a Microbiolog.pdf
case study of a female with a parasitic disease Here is a Microbiolog.pdfarihantplastictanksh
 
are marine multicellular protists belonging to the larger brown alg.pdf
are marine multicellular protists belonging to the larger brown alg.pdfare marine multicellular protists belonging to the larger brown alg.pdf
are marine multicellular protists belonging to the larger brown alg.pdfarihantplastictanksh
 
8-9 Which gene (C or D) is downstream in the pathway based on the ep.pdf
8-9 Which gene (C or D) is downstream in the pathway based on the ep.pdf8-9 Which gene (C or D) is downstream in the pathway based on the ep.pdf
8-9 Which gene (C or D) is downstream in the pathway based on the ep.pdfarihantplastictanksh
 
4. Belief in God Religion Studies researchers were interested in ma.pdf
4. Belief in God Religion Studies researchers were interested in ma.pdf4. Belief in God Religion Studies researchers were interested in ma.pdf
4. Belief in God Religion Studies researchers were interested in ma.pdfarihantplastictanksh
 
18. Identify (at least 5) and explain their meanings of reducing ble.pdf
18. Identify (at least 5) and explain their meanings of reducing ble.pdf18. Identify (at least 5) and explain their meanings of reducing ble.pdf
18. Identify (at least 5) and explain their meanings of reducing ble.pdfarihantplastictanksh
 
With enough money, energy, and political will, the nations of the wo.pdf
With enough money, energy, and political will, the nations of the wo.pdfWith enough money, energy, and political will, the nations of the wo.pdf
With enough money, energy, and political will, the nations of the wo.pdfarihantplastictanksh
 
Which members of the truss are zero-force members Solutionass.pdf
Which members of the truss are zero-force members  Solutionass.pdfWhich members of the truss are zero-force members  Solutionass.pdf
Which members of the truss are zero-force members Solutionass.pdfarihantplastictanksh
 
Which THREE of the following statements about autotrophs and heterot.pdf
Which THREE of the following statements about autotrophs and heterot.pdfWhich THREE of the following statements about autotrophs and heterot.pdf
Which THREE of the following statements about autotrophs and heterot.pdfarihantplastictanksh
 
What type of biometric error signifies that an authorized user has b.pdf
What type of biometric error signifies that an authorized user has b.pdfWhat type of biometric error signifies that an authorized user has b.pdf
What type of biometric error signifies that an authorized user has b.pdfarihantplastictanksh
 
What is an unintended medical consequences What is an example of on.pdf
What is an unintended medical consequences What is an example of on.pdfWhat is an unintended medical consequences What is an example of on.pdf
What is an unintended medical consequences What is an example of on.pdfarihantplastictanksh
 

More from arihantplastictanksh (20)

If a protein is destined to be a part of the cell membrane or to lea.pdf
If a protein is destined to be a part of the cell membrane or to lea.pdfIf a protein is destined to be a part of the cell membrane or to lea.pdf
If a protein is destined to be a part of the cell membrane or to lea.pdf
 
How do angiosperms increase the likelihood that their embryos arc mov.pdf
How do angiosperms increase the likelihood that their embryos arc mov.pdfHow do angiosperms increase the likelihood that their embryos arc mov.pdf
How do angiosperms increase the likelihood that their embryos arc mov.pdf
 
How is FOIL used in factoring polynomialsSolutionFOIL method .pdf
How is FOIL used in factoring polynomialsSolutionFOIL method .pdfHow is FOIL used in factoring polynomialsSolutionFOIL method .pdf
How is FOIL used in factoring polynomialsSolutionFOIL method .pdf
 
How did social revolution relate to warfare developmentSolution.pdf
How did social revolution relate to warfare developmentSolution.pdfHow did social revolution relate to warfare developmentSolution.pdf
How did social revolution relate to warfare developmentSolution.pdf
 
Does native Con A exist as a monomer, dimer, trimer, or tetramer.pdf
Does native Con A exist as a monomer, dimer, trimer, or tetramer.pdfDoes native Con A exist as a monomer, dimer, trimer, or tetramer.pdf
Does native Con A exist as a monomer, dimer, trimer, or tetramer.pdf
 
Explain role ambiguity in terms of supportive leader behavior.So.pdf
Explain role ambiguity in terms of supportive leader behavior.So.pdfExplain role ambiguity in terms of supportive leader behavior.So.pdf
Explain role ambiguity in terms of supportive leader behavior.So.pdf
 
Explain the benefit of designing a foundation with LRFD as opposed to.pdf
Explain the benefit of designing a foundation with LRFD as opposed to.pdfExplain the benefit of designing a foundation with LRFD as opposed to.pdf
Explain the benefit of designing a foundation with LRFD as opposed to.pdf
 
Expand upon selectionSortType so that you are no longer bound to a l.pdf
Expand upon selectionSortType so that you are no longer bound to a l.pdfExpand upon selectionSortType so that you are no longer bound to a l.pdf
Expand upon selectionSortType so that you are no longer bound to a l.pdf
 
describe the three major categorical theories of language developmen.pdf
describe the three major categorical theories of language developmen.pdfdescribe the three major categorical theories of language developmen.pdf
describe the three major categorical theories of language developmen.pdf
 
Compare the capabilities of the Microsoft Access, Microsoft SQL Serv.pdf
Compare the capabilities of the Microsoft Access, Microsoft SQL Serv.pdfCompare the capabilities of the Microsoft Access, Microsoft SQL Serv.pdf
Compare the capabilities of the Microsoft Access, Microsoft SQL Serv.pdf
 
case study of a female with a parasitic disease Here is a Microbiolog.pdf
case study of a female with a parasitic disease Here is a Microbiolog.pdfcase study of a female with a parasitic disease Here is a Microbiolog.pdf
case study of a female with a parasitic disease Here is a Microbiolog.pdf
 
are marine multicellular protists belonging to the larger brown alg.pdf
are marine multicellular protists belonging to the larger brown alg.pdfare marine multicellular protists belonging to the larger brown alg.pdf
are marine multicellular protists belonging to the larger brown alg.pdf
 
8-9 Which gene (C or D) is downstream in the pathway based on the ep.pdf
8-9 Which gene (C or D) is downstream in the pathway based on the ep.pdf8-9 Which gene (C or D) is downstream in the pathway based on the ep.pdf
8-9 Which gene (C or D) is downstream in the pathway based on the ep.pdf
 
4. Belief in God Religion Studies researchers were interested in ma.pdf
4. Belief in God Religion Studies researchers were interested in ma.pdf4. Belief in God Religion Studies researchers were interested in ma.pdf
4. Belief in God Religion Studies researchers were interested in ma.pdf
 
18. Identify (at least 5) and explain their meanings of reducing ble.pdf
18. Identify (at least 5) and explain their meanings of reducing ble.pdf18. Identify (at least 5) and explain their meanings of reducing ble.pdf
18. Identify (at least 5) and explain their meanings of reducing ble.pdf
 
With enough money, energy, and political will, the nations of the wo.pdf
With enough money, energy, and political will, the nations of the wo.pdfWith enough money, energy, and political will, the nations of the wo.pdf
With enough money, energy, and political will, the nations of the wo.pdf
 
Which members of the truss are zero-force members Solutionass.pdf
Which members of the truss are zero-force members  Solutionass.pdfWhich members of the truss are zero-force members  Solutionass.pdf
Which members of the truss are zero-force members Solutionass.pdf
 
Which THREE of the following statements about autotrophs and heterot.pdf
Which THREE of the following statements about autotrophs and heterot.pdfWhich THREE of the following statements about autotrophs and heterot.pdf
Which THREE of the following statements about autotrophs and heterot.pdf
 
What type of biometric error signifies that an authorized user has b.pdf
What type of biometric error signifies that an authorized user has b.pdfWhat type of biometric error signifies that an authorized user has b.pdf
What type of biometric error signifies that an authorized user has b.pdf
 
What is an unintended medical consequences What is an example of on.pdf
What is an unintended medical consequences What is an example of on.pdfWhat is an unintended medical consequences What is an example of on.pdf
What is an unintended medical consequences What is an example of on.pdf
 

Recently uploaded

Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 

Recently uploaded (20)

Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 

For the following I have finished most of this question but am havin.pdf

  • 1. For the following I have finished most of this question but am having problem with on method. I just need the void copyNumbers method filled out. The commented out sections describe what it needs to do. I have it started. Just need it finished. package reading_with_exceptions; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.InputMismatchException; import java.util.Scanner; public class Reading_With_Exceptions { // 1.) Create a Scanner from the inputFilename. Catch exceptions from errors. // 2.) Read the first String from the file and use it to create a PrintStream // catching appropriate exceptions // 3.) Using hasNextInt and nextInt, carefully read the count integer. // I recommend -1 for a count value if it is bad to indicate reading ALL // 4.) Use copyNumbers method described below to complete the job // 5.) Close Scanner and PrintStream objects // 6.) Call printToScreen to copy the output file to the screen void process(String inputFilename) { int number_to_read = 0; try { Scanner input = new Scanner(inputFilename); String outputFilename = input.next(); PrintStream os = new PrintStream(new FileOutputStream(outputFilename)); if ( input.hasNextInt()) { number_to_read = input.nextInt(); }else { number_to_read = -1;
  • 2. } copyNumbers(input, os, number_to_read); input.close(); os.close(); printToScreen(outputFilename); }catch (FileNotFoundException e) { System.out.println("Cannot find file: " + e); return; } } // The following routine is called to complete the job of copying integers to // the output file: // scan - a Scanner object to copy integers from // ps - A PrintStream to write the integers to // numIntsToRead - number of integers to read. A value of -1 ==> read all integers void copyNumbers(Scanner scan, PrintStream ps, int numIntsToRead) { // hasNext() can be used to see if the scan object still has data // Note that hasNextInt() can be used to see if an integer is present // nextInt() will read an integer // next() can be used to skip over bad integers while (scan.hasNext()) { if (numIntsToRead < 0) { //print out a complaint message and then read as many integers as you find. scan.nextInt(); } if (!scan.hasNextInt()) { // print a complaint message and skip over the data
  • 3. scan.next(); } if ( scan < numIntsToRead) { // complain but do not abort } } } public static void main(String[] args) { Reading_With_Exceptions rwe = new Reading_With_Exceptions(); for (int i=0; i < args.length; i++) { System.out.println(" =========== Processing "+ args[i] + " ========== "); rwe.process(args[i]); } } // For the last step, we Copy the contents of the file to the screen private void printToScreen(String filename) { Scanner scan = null; try { FileInputStream fis = new FileInputStream(filename); scan = new Scanner(fis); while (scan.hasNextLine()) { System.out.println(scan.nextLine()); } } catch (FileNotFoundException e) { System.out.println("printToScreen: can't open: " + filename); } finally { if (scan != null) scan.close(); } }// end of printToScreen
  • 4. } Solution Please follow the code and comments for description : CODE : import java.io.File; // required imports for the code import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.Scanner; public class Reading_With_Exceptions { // class that runs the code // 1.) Create a Scanner from the inputFilename. Catch exceptions from errors. // 2.) Read the first String from the file and use it to create a PrintStream // catching appropriate exceptions // 3.) Using hasNextInt and nextInt, carefully read the count integer. // I recommend -1 for a count value if it is bad to indicate reading ALL // 4.) Use copyNumbers method described below to complete the job // 5.) Close Scanner and PrintStream objects // 6.) Call printToScreen to copy the output file to the screen void process(String inputFilename) { // method that does the processing of the file int number_to_read = 0; File file = new File(inputFilename); // reading it to a file as the input form is a string name try { String outputFilename; PrintStream os; try (Scanner input = new Scanner(file)) { // checking or reading the unput file outputFilename = input.nextLine(); os = new PrintStream(new FileOutputStream(outputFilename)); // saving the firstline to a output filename if (input.hasNextInt()) { // checking for the data in the file number_to_read = input.nextInt(); } else { number_to_read = -1;
  • 5. } copyNumbers(input, os, number_to_read); } os.close(); // closing the stream class printToScreen(outputFilename); // calling the method to print the data from the output file } catch (FileNotFoundException e) { // catching the exceptions System.out.println("Cannot find file: " + e); } } // The following routine is called to complete the job of copying integers to // the output file: // scan - a Scanner object to copy integers from // ps - A PrintStream to write the integers to // numIntsToRead - number of integers to read. A value of -1 ==> read all integers void copyNumbers(Scanner scan, PrintStream ps, int numIntsToRead) { // method to copy the data to the file // hasNext() can be used to see if the scan object still has data // Note that hasNextInt() can be used to see if an integer is present // nextInt() will read an integer // next() can be used to skip over bad integers while (scan.hasNext()) { //iterating over the loop to read the data if (numIntsToRead < 0) { //print out a complaint message and then read as many integers as you find. System.out.println("A Message Indicating that reading all the data from the file."); while(scan.hasNextInt()){ int readNum = scan.nextInt(); ps.print(readNum); ps.print(" "); ps.flush(); System.out.println(" Completed Reading the Data.! "); } } if (!scan.hasNextInt()) { // print a complaint message and skip over the data System.out.println(" No Data Present in the File to Read.! "); scan.nextLine();
  • 6. } } } public static void main(String[] args) { // driver method Reading_With_Exceptions rwe = new Reading_With_Exceptions(); Scanner sc = new Scanner(System.in); System.out.println("Enter the Number of Files : "); // prompt for the user the enter the total number of files int num = sc.nextInt(); System.out.println("Enter the FileName : "); // prompt to enter the file name with extension String file[] = new String[num]; sc.nextLine(); for (int x = 0; x < num; x++) { String filename = sc.nextLine(); file[x] = filename; } for (String files : file) { System.out.println(" =========== Processing " + files + " ========== "); rwe.process(files); //calling the method to process the data files } } // For the last step, we Copy the contents of the file to the screen private void printToScreen(String filename) { // method to print the data to the screen Scanner scan = null; try { FileInputStream fis = new FileInputStream(filename); scan = new Scanner(fis); System.out.println("Data Present in the Output File is : "); while (scan.hasNextLine()) { System.out.println(scan.nextLine()); } } catch (FileNotFoundException e) { System.out.println("printToScreen: can't open: " + filename); } finally {
  • 7. if (scan != null) { scan.close(); } } }// end of printToScreen } OUTPUT : Enter the Number of Files : 1 Enter the FileName : input.txt =========== Processing input.txt ========== A Message Indicating that reading all the data from the file. Completed Reading the Data.! No Data Present in the File to Read.! Data Present in the Output File is : 102 3 4 5 6 7 8 9 10 Hope this is helpful.