1
\$\begingroup\$

This is a class I wrote check to check the format of .dat files. My code makes sure that the content of the files satisfies the conditions.

A file can be deemed invalid if:

  • The file can't be found.
  • The file contains data in the wrong format.
  • The values don't match the expected data types.
  • There are fewer rows and/or columns of data than specified.
  • There are more rows and/or columns of data than specified.

e.g.

 3 3
 1 4 5
 7 5 3
 2 9 0

What can I do to make my code more efficient?

// Should we check to see if numbers are seperated by more than one space?


  public class FormatChecker {
        public static void main(String[] args) {
            // Checks to make sure at least one file has been provided via command line
            if (args.length > 0) {
                for (String fileName : args) {
                    File file = new File(fileName);
                    // Checks to make sure file is a file and that the file exists
                    if (file.exists() && file.isFile()) {
                        // Catches if file still exists and is a file
                        try {
                            Scanner fileScan = new Scanner(file);
                            String trueRowCol = fileScan.nextLine().trim();
                            String[] dimToken = trueRowCol.split("\\s+");
                            String trueRowStr = dimToken[0];
                            String trueColStr = dimToken[1];
                            // Checks to make sure there is not an extra integer on the first line
                            if (dimToken.length > 2) { // should I include new lines?
                                InputMismatchException notDim = new InputMismatchException(
                                        "Row and Column have already been provided on the first line of the file. The extra integer: "
                                                + "'" + dimToken[2] + "'" + " should not be included.");
                                System.out.println(file + "");
                                System.out.println(notDim);
                                System.out.println("INVALID");
                                System.out.println();
                            } else {
                                // Catches if the variables on the first line are of type integer
                                int trueRow = 0;
                                int trueCol = 0;
                                try {
                                    trueRow = Integer.parseInt(trueRowStr);
                                    trueCol = Integer.parseInt(trueColStr);
                                    // Catches if a token is not a number in the file
                                    int rowCount = 0;
                                    int colCount = 0;
                                    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?
                                            double intToken = Double.parseDouble(token);
                                            colCount++;// Counts actual number of columns, divide by rowCount to get actual
                                        }
                                    }
                                    // 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 != trueRow) {
                                        InputMismatchException notRow = new InputMismatchException(
                                                "Number of rows decleration: " + "'" + trueRow + "'"
                                                        + " on first line does not match the actual number of rows in file.");
                                        System.out.println(file + "");
                                        System.out.println(notRow);
                                        System.out.println("INVALID");
                                        System.out.println();
                                    } else if (roundToRealColCount != trueCol) {

                                        InputMismatchException notCol = new InputMismatchException(
                                                "Number of columns decleration: " + "'" + trueCol + "'"
                                                        + " on first line does not match the actual number of columns in file.");
                                        System.out.println(file + "");
                                        System.out.println(notCol);
                                        System.out.println("INVALID");
                                        System.out.println();
                                    } else {
                                        System.out.println(file + "");
                                        System.out.println("VALID");
                                        System.out.println();
                                    }
                                } catch (NumberFormatException notNum) {
                                    NumberFormatException notDouble = new NumberFormatException(
                                            "This value in your file: " + notNum.getMessage() + " is not a number.");
                                    System.out.println(file + "");
                                    System.out.println(notDouble);
                                    System.out.println("INVALID");
                                    System.out.println();
                                    // System.out.println(file + "");
                                    // System.out.println(notNum); // Says input string is that ok? How to change?
                                    // System.out.println("INVALID");
                                    // System.out.println();
                                }
                            }
                        } catch (FileNotFoundException notFound) {
                            System.out.println(file + "");
                            System.out.print(notFound);
                            System.out.println("INVALID");
                            System.out.println();
                        }
                    } else {
                        System.out.println(file + "");
                        FileNotFoundException noFile = new FileNotFoundException(
                                file + " (The system cannot find the file specified)");
                        System.out.println(noFile);
                        System.out.println("INVALID");
                        System.out.println();
                    }
                }
            } else {
                System.out.println("Usage: $ java FormatChecker file1 [file2 ... fileN]");
            }
        }
    }
\$\endgroup\$
1
\$\begingroup\$
  1. Break up your code into methods, each with clear purpose and description

  2. Avoid nested if-else blocks if possible

  3. Use exceptions for error conditions, rather than if-else blocks

  4. use one method for reporting errors, instead of repeating the code

Instead of:

if (args.length > 0) {
    if(file.exists() && file.isFile()){
    // do a lot of work here
    } else {
    //report error
    }
}

You should reverse the condition and exit on error. Like this:

if (args.length == 0) {
{
    // Signal error and exit
}
if(!file.exists() || !(file.isFile()))
{
   // Signal error and exit
}

//Do some work

Or, better

try {
// do some work
   if(!file.exists())
   {
      throw new RuntimeException("Input file not found");
   }
}
catch(Exception x)
{
   this.reportError(x);
}
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.