想txt中写随机二维数组
import java.io.*;
public class createarray {
public static void main(String [] args) throws IOException
{
String s;
int dim=0;
prt("please input the dimension:");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
s=br.readLine();
dim=Integer.parseInt(s);
int temp[][]=new int[dim][dim];
File file=new File("E:\\test.txt");
FileWriter out=new FileWriter(file);
for(int i=0;i<dim;i++)
{
for(int j=0;j<=i;j++)
{
if(i == j)
{
temp[i][j]=0;
}
else
{
int rand=(int)(Math.random()*90+10);
temp[i][j]=rand;
temp[j][i]=rand;
}
}
}
for(int i=0;i<dim;i++)
{
for(int j=0;j<dim;j++)
{
int t=temp[i][j];
out.write(t+" ");
}
out.write("\r\n");
}
out.close();
}
static void prt(String s)
{
System.out.println(s);
}
}
0 58 68 36 81 88 92 30 31 87 70 88 33 40 50 37 92 65 34 22
58 0 14 52 78 15 42 87 47 75 56 94 49 72 57 20 51 63 92 85
68 14 0 45 93 93 12 81 51 56 96 91 46 44 56 87 88 24 75 16
36 52 45 0 32 47 96 58 74 49 17 77 64 80 25 58 88 43 78 76
81 78 93 32 0 67 16 26 46 29 37 77 92 50 42 89 20 96 34 55
88 15 93 47 67 0 23 74 71 96 70 38 70 19 88 42 88 99 86 41
92 42 12 96 16 23 0 17 77 29 98 25 92 58 31 74 86 71 15 63
30 87 81 58 26 74 17 0 55 54 17 16 17 80 52 42 59 12 99 39
31 47 51 74 46 71 77 55 0 51 65 37 64 41 14 38 29 25 21 99
87 75 56 49 29 96 29 54 51 0 57 31 99 47 78 87 34 26 91 85
70 56 96 17 37 70 98 17 65 57 0 91 54 53 26 41 26 90 91 13
88 94 91 77 77 38 25 16 37 31 91 0 64 42 81 51 14 75 94 71
33 49 46 64 92 70 92 17 64 99 54 64 0 25 77 18 13 92 15 17
40 72 44 80 50 19 58 80 41 47 53 42 25 0 17 97 74 60 87 98
50 57 56 25 42 88 31 52 14 78 26 81 77 17 0 71 22 69 50 86
37 20 87 58 89 42 74 42 38 87 41 51 18 97 71 0 36 73 78 82
92 51 88 88 20 88 86 59 29 34 26 14 13 74 22 36 0 68 41 75
65 63 24 43 96 99 71 12 25 26 90 75 92 60 69 73 68 0 14 11
34 92 75 78 34 86 15 99 21 91 91 94 15 87 50 78 41 14 0 76
22 85 16 76 55 41 63 39 99 85 13 71 17 98 86 82 75 11 76 0
读二维数组
import java.io.*;
public class city {
public int cityarray[][];
static public int N=20;
city()
{
cityarray=new int[N][N];
}
public void getarray() throws NumberFormatException, IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(
new File("E:\\test.txt"))));
String s;
int i = 0;
while((s=br.readLine())!=null && i<N)
{
String []str = s.split("\\ "); // 将 lineContent 按数字拆分
for(int j = 0; j <N; j++)
{
cityarray[i][j] = Integer.parseInt(str[j]);
}
i++;
}
for(int x=0;x<N*N;x++)
{
int temp=cityarray[x/N][x%N];
if(x%N==0 && x!=0 )
{
System.out.println("");
System.out.print(temp+" ");
}
else if(x%N != 0 || x==0)
{
System.out.print(temp+" ");
}
}
}
}