资源简介
判断某一个矩阵是否是一个幻方,如果是,将其输出到文件
代码片段和文件信息
package P1;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MagicSquare {
public MagicSquare() {
}
static boolean isLegalMagicSquare(String filename){
ArrayListdata = new ArrayList();
ArrayListsums = new ArrayList();
int right = 0;
int left = 0;
int temprows = 0;
int tempcols = 0;
int lines = 0;
File file = new File(filename);
int n = 0;
String regEx = “[ _‘~!@#$%^&*()+=|{}‘:;‘\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]“;
Pattern p = Pattern.compile(regEx);
Pattern pattern = Pattern.compile(“[0-9]*“);
int lastrow = 0;
BufferedReader reader = null;
try{
reader = new BufferedReader(new FileReader(file));
String tempString = null;
while ((tempString=reader.readLine())!=null){
lines++;
Matcher m = p.matcher(tempString);
if(m.find()){
System.out.println(“The numbers are not splitted by \\t“);
return false;
}
String []tokens = tempString.split(“\t“);
if(lastrow == 0){
lastrow = tokens.length;
}
n = tokens.length;
if(n!=lastrow) {
System.out.println(“It is not a matrix“);
return false;
}
for (int i = 0; i < n; i++) {
if (!pattern.matcher(tokens[i]).matches()){
System.out.println(“The numbers in this matrix are not all integers“);
return false;
}
data.add(Integer.valueOf(tokens[i]));
}
lastrow = n;
}
if(n!=lines)
{
System.out.println(“It is not a square matrix“);
return false;
}
for(int i=0;i for(int j=0;j temprows += data.get(n*i+j);
tempcols += data.get(i+n*j);
}
sums.add(tempcols);
sums.add(tempcols);
temprows = 0;
tempcols = 0;
}
for(int i=0; i left += data.get(i*n + i);
right += data.get(n*i + (n-i));
}
sums.add(left);
sums.add(right);
reader.close();
for(int i=0;i<2*n-1;i++){
if(! sums.get(i).toString().equals(sums.get(i+1).toString())){
return false;
}
}
}catch (IOException e){
e.printStackTrace();
评论
共有 条评论