我的矩阵有问题。我在 txt 文件中有一个矩阵。这个矩阵看起来:
231 324 123
345 565 234
657 234 654
我想替换元素以形成:
654 234 657
234 565 345
231 324 123
我有一个带有替换元素的算法:3-1-i,其中 i 是从数组中选择的元素的数量。我在如何读取文件并将元素保存到数组以及如何实现此循环方面遇到问题。这是我尝试读取 txt 文件并将元素保存到数组:
List<String[]> rows = new ArrayList<String[]>();
while ((line = bfr.readLine()) != null) {
String[] row = line.split(" ");
rows.add(row);
}
System.out.println(rows.toString());
但是我得到了[Ljava.lang.String;@525483cd
结果。
谁能帮助我完成这个循环并阅读这个矩阵?
最佳答案
注意:我使用带有换行符 \n
的 String ,如果从文件中获取字符串,则工作方式相同。
import java.io.*;
import java.util.StringTokenizer;
public class file {
public static void main(String args[]) throws IOException {
String s = "231 324 123 \n 345 565 234 \n 657 234 654";
StringTokenizer n = new StringTokenizer(s);
String [] arr = new String[9];
int nn = 0;
while(n.hasMoreElements()){
arr[nn] = n.nextToken();
nn+=1;
}
for(int iii = (arr.length -1); iii >=0 ; iii--){
System.out.print(arr[iii] + " ");
if((iii % 3) == 0) {
System.out.println();
}
}
}
}
输出为
654 234 657
234 565 345
123 324 231
编辑从文件中读取字符串
public static void main(String args[]) throws IOException {
int i;
FileInputStream fin = new FileInputStream("files.txt");
String n = "";
do {
i = fin.read();
n += (char) i;
} while(i != -1);
fin.close();
//String n now contains the contents of the file
}
关于java - txt 文件中的矩阵 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8172609/