May use \"Problem Solving, Abstraction, and Design Using C++\", 6th Ed. as refer
ID: 3831323 • Letter: M
Question
May use "Problem Solving, Abstraction, and Design Using C++", 6th Ed. as reference - ch8 Modular Programming
Introduction to C++
Note: In this lab, your programs that are interactive DO need to check for invalid input and those tests should be included in your Test Suite. Anything running in batch-mode (reading from input files) may assume the input file is formatted as specified. Your program should display an error message on invalid user input and require the user to re-enter the information correctly (input validation)
Number Translation. --- TEST SUITE is required! (5pts)
Write a program that reads integers from a local input file, in the range from 1 till 9,999 and writes the same number in English and in digits (same Line) to a local output file. Each integer in both the input and output file should be on its own line. The input file (on blackboard ) will be formatted with commas, the output file (that you create) will not be (i.e. remove the commas from the numerical version).
Explanation / Answer
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class ReadWriteFileMain {
static File inputFile = null;
static FileReader fileReader = null;
static File outputFile = null;
static FileWriter fileWriter = null;
static String s="";
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) throws IOException {
System.out.print("Please enter input file name: ");
String inputFileName = sc.next();
reader(inputFileName);
}
public static void reader(String fileName) throws IOException,NullPointerException{
if(fileName == null || "".equals(fileName)){
throw new NullPointerException("fileName can't be null or empty!");
}
inputFile = new File("D:\"+fileName+".txt");
if(inputFile == null){
throw new NullPointerException("File does not exist");
}
fileReader = new FileReader(inputFile);
int i;
int j=0;
while((i=fileReader.read())!=-1){
s=s+(char)i;
System.out.print((char)i);
}
System.out.println();
System.out.print("Please enter output file name: ");
String outputFileName = sc.next();
writer(outputFileName);
}
public static void writer(String fileName) throws IOException{
if(fileName == null || "".equals(fileName)){
throw new NullPointerException("fileName can't be null or empty!");
}
outputFile = new File("D:\"+fileName+".txt");
if(outputFile == null){
throw new NullPointerException("File does not exist");
}
fileWriter = new FileWriter(outputFile);
fileWriter.write(s);
}
}