在HIT第一次软件构造的实验中,第一个实验需要题目所述的方法,而在网上寻找的过程中,能够真正使用的方法并不多,于是通过寻求老师及同学帮助,结合网络资料的方法,最终构建出以下代码。
由于本人也是java初学者,在代码中已有详细的注释(防止自己将来读不懂自己曾写的代码),所以不在文字方面过多赘述。
补充说明:使用的jdk版本为1.8
package hello;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class readTest {
public static void main(String[] args) throws IOException {
String fileName; //所读文件名
System.out.println("Please input a file name:");
Scanner in = new Scanner(System.in);
fileName = in.nextLine(); //输入所读文件名
Read(fileName);
in.close();
}
public static void Read(String fileName) throws IOException {//此处填写所读文件名
/*
* 文件读入
*/
String filePath = "src/foreverTest/txt/" + fileName; //文件地址+文件名
FileReader in = null;
try {
in = new FileReader(filePath);
} catch (FileNotFoundException e) {
System.out.println("File doesn't exsit!");
return ;
}
/*
* 使用BufferedReader读入并保存
*/
BufferedReader br = new BufferedReader(in);
ArrayList<String> list = new ArrayList<String>();
String s = null;
while(true) {
try {
s = br.readLine();
} catch(IOException e) {
e.printStackTrace();
}list.add(s);
if(s == null)
break;
}
/*
* 创建矩阵
*/
int colLength; //列数
int rowLength; //行数
rowLength = list.size() - 1;
String num0 = list.get(0);
String[] line0 = num0.split("\t");
colLength = line0.length;
int[][] square = new int[rowLength][colLength]; //幻方
/*
* 将数据写入二维数组
*/
try {
for (int i = 0; i < rowLength; i++) {
String numx = list.get(i);
String[] linex = numx.split("\t");
for (int j = 0; j < colLength; j++) {
if (Integer.valueOf(linex[j]) <= 0) { // 判断是否有输入为非正整数或未用'\t'分隔
System.out.println("Non positive integer or input format error!");
return ;
}
else
square[i][j] = Integer.valueOf(linex[j]);
}
}
} catch (Exception e) { //判断是否为矩阵
System.out.println("Not a matrix!");
return;
}
br.close();
Print(colLength, rowLength, square);
}
public static void Print(int colLength, int rowLength, int[][] square) {
for (int i = 0; i < rowLength; i++) {
if (i > 0)
System.out.print("\n");
for (int j = 0; j < colLength; j++) {
System.out.print(square[i][j] + "\t");
}
}
}
}