📄 sudokufile.java
字号:
// Name: Tsang Kai Ming, Patrick (25)
// Couse Code 41300/1 Group V
// Subject: ICT-1414 Object-oriented Programming
// Sudoku Assignment 2 File (Java Programming)
import java.io.*;
import java.util.StringTokenizer;
class SudokuFile {
// A static method to read the specified file to a Sudoku object
public static Sudoku readFile(String filename) {
// create an empty sudoku to store the result
Sudoku sdk = new Sudoku();
// you need to have try...catch (or throw IOExceptin)
// whenever you read/write a file
try {
// open the file using a buffered reader
BufferedReader in = new BufferedReader (new FileReader(filename));
// read in a line
String line = in.readLine();
// line counter
int i = 0;
// if the line is successfully read,
while(line!=null) {
// if more than 9 lines, the file format is wrong
if(i>=9) throw new SudokuFileFormatException();
// break it down using string tokenizer, cut down by " " or "|"
StringTokenizer st = new StringTokenizer(line, " |");
// if there are 9 tokens, (the horizontal lines will not have 9 tokens)
if(st.countTokens()==9) {
// we use a for loop to put in the numbers one by one
for (int j=0; j<9; j++) {
// Integer.parseInt is used to convert the String read to int
sdk.put(Integer.parseInt(st.nextToken()), i, j);
}
i++;
}
// read the next line
line = in.readLine();
} // while loop
// if number of rows is not 9, the file format is wrong
if(i!=9) throw new SudokuFileFormatException();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Cannot read sudoku file: " + filename + ". Program aborted.");
sdk = null;
}
// return the filled sudoku object
return sdk;
}
// You may want to test your program by un-commenting the followings:
// read the given s1.txt to test the files
public static void main (String args[]) {
System.out.println(readFile("s1.txt"));
}
}
class SudokuFileFormatException extends IOException {
public SudokuFileFormatException () {
super("Your file is not in Sudoku format");
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -