java实现从txt文件读取数据并保存至二维数组及判断其是否是方阵

在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");
			}
		}
	}
}




  • 6
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值