我正在尝试编写一个程序来读取数组文件(排列为行作为第一个字符,列作为下一个字符,然后是一盒 RxC 术语)并尝试确定是否有五个水平、垂直或对角线上相邻的字符相同,颜色不同(在我的 GUI 主程序中)
代码非常慢,而且只适用于较小的数组?我不明白我做错了什么。
文件看起来像这样:
5 4
1 2 3 4 5
1 2 3 4 5
7 3 2 0 1
6 1 2 3 5
代码:
public class fiveinarow
{
int[][] Matrix = new int [100][100];
byte[][] Tag = new byte [100][100];
int row, col;
String filepath, filename;
public fiveinarow()
{
row = 0;
col = 0;
filepath = null;
filename = null;
}
public void readfile()
{
JFileChooser chooser = new JFileChooser();
chooser.setDialogType(JFileChooser.OPEN_DIALOG );
chooser.setDialogTitle("Open Data File");
int returnVal = chooser.showOpenDialog(null);
if( returnVal == JFileChooser.APPROVE_OPTION)
{
filepath = chooser.getSelectedFile().getPath();
filename = chooser.getSelectedFile().getName();
}
try
{
Scanner inputStream = new Scanner(new FileReader(filepath));
int intLine;
row = scan.nextInt();
col = scan.nextInt();
for (int i=0; i < row; i++)
{
for (int j = 0 ; j < col; j++)
{
int[][]Matrix = new int[row][col];
Matrix[i][j] = inputStream.nextInt();
}
}
}
catch(IOException ioe)
{
System.exit(0);
}
}
当我计算一个 7x7 时,我得到了打开和处理的确认,给出了一个全零的数组 (7x7)。 当我计算 15x14 时,我得到“线程“AWT-EventQueue-0”错误中的异常,并且在处理时没有数组。
最佳答案
一些建议:
- 创建一个返回 int[][] 的方法以读入您的输入文件
- 读取行和列后,创建矩阵int[][] result = new int[row][column];
- 在循环中,将每个整数读入矩阵 (result[i][j] = scan.nextInt();
不要忘记在扫描完一行中的所有数字后移动到下一行'
你可以使用类似的东西:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
import javax.swing.JFileChooser;
public class ReadMatrix {
static ReadMatrix mReadMatrix;
int[][] matrix;
int row, col;
String filepath, filename;
/**
* @param args
*/
public static void main(String[] args) {
mReadMatrix = new ReadMatrix();
mReadMatrix.readfile();
}
// int[][] Matrix = new int [100][100];
// byte[][] Tag = new byte [100][100];
public void readfile() {
JFileChooser chooser = new JFileChooser();
chooser.setDialogType(JFileChooser.OPEN_DIALOG);
chooser.setDialogTitle("Open Data File");
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
filepath = chooser.getSelectedFile().getPath();
filename = chooser.getSelectedFile().getName();
}
Scanner inputStream;
try {
inputStream = new Scanner(new FileReader(filepath));
row = inputStream.nextInt();
col = inputStream.nextInt();
System.out.println(" matrix is " + row + " rows and " + col + " columns");
matrix = new int[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
matrix[i][j] = inputStream.nextInt();
System.out.println(" " + i + "," + j + ": " + matrix[i][j]);
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
关于java - 将读取文件中的整数字符存储到二维数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22365643/