Read in a file, check that it meets certain criteria











up vote
0
down vote

favorite
1












This was my original posting: Check that a data file contains the expected number of rows and columns of integers



I updated the code. Still what could I improve on?



Another question I have is how come my last method fileContent() does not need any throws declaration in the method header?



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

public class FormatChecker2 {

public static void main(String args) {
FormatChecker2 tester = new FormatChecker2(); // To avoid every method being static.

if (args.length == 0) {
System.out.println("Usage: $ java FormatChecker file1 [file2 ... fileN]");
} else {
for (String fileName : args) {
try {
tester.readInTextFile(fileName);
System.out.println(fileName + "");
System.out.println("VALID");
System.out.println();
} catch (FileNotFoundException notFound) {
System.out.println(notFound.getMessage() + "");
System.out.println(notFound + " (The system cannot find the file specified)");
System.out.println("INVALID");
System.out.println();
} catch (NumberFormatException notInt) {
System.out.println(fileName);
// String printMessage = notInt.toString().replaceAll("#.*?;", ""); "#" + file +
// ";"
System.out.println(notInt);
System.out.println("INVALID");
System.out.println();
} catch (InputMismatchException badContent) {
System.out.println(fileName);
System.out.println(badContent);
System.out.println("INVALID");
System.out.println();
} catch (IllegalCharacterException delChar) {
System.out.println(fileName);
System.out.println(delChar);
System.out.println("INVALID");
System.out.println();
}

}
}
}

public void readInTextFile(String fileName)
throws FileNotFoundException, IllegalCharacterException, NumberFormatException {
File file = new File(fileName);
if (file.exists() && file.isFile()) {
parseFile(file);
} else {
throw new FileNotFoundException(fileName);
}
}

public void parseFile(File file) throws FileNotFoundException, IllegalCharacterException {
Scanner fileScan = new Scanner(file);
String declaredRowCol = fileScan.nextLine().trim();
String dimensions = declaredRowCol.split("\s+");
String declaredRowStr = dimensions[0];
String declaredColStr = dimensions[1];
int rowCount = 0;
int colCount = 0;
String notAllNumbers = "";
while (fileScan.hasNextLine()) {
String line = fileScan.nextLine().trim();
if (!line.isEmpty()) {
rowCount++;// Counts actual number of rows
}
Scanner lineScan = new Scanner(line);
while (lineScan.hasNext()) {
String token = lineScan.next().trim(); // should I include trim?
char letterCheck = token.charAt(0);
// Checks to make sure the content of this file includes only numbers
if (Character.isLetter(letterCheck)) {
notAllNumbers = letterCheck + "";
}
colCount++; // Counts actual number of columns, divide by rowCount to get actual
}
lineScan.close();
}
// Checks to make sure there is not an extra integer on the first line
if (dimensions.length > 2) {
throw new IllegalCharacterException(
"Row and Column have already been provided on the first line of the file. The extra integer: "
+ """ + dimensions[2] + """ + " should not be included.");
} else if (!notAllNumbers.isEmpty()) {
throw new IllegalCharacterException(
"This value in your file: " + """ + notAllNumbers + """ + " is not a number.");
} else {
formatDimensions(dimensions, declaredRowStr, declaredColStr, rowCount, colCount);
}
}

public void formatDimensions(String dimensions, String declaredRowStr, String declaredColStr, int rowCount,
int colCount) throws IllegalCharacterException, NumberFormatException, FileNotFoundException {

int declaredRow = 0;
int declaredCol = 0;
// Catches if the variables on the first line are of type integer
try {
declaredRow = Integer.parseInt(declaredRowStr);
declaredCol = Integer.parseInt(declaredColStr);
fileContent(declaredRow, declaredCol, rowCount, colCount);
} catch (NumberFormatException e) {
throw new NumberFormatException("This value on the first line of your file:"
+ e.getMessage().substring(17, e.getMessage().length()) + " is not of type integer.");
}
}

public void fileContent(int declaredRow, int declaredCol, int rowCount, int colCount)
throws FileNotFoundException, IllegalCharacterException {

// Checks to see if row and column matches the actual number of rows and columns
double roundToRealRowCount = (rowCount / 1.0); // This is to account for rounding of
// integer
double roundToRealColCount = (colCount / roundToRealRowCount);// if row or column is not
// divided evenly

if (rowCount != declaredRow) {
throw new InputMismatchException("Number of rows declaration: " + "'" + declaredRow + "'"
+ " on first line does not match the actual number of rows in file.");
} else if (roundToRealColCount != declaredCol) {
throw new InputMismatchException("Number of columns declaration: " + "'" + declaredCol + "'"
+ " on first line does not match the actual number of columns in file.");
}
}
}









share|improve this question
























  • ...but I see fileContent method does have throws clause ....
    – Sharon Ben Asher
    Sep 19 '17 at 6:32










  • all the printing inside the catch clauses look very similar. should be put in a method.
    – Sharon Ben Asher
    Sep 19 '17 at 6:34















up vote
0
down vote

favorite
1












This was my original posting: Check that a data file contains the expected number of rows and columns of integers



I updated the code. Still what could I improve on?



Another question I have is how come my last method fileContent() does not need any throws declaration in the method header?



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

public class FormatChecker2 {

public static void main(String args) {
FormatChecker2 tester = new FormatChecker2(); // To avoid every method being static.

if (args.length == 0) {
System.out.println("Usage: $ java FormatChecker file1 [file2 ... fileN]");
} else {
for (String fileName : args) {
try {
tester.readInTextFile(fileName);
System.out.println(fileName + "");
System.out.println("VALID");
System.out.println();
} catch (FileNotFoundException notFound) {
System.out.println(notFound.getMessage() + "");
System.out.println(notFound + " (The system cannot find the file specified)");
System.out.println("INVALID");
System.out.println();
} catch (NumberFormatException notInt) {
System.out.println(fileName);
// String printMessage = notInt.toString().replaceAll("#.*?;", ""); "#" + file +
// ";"
System.out.println(notInt);
System.out.println("INVALID");
System.out.println();
} catch (InputMismatchException badContent) {
System.out.println(fileName);
System.out.println(badContent);
System.out.println("INVALID");
System.out.println();
} catch (IllegalCharacterException delChar) {
System.out.println(fileName);
System.out.println(delChar);
System.out.println("INVALID");
System.out.println();
}

}
}
}

public void readInTextFile(String fileName)
throws FileNotFoundException, IllegalCharacterException, NumberFormatException {
File file = new File(fileName);
if (file.exists() && file.isFile()) {
parseFile(file);
} else {
throw new FileNotFoundException(fileName);
}
}

public void parseFile(File file) throws FileNotFoundException, IllegalCharacterException {
Scanner fileScan = new Scanner(file);
String declaredRowCol = fileScan.nextLine().trim();
String dimensions = declaredRowCol.split("\s+");
String declaredRowStr = dimensions[0];
String declaredColStr = dimensions[1];
int rowCount = 0;
int colCount = 0;
String notAllNumbers = "";
while (fileScan.hasNextLine()) {
String line = fileScan.nextLine().trim();
if (!line.isEmpty()) {
rowCount++;// Counts actual number of rows
}
Scanner lineScan = new Scanner(line);
while (lineScan.hasNext()) {
String token = lineScan.next().trim(); // should I include trim?
char letterCheck = token.charAt(0);
// Checks to make sure the content of this file includes only numbers
if (Character.isLetter(letterCheck)) {
notAllNumbers = letterCheck + "";
}
colCount++; // Counts actual number of columns, divide by rowCount to get actual
}
lineScan.close();
}
// Checks to make sure there is not an extra integer on the first line
if (dimensions.length > 2) {
throw new IllegalCharacterException(
"Row and Column have already been provided on the first line of the file. The extra integer: "
+ """ + dimensions[2] + """ + " should not be included.");
} else if (!notAllNumbers.isEmpty()) {
throw new IllegalCharacterException(
"This value in your file: " + """ + notAllNumbers + """ + " is not a number.");
} else {
formatDimensions(dimensions, declaredRowStr, declaredColStr, rowCount, colCount);
}
}

public void formatDimensions(String dimensions, String declaredRowStr, String declaredColStr, int rowCount,
int colCount) throws IllegalCharacterException, NumberFormatException, FileNotFoundException {

int declaredRow = 0;
int declaredCol = 0;
// Catches if the variables on the first line are of type integer
try {
declaredRow = Integer.parseInt(declaredRowStr);
declaredCol = Integer.parseInt(declaredColStr);
fileContent(declaredRow, declaredCol, rowCount, colCount);
} catch (NumberFormatException e) {
throw new NumberFormatException("This value on the first line of your file:"
+ e.getMessage().substring(17, e.getMessage().length()) + " is not of type integer.");
}
}

public void fileContent(int declaredRow, int declaredCol, int rowCount, int colCount)
throws FileNotFoundException, IllegalCharacterException {

// Checks to see if row and column matches the actual number of rows and columns
double roundToRealRowCount = (rowCount / 1.0); // This is to account for rounding of
// integer
double roundToRealColCount = (colCount / roundToRealRowCount);// if row or column is not
// divided evenly

if (rowCount != declaredRow) {
throw new InputMismatchException("Number of rows declaration: " + "'" + declaredRow + "'"
+ " on first line does not match the actual number of rows in file.");
} else if (roundToRealColCount != declaredCol) {
throw new InputMismatchException("Number of columns declaration: " + "'" + declaredCol + "'"
+ " on first line does not match the actual number of columns in file.");
}
}
}









share|improve this question
























  • ...but I see fileContent method does have throws clause ....
    – Sharon Ben Asher
    Sep 19 '17 at 6:32










  • all the printing inside the catch clauses look very similar. should be put in a method.
    – Sharon Ben Asher
    Sep 19 '17 at 6:34













up vote
0
down vote

favorite
1









up vote
0
down vote

favorite
1






1





This was my original posting: Check that a data file contains the expected number of rows and columns of integers



I updated the code. Still what could I improve on?



Another question I have is how come my last method fileContent() does not need any throws declaration in the method header?



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

public class FormatChecker2 {

public static void main(String args) {
FormatChecker2 tester = new FormatChecker2(); // To avoid every method being static.

if (args.length == 0) {
System.out.println("Usage: $ java FormatChecker file1 [file2 ... fileN]");
} else {
for (String fileName : args) {
try {
tester.readInTextFile(fileName);
System.out.println(fileName + "");
System.out.println("VALID");
System.out.println();
} catch (FileNotFoundException notFound) {
System.out.println(notFound.getMessage() + "");
System.out.println(notFound + " (The system cannot find the file specified)");
System.out.println("INVALID");
System.out.println();
} catch (NumberFormatException notInt) {
System.out.println(fileName);
// String printMessage = notInt.toString().replaceAll("#.*?;", ""); "#" + file +
// ";"
System.out.println(notInt);
System.out.println("INVALID");
System.out.println();
} catch (InputMismatchException badContent) {
System.out.println(fileName);
System.out.println(badContent);
System.out.println("INVALID");
System.out.println();
} catch (IllegalCharacterException delChar) {
System.out.println(fileName);
System.out.println(delChar);
System.out.println("INVALID");
System.out.println();
}

}
}
}

public void readInTextFile(String fileName)
throws FileNotFoundException, IllegalCharacterException, NumberFormatException {
File file = new File(fileName);
if (file.exists() && file.isFile()) {
parseFile(file);
} else {
throw new FileNotFoundException(fileName);
}
}

public void parseFile(File file) throws FileNotFoundException, IllegalCharacterException {
Scanner fileScan = new Scanner(file);
String declaredRowCol = fileScan.nextLine().trim();
String dimensions = declaredRowCol.split("\s+");
String declaredRowStr = dimensions[0];
String declaredColStr = dimensions[1];
int rowCount = 0;
int colCount = 0;
String notAllNumbers = "";
while (fileScan.hasNextLine()) {
String line = fileScan.nextLine().trim();
if (!line.isEmpty()) {
rowCount++;// Counts actual number of rows
}
Scanner lineScan = new Scanner(line);
while (lineScan.hasNext()) {
String token = lineScan.next().trim(); // should I include trim?
char letterCheck = token.charAt(0);
// Checks to make sure the content of this file includes only numbers
if (Character.isLetter(letterCheck)) {
notAllNumbers = letterCheck + "";
}
colCount++; // Counts actual number of columns, divide by rowCount to get actual
}
lineScan.close();
}
// Checks to make sure there is not an extra integer on the first line
if (dimensions.length > 2) {
throw new IllegalCharacterException(
"Row and Column have already been provided on the first line of the file. The extra integer: "
+ """ + dimensions[2] + """ + " should not be included.");
} else if (!notAllNumbers.isEmpty()) {
throw new IllegalCharacterException(
"This value in your file: " + """ + notAllNumbers + """ + " is not a number.");
} else {
formatDimensions(dimensions, declaredRowStr, declaredColStr, rowCount, colCount);
}
}

public void formatDimensions(String dimensions, String declaredRowStr, String declaredColStr, int rowCount,
int colCount) throws IllegalCharacterException, NumberFormatException, FileNotFoundException {

int declaredRow = 0;
int declaredCol = 0;
// Catches if the variables on the first line are of type integer
try {
declaredRow = Integer.parseInt(declaredRowStr);
declaredCol = Integer.parseInt(declaredColStr);
fileContent(declaredRow, declaredCol, rowCount, colCount);
} catch (NumberFormatException e) {
throw new NumberFormatException("This value on the first line of your file:"
+ e.getMessage().substring(17, e.getMessage().length()) + " is not of type integer.");
}
}

public void fileContent(int declaredRow, int declaredCol, int rowCount, int colCount)
throws FileNotFoundException, IllegalCharacterException {

// Checks to see if row and column matches the actual number of rows and columns
double roundToRealRowCount = (rowCount / 1.0); // This is to account for rounding of
// integer
double roundToRealColCount = (colCount / roundToRealRowCount);// if row or column is not
// divided evenly

if (rowCount != declaredRow) {
throw new InputMismatchException("Number of rows declaration: " + "'" + declaredRow + "'"
+ " on first line does not match the actual number of rows in file.");
} else if (roundToRealColCount != declaredCol) {
throw new InputMismatchException("Number of columns declaration: " + "'" + declaredCol + "'"
+ " on first line does not match the actual number of columns in file.");
}
}
}









share|improve this question















This was my original posting: Check that a data file contains the expected number of rows and columns of integers



I updated the code. Still what could I improve on?



Another question I have is how come my last method fileContent() does not need any throws declaration in the method header?



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

public class FormatChecker2 {

public static void main(String args) {
FormatChecker2 tester = new FormatChecker2(); // To avoid every method being static.

if (args.length == 0) {
System.out.println("Usage: $ java FormatChecker file1 [file2 ... fileN]");
} else {
for (String fileName : args) {
try {
tester.readInTextFile(fileName);
System.out.println(fileName + "");
System.out.println("VALID");
System.out.println();
} catch (FileNotFoundException notFound) {
System.out.println(notFound.getMessage() + "");
System.out.println(notFound + " (The system cannot find the file specified)");
System.out.println("INVALID");
System.out.println();
} catch (NumberFormatException notInt) {
System.out.println(fileName);
// String printMessage = notInt.toString().replaceAll("#.*?;", ""); "#" + file +
// ";"
System.out.println(notInt);
System.out.println("INVALID");
System.out.println();
} catch (InputMismatchException badContent) {
System.out.println(fileName);
System.out.println(badContent);
System.out.println("INVALID");
System.out.println();
} catch (IllegalCharacterException delChar) {
System.out.println(fileName);
System.out.println(delChar);
System.out.println("INVALID");
System.out.println();
}

}
}
}

public void readInTextFile(String fileName)
throws FileNotFoundException, IllegalCharacterException, NumberFormatException {
File file = new File(fileName);
if (file.exists() && file.isFile()) {
parseFile(file);
} else {
throw new FileNotFoundException(fileName);
}
}

public void parseFile(File file) throws FileNotFoundException, IllegalCharacterException {
Scanner fileScan = new Scanner(file);
String declaredRowCol = fileScan.nextLine().trim();
String dimensions = declaredRowCol.split("\s+");
String declaredRowStr = dimensions[0];
String declaredColStr = dimensions[1];
int rowCount = 0;
int colCount = 0;
String notAllNumbers = "";
while (fileScan.hasNextLine()) {
String line = fileScan.nextLine().trim();
if (!line.isEmpty()) {
rowCount++;// Counts actual number of rows
}
Scanner lineScan = new Scanner(line);
while (lineScan.hasNext()) {
String token = lineScan.next().trim(); // should I include trim?
char letterCheck = token.charAt(0);
// Checks to make sure the content of this file includes only numbers
if (Character.isLetter(letterCheck)) {
notAllNumbers = letterCheck + "";
}
colCount++; // Counts actual number of columns, divide by rowCount to get actual
}
lineScan.close();
}
// Checks to make sure there is not an extra integer on the first line
if (dimensions.length > 2) {
throw new IllegalCharacterException(
"Row and Column have already been provided on the first line of the file. The extra integer: "
+ """ + dimensions[2] + """ + " should not be included.");
} else if (!notAllNumbers.isEmpty()) {
throw new IllegalCharacterException(
"This value in your file: " + """ + notAllNumbers + """ + " is not a number.");
} else {
formatDimensions(dimensions, declaredRowStr, declaredColStr, rowCount, colCount);
}
}

public void formatDimensions(String dimensions, String declaredRowStr, String declaredColStr, int rowCount,
int colCount) throws IllegalCharacterException, NumberFormatException, FileNotFoundException {

int declaredRow = 0;
int declaredCol = 0;
// Catches if the variables on the first line are of type integer
try {
declaredRow = Integer.parseInt(declaredRowStr);
declaredCol = Integer.parseInt(declaredColStr);
fileContent(declaredRow, declaredCol, rowCount, colCount);
} catch (NumberFormatException e) {
throw new NumberFormatException("This value on the first line of your file:"
+ e.getMessage().substring(17, e.getMessage().length()) + " is not of type integer.");
}
}

public void fileContent(int declaredRow, int declaredCol, int rowCount, int colCount)
throws FileNotFoundException, IllegalCharacterException {

// Checks to see if row and column matches the actual number of rows and columns
double roundToRealRowCount = (rowCount / 1.0); // This is to account for rounding of
// integer
double roundToRealColCount = (colCount / roundToRealRowCount);// if row or column is not
// divided evenly

if (rowCount != declaredRow) {
throw new InputMismatchException("Number of rows declaration: " + "'" + declaredRow + "'"
+ " on first line does not match the actual number of rows in file.");
} else if (roundToRealColCount != declaredCol) {
throw new InputMismatchException("Number of columns declaration: " + "'" + declaredCol + "'"
+ " on first line does not match the actual number of columns in file.");
}
}
}






java






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Sep 19 '17 at 0:09

























asked Sep 19 '17 at 0:03









dporth

123




123












  • ...but I see fileContent method does have throws clause ....
    – Sharon Ben Asher
    Sep 19 '17 at 6:32










  • all the printing inside the catch clauses look very similar. should be put in a method.
    – Sharon Ben Asher
    Sep 19 '17 at 6:34


















  • ...but I see fileContent method does have throws clause ....
    – Sharon Ben Asher
    Sep 19 '17 at 6:32










  • all the printing inside the catch clauses look very similar. should be put in a method.
    – Sharon Ben Asher
    Sep 19 '17 at 6:34
















...but I see fileContent method does have throws clause ....
– Sharon Ben Asher
Sep 19 '17 at 6:32




...but I see fileContent method does have throws clause ....
– Sharon Ben Asher
Sep 19 '17 at 6:32












all the printing inside the catch clauses look very similar. should be put in a method.
– Sharon Ben Asher
Sep 19 '17 at 6:34




all the printing inside the catch clauses look very similar. should be put in a method.
– Sharon Ben Asher
Sep 19 '17 at 6:34










1 Answer
1






active

oldest

votes

















up vote
0
down vote













You could use the split method in the String class to count the columns.



String columns = line.split(SEPARATOR);
int colCount = columns.length.





share|improve this answer























    Your Answer





    StackExchange.ifUsing("editor", function () {
    return StackExchange.using("mathjaxEditing", function () {
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    });
    });
    }, "mathjax-editing");

    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "196"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f176021%2fread-in-a-file-check-that-it-meets-certain-criteria%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote













    You could use the split method in the String class to count the columns.



    String columns = line.split(SEPARATOR);
    int colCount = columns.length.





    share|improve this answer



























      up vote
      0
      down vote













      You could use the split method in the String class to count the columns.



      String columns = line.split(SEPARATOR);
      int colCount = columns.length.





      share|improve this answer

























        up vote
        0
        down vote










        up vote
        0
        down vote









        You could use the split method in the String class to count the columns.



        String columns = line.split(SEPARATOR);
        int colCount = columns.length.





        share|improve this answer














        You could use the split method in the String class to count the columns.



        String columns = line.split(SEPARATOR);
        int colCount = columns.length.






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Aug 19 at 20:30









        Stephen Rauch

        3,75051530




        3,75051530










        answered Aug 19 at 19:56









        fpezzini

        664




        664






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f176021%2fread-in-a-file-check-that-it-meets-certain-criteria%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Mont Emei

            Province de Neuquén

            Journaliste