
java 用 split 存入 二维数组
aaa 22 999
bbb 21 998
ccc 20 997
ddd 19 996
eee 18 995
fff 17 994
ggg 16 993
我想用String[][] s=null; BufferedReader 的readLine() 和 split() 方法 存入这个二维数组
达到这个效果 :
s[0][1]="aaa"
s[0][2]="22"
s[0][3]="999"
s[1][0]="bbb"
.....
请问如何实现? 谢谢。 展开
解题思路,用 BufferedReader 来定义一个输入流,根据readLine方法一行一行的读取数据放到字符串里面,每读完一行数据,根据字符串的空格把这个字符串拆分成一个一维数组,然后把这个一维数组赋给二维数组就可以了,程序如下。
import java.io.*;
public class FileOperationTest {
public static void main(String[] args)throws Exception{
//创建输入流用来读取文件file.txt。
FileInputStream file=new FileInputStream("D:/file.txt");
InputStreamReader in=new InputStreamReader(file);
BufferedReader buffer=new BufferedReader(in);
//定义用来保存文件内容的二维数组。
String[][] result=new String[7][3];//因为你的文件给出的是7行3列的二维数组。
//定义一个一维临时数组,用来保存读取的每一行。
String[] array=new String[3];
//读取文件。
int count=0;//计数,用来对二维数组的行进行计数。
String temp=null;//临时变量
while((temp=buffer.readLine())!=null){
array=temp.split(" ");//从文件中读到的行数据转换为一维数组。
for(int i=0;i<array.length;i++){
result[count][i]=array[i];
}
count++;
}
for(int i=0;i<7;i++){//输出二维数组。
for(int j=0;j<3;j++){
System.out.print("s["+i+"]"+"["+j+"]="+result[i][j]+" ");
if(j==2){//输出三个数就换行。
System.out.println();
}
}
}
}
}
输出结果:
注意:要在D盘下面新建一个file.txt的文件,这里我放在D盘,并且文件的内容,输入你提供的数据。
public class ArrayParser {
public static void main(String[] args) {
String[][] arr = new String[7][3];
arrayParser(arr);
}
public static String[][] arrayParser(String d[][]){
Scanner scanner = new Scanner(System.in);
System.out.println("请输入字符串:");
String s = scanner.next();
System.out.println("拆分后的double数组:");
String[] sFirst = s.split("\\n");//第一维
d = new double[sFirst.length][];
for(int i = 0; i < d.length; i++){
String[] sSecond = sFirst[i].split(" ");//第二维
d[i] = new String[sSecond.length];
for(int j = 0; j < d[i].length; j++){
d[i][j] = sSecond[j];
System.out.print("d["+i+"]["+j+"] = "+d[i][j]+" ");
}
System.out.println();
}
return d;
}
}
int column= 0 ;
StringBuffer txt=new StringBuffer();//临时变量
String temp = null ;
while((temp=buffer.readLine())!=null){
txt.append(temp+" ");
if(column== 0) {
column= temp.split(" ").length;
}
}
String[] all = txt.toString().split(" ");
int row= all%column==0?all/column:(int)all/row+1;
String[][] s = new String[row][column];
for(int i=0;i<all.length;i++) {
s[(int)i/column][i%column] = all[i];
}