diff --git a/AcceptFile.java b/AcceptFile.java new file mode 100644 index 0000000000000000000000000000000000000000..f4ebc4c84d4bf425192b866ef7331cd197e98ea0 --- /dev/null +++ b/AcceptFile.java @@ -0,0 +1,73 @@ +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +/** +* AcceptFile class that reads a text file and identifies whether it is in the +* following format: +* 1) First two lines must contain exactly one integer (representing width & length) +* 2) There must be width * height more lines after +* 3) Each of these lines must have exactly 3 integers with values within 0 to 100 inclusive +* @param String fileName +* @return error messages if criterias are not met +*/ + +public class AcceptFile { + public static void main(String[] args) { + String fileName = "correctInput.txt"; // Replace with the name of text file to check + + // BufferedReader is used to parse through text file line by line + try (BufferedReader br = new BufferedReader(new FileReader(fileName))) { + // Read and check the first two lines to get the width and height + String line = br.readLine(); + int width = Integer.parseInt(line.trim()); + line = br.readLine(); + int height = Integer.parseInt(line.trim()); + + //to save the point in the file after reading width and height (line 3) + br.mark(1000); + + if (width <= 0 || height <= 0) { + System.out.println("Error: width and height must be positive integers."); + return; + + } + + // Check that there are width * height more lines in the file + int expectedNumLines = width * height; + int currentNumLines = 0; // Counter to keep track number of lines + while ((line = br.readLine()) != null) { + currentNumLines += 1; + } + if (expectedNumLines != currentNumLines) { + System.out.println("Error: Expected " + expectedNumLines + " lines, but found " + currentNumLines + " lines."); + return; + } + + // Check that each of the following lines has exactly 3 integers between 0 and 100 + br.reset(); // puts us back to line 3 and no longer need to skip first two lines + + while ((line = br.readLine()) != null) { + String[] tokens = line.split("\\s+"); + if (tokens.length != 3) { + System.out.println("Error: Line \"" + line + "\" does not contain exactly 3 integers."); + return; + } + for (String token : tokens) { + int value = Integer.parseInt(token); + if (value < 0 || value > 100) { + System.out.println("Error: Value " + value + " is not between 0 and 100."); + return; + } + } + } + + // When text file meets all the requirements + System.out.println("The file \"" + fileName + "\" meets all the requirements."); + } catch (IOException e) { + System.out.println("Error reading file \"" + fileName + "\": " + e.getMessage()); + } catch (NumberFormatException e) { + System.out.println("Error parsing integer \"" + "\": " + e.getMessage()); + } + } +} +