Question

In: Computer Science

Language: Java I have written this code but not all methods are running. First method is...

Language: Java

I have written this code but not all methods are running. First method is running fine but when I enter the file path, it is not reading it.

Directions

The input file must be read into an input array and data validated from the array. Input file format (500 records maximum per file): comma delimited text, should contain 6 fields: any row containing exactly 6 fields is considered to be invalid

Purpose of this code is to : Read the file from where it is place, data validate it for correctness, manipulate it into a slightly different format and write a new version of all VALID rows to a new file placed in a standard location. Create an error/suspense file that contains only the rows that contain errors and place it into a standard location.Teammate/mentor and you have decided to code the application using the main method to only call other methods to do the work.

Code

import java.io.*;

import java.text.MessageFormat;

import java.util.*;

public class Students {

static public final int ARRAY_SIZE = 500;

static public final int REQUIRED_TOKEN_NUMBER = 6;

static public File inputFile;

static public File goodFile = new File("c:" + File.separator + "student" +

File.separator + "students.dat");

static public File errorFile = new File("c:" + File.separator + "student" +

File.separator + "studentSuspense.dat");

static public BufferedReader inStream;

static public BufferedReader inFileStream;

static public BufferedWriter goodFileOut, errorFileOut;

static public String inputArray[];

public static void main(String args[]) {

getFileNameAndPath();

openInputFile();

fillInputArray();

openGoodFile();

openErrorFile();

validateData();

closeOutputFiles();

System.exit(0);

}

public static void getFileNameAndPath() {

try{

inStream = new BufferedReader(new InputStreamReader(System.in));

System.out.print("Please, enter file path: ");

String filePath = inStream.readLine().trim();

inputFile = new File(filePath);

}

catch (IOException e) {

System.out.println(e.getMessage());

System.exit(-1);

}

}

public static void openInputFile() {

try {

inFileStream = new BufferedReader(new FileReader(inputFile));

}

catch (IOException e) {

System.out.println(e.getMessage());

System.exit(-1);

}

}

private static void fillInputArray() {

try {

inputArray = new String[ARRAY_SIZE];

int counter = 0;

String line = null;

while ((line = inFileStream.readLine()) != null) {

inputArray[counter++] = line;

}

inFileStream.close();

}

catch (IOException e) {

System.out.println(e.getMessage());

System.exit(-1);

}

}

private static void openGoodFile() {

try {

goodFileOut = new BufferedWriter(new FileWriter(goodFile));

}

catch (IOException e) {

System.out.println(e.getMessage());

System.exit(-1);

}

}

private static void openErrorFile() {

try {

errorFileOut = new BufferedWriter(new FileWriter(errorFile));

}

catch (IOException e) {

System.out.println(e.getMessage());

System.exit(-1);

}

}

private static void validateData() {

for(int i = 0; i<inputArray.length; i++) {

String line = inputArray[i];

if (line == null) {

break;

}

String[] parts = line.split(",");

int age = 0;

double score = 0.0;

if (parts.length != REQUIRED_TOKEN_NUMBER) {

writeLineToErrorFile(line);

continue;

}

try {

age = Integer.parseInt(parts[4]);

}

catch (NumberFormatException e) {

writeLineToErrorFile(line);

continue;

}

try {

score = Double.parseDouble(parts[5]);

}

catch (NumberFormatException e) {

writeLineToErrorFile(line);

continue;

}

writeLineToGoodFile(parts[0], parts[1], parts[2], parts[3], age, score);

}

}

public static void writeLineToErrorFile(String badLine) {

try {

errorFileOut.write(badLine + System.lineSeparator());

}

catch (IOException e) {

System.out.println(e.getMessage());

System.exit(-1);

}

}

public static void writeLineToGoodFile(String lName, String fName,

String mName, String id, int age, double examScore) {

String newLine = MessageFormat.format("{0}, {1}|{0}|{1}|{2}|{3}|{4}|{5}",

lName, fName, mName,id, age, String.format("%.1f", examScore));

try {

goodFileOut.write(newLine + System.lineSeparator());

}

catch (IOException e) {

System.out.println(e.getMessage());

System.exit(-1);

}

}

public static void closeOutputFiles() {

try {

goodFileOut.close();

errorFileOut.close();

}

catch (IOException e) {

System.err.println(e.getMessage());

System.exit(-1);

}

}

}

Solutions

Expert Solution


import java.io.*;

import java.text.MessageFormat;

import java.util.*;

public class Students {

static public final int ARRAY_SIZE = 500;

static public final int REQUIRED_TOKEN_NUMBER = 6;

static public File inputFile;
//good file path should be present otherwise getting error with file not found
static public File goodFile = new File("c:" + File.separator + "student"
+ File.separator + "students.dat");
//also errorfile should be present on provided path otherwise exception will occur
static public File errorFile = new File("c:" + File.separator + "student"
+ File.separator + "studentSuspense.dat");

static public BufferedReader inStream;

static public BufferedReader inFileStream;

static public BufferedWriter goodFileOut, errorFileOut;

static public String inputArray[];

public static void main(String args[]) {

getFileNameAndPath();

openInputFile();

fillInputArray();

openGoodFile();

openErrorFile();

validateData();

closeOutputFiles();
//write to console if there is no any exception or error
System.out.println("File validated successfully...");
System.exit(0);

}

public static void getFileNameAndPath() {

try {
//get file path from user with file name
inStream = new BufferedReader(new InputStreamReader(System.in));

System.out.print("Please, enter file path: ");

String filePath = inStream.readLine().trim();

inputFile = new File(filePath);

} catch (IOException e) {

System.out.println(e.getMessage());

System.exit(-1);

}

}

public static void openInputFile() {

try {
//read the input file
inFileStream = new BufferedReader(new FileReader(inputFile));

} catch (IOException e) {

System.out.println(e.getMessage());

System.exit(-1);

}

}

private static void fillInputArray() {

try {
//read file and convert it into array
inputArray = new String[ARRAY_SIZE];

int counter = 0;

String line = null;

while ((line = inFileStream.readLine()) != null) {

inputArray[counter++] = line;

}

inFileStream.close();

} catch (IOException e) {

System.out.println(e.getMessage());

System.exit(-1);

}

}

private static void openGoodFile() {

try {

goodFileOut = new BufferedWriter(new FileWriter(goodFile));

} catch (IOException e) {

System.out.println(e.getMessage());

System.exit(-1);

}

}

private static void openErrorFile() {

try {

errorFileOut = new BufferedWriter(new FileWriter(errorFile));

} catch (IOException e) {

System.out.println(e.getMessage());

System.exit(-1);

}

}

private static void validateData() {
//validate the each line if data contains exactly 6 fields then it is valid if not then invalid
for (int i = 0; i < inputArray.length; i++) {

String line = inputArray[i];

if (line == null) {

break;

}

String[] parts = line.split(",");

int age = 0;

double score = 0.0;

if (parts.length != REQUIRED_TOKEN_NUMBER) {

writeLineToErrorFile(line);

continue;

}

try {

age = Integer.parseInt(parts[4]);

} catch (NumberFormatException e) {

writeLineToErrorFile(line);

continue;

}

try {

score = Double.parseDouble(parts[5]);

} catch (NumberFormatException e) {

writeLineToErrorFile(line);

continue;

}
//write data to goodfile
writeLineToGoodFile(parts[0], parts[1], parts[2], parts[3], age, score);

}

}

public static void writeLineToErrorFile(String badLine) {

try {

errorFileOut.write(badLine + System.lineSeparator());

} catch (IOException e) {

System.out.println(e.getMessage());

System.exit(-1);

}

}

public static void writeLineToGoodFile(String lName, String fName,
String mName, String id, int age, double examScore) {

String newLine = MessageFormat.format("{0}, {1}|{0}|{1}|{2}|{3}|{4}|{5}",
lName, fName, mName, id, age, String.format("%.1f", examScore));

try {

goodFileOut.write(newLine + System.lineSeparator());

} catch (IOException e) {

System.out.println(e.getMessage());

System.exit(-1);

}

}

public static void closeOutputFiles() {

try {
//close all open files
goodFileOut.close();

errorFileOut.close();

} catch (IOException e) {

System.err.println(e.getMessage());

System.exit(-1);

}

}

}
Note: path should be contain filename and extension

//output

Please, enter file path: C:\Users\PhoenixZone\Desktop\testfile.txt
File validated successfully...

//input file data (testfile.txt)

Dinesh,Ubale,First Year,Computer Engineering,lo,63.2
Dinesh,SDE,Second Year,Computer Engineering,23,65.8
John,Smith,Third Year,Computer Engineering,25,80.36
Dinsh,Pawar,First Year,Mechanical Engineering,26,70.5
Dnew,Nimbhore,First Year,Civil Engineering,27,46.2
Din,UHY,Fourth Year,E&TC Engineering,28,66.0

//students.dat file data

Dinesh, SDE|Dinesh|SDE|Second Year|Computer Engineering|23|65.8
John, Smith|John|Smith|Third Year|Computer Engineering|25|80.4
Dinsh, Pawar|Dinsh|Pawar|First Year|Mechanical Engineering|26|70.5
Dnew, Nimbhore|Dnew|Nimbhore|First Year|Civil Engineering|27|46.2
Din, UHY|Din|UHY|Fourth Year|E&TC Engineering|28|66.0

//studentSuspense.dat file data

Dinesh,Ubale,First Year,Computer Engineering,lo,63.2


Related Solutions

Language: Java To be able to code a class structure with appropriate attributes and methods. To...
Language: Java To be able to code a class structure with appropriate attributes and methods. To demonstrate the concept of inheritance. To be able to create different objects and use both default and overloaded constructors. Practice using encapsulation (setters and getters) and the toString method. Create a set of classes for various types of video content (TvShows, Movies, MiniSeries). Write a super or parent class that contains common attributes and subclasses with unique attributes for each class. Make sure to...
The programming language that is being used here is JAVA, below I have my code that...
The programming language that is being used here is JAVA, below I have my code that is supposed to fulfill the TO-DO's of each segment. This code in particular has not passed 3 specific tests. Below the code, the tests that failed will be written in bold with what was expected and what was outputted. Please correct the mistakes that I seem to be making if you can. Thank you kindly. OverView: For this project, you will develop a game...
I need this written in Java, it is a Linked List and each of it's Methods....
I need this written in Java, it is a Linked List and each of it's Methods. I am having trouble and would appreciate code written to specifications and shown how to check if each method is working with an example of one method being checked. Thank you. public interface Sequence <T> { /** * Inserts the given element at the specified index position within the sequence. The element currently at that * index position (and all subsequent elements) are shifted...
So I have written a code for it but i just have a problem with the...
So I have written a code for it but i just have a problem with the output. For the month with the highest temperature and lowest temperature, my code starts at 0 instead of 1. For example if I input that month 1 had a high of 20 and low of -10, and every other month had much warmer weather than that, it should say "The month with the lowest temperature is 1" but instead it says "The month with...
IN JAVA. I have the following code (please also implement the Tester to test the methods...
IN JAVA. I have the following code (please also implement the Tester to test the methods ) And I need to add a method called public int remove() that should remove the first integer of the array and return it at the dame time saving the first integer and bring down all other elements. After it should decrease the size of the array, and after return and save the integer. package ourVector; import java.util.Scanner; public class ourVector { private int[]...
I don't know why my java code is not running this error code pops up -->...
I don't know why my java code is not running this error code pops up --> Error: Could not find or load main class DieRoll Caused by: java.lang.ClassNotFoundException: DieRoll. Code below:    import java.util.Random;    import java.util.Scanner;    public class Assignment {    public static void combineStrings() {    String school = "Harvard";    String city = "Boston, MA";    int stringLen;       String upper, changeChar, combine;       stringLen = school.length();    System.out.println(school+" contains "+stringLen+" characters." );   ...
(To be written in Java code) A personal phone directory contains room for first names and...
(To be written in Java code) A personal phone directory contains room for first names and phone numbers for 30 people. Assign names and phone numbers for the first 10 people. Prompt the user for a name, and if the name is found in the list, display the corresponding phone number. If the name is not found in the list, prompt the user for a phone number, and add the new name and phone number to the list. Continue to...
in java: In my code at have my last two methods that I cannot exactly figure...
in java: In my code at have my last two methods that I cannot exactly figure out how to execute. I have too convert a Roman number to its decimal form for the case 3 switch. The two methods I cannot figure out are the public static int valueOf(int numeral) and public static int convertRomanNumber(int total, int length, String numeral). This is what my code looks like so far: public static void main(String[] args) { // TODO Auto-generated method stub...
// the language is java, please implement the JOptionPane Use method overloading to code an operation...
// the language is java, please implement the JOptionPane Use method overloading to code an operation class called CircularComputing in which there are 3 overloaded methods and an output method as follows: • computeObject(double radius) – compute the area of a circle • computeObject(double radius, double height) – compute area of a cylinder • computeObject(double radiusOutside, double radiusInside, double height) – compute the volume of a cylindrical object • output() use of JOptionPane to display instance field(s) and the result...
I need code written in java for one of my projects the instructions are Write a...
I need code written in java for one of my projects the instructions are Write a program that interacts with the user via the console and lets them choose options from a food menu by using the associated item number. It is expected that your program builds an <orderString> representing the food order to be displayed at the end. (See Sample Run Below). Please note: Each student is required to develop their own custom menus, with unique food categories, items...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT