给定二维整形数组int[][]
1.将其用矩阵的形式输出
2.设计方法,将上矩阵的一圈提取出来,并存储到新的数组db[20]中,该方法返回一圈数字的数目
3.存储上述数组db[20],并做读取测试。
1 import java.io.FileInputStream; 2 import java.io.FileOutputStream; 3 import java.io.IOException; 4 import java.io.ObjectInputStream; 5 import java.io.ObjectOutputStream; 6 import java.io.Serializable; 7 8 9 public class Test implements Serializable{ 10 //给定的数组 11 int[][] mb={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16},{17,18,19,20}}; 12 //用于存储一圈数字的数组 13 int[][] db=new int[16][1]; 14 15 public static void main(String[] args) { 16 // TODO Auto-generated method stub 17 Test test=new Test(); 18 test.print(test.mb, 1); 19 20 //提取一圈数字并现实 21 test.MoveWall(test.mb); 22 test.print(test.db, 2); 23 24 //存储文件 25 test.savefile2ser(test); 26 27 //将db[]清空并显示,用于下一步测试文件确实读取成功 28 test.db=new int[16][1]; 29 test.print(test.db, 2); 30 31 //读取文件并现实 32 test=new Test().readfilefser(); 33 test.print(test.db, 2); 34 35 } 36 37 //获取一圈数字,存储到db[],且返回数字的个数 38 public int MoveWall(int[][] a){ 39 int temp = 0; 40 for (int i = 0; i < a[a.length-1].length; i++) { 41 db[temp][0]=a[0][i]; 42 temp++; 43 } 44 temp--; 45 for (int i = 0; i < a.length; i++) { 46 db[temp][0]=a[i][a[a.length-1].length-1]; 47 temp++; 48 } 49 temp--; 50 for (int i = a[a.length-1].length-1; i >=0; i--) { 51 db[temp][0]=a[a.length-1][i]; 52 temp++; 53 } 54 temp--; 55 for (int i = a[a.length-1].length-1; i > 0; i--) { 56 db[temp][0]=a[i][0]; 57 temp++; 58 } 59 return temp; 60 61 } 62 //用于显示矩阵及db[] o=1显示矩阵,o=2显示db[] 63 public void print(int[][] temp,int o){ 64 if (o==1) { 65 for (int i = 0; i < temp.length; i++) { 66 for (int j = 0; j < temp[i].length; j++) { 67 System.out.print(temp[i][j]+" "); 68 } 69 System.out.println(); 70 } 71 }else if (o==2) { 72 for (int i = 0; i < temp.length; i++) { 73 for (int j = 0; j < temp[i].length; j++) { 74 System.out.print(temp[i][j]+" "); 75 } 76 } 77 System.out.println(); 78 }else { 79 System.out.println("wrong parameter o"); 80 } 81 } 82 83 //save file to File.ser 84 public void savefile2ser(Test test) { 85 try { 86 FileOutputStream file=new FileOutputStream("File.ser"); 87 ObjectOutputStream o=new ObjectOutputStream(file); 88 o.writeObject(test); 89 o.close(); 90 91 } catch (IOException e) { 92 // TODO Auto-generated catch block 93 e.printStackTrace(); 94 } 95 } 96 //read file from File.ser 97 public Test readfilefser(){ 98 try { 99 FileInputStream file=new FileInputStream("File.ser"); 100 ObjectInputStream o=new ObjectInputStream(file); 101 Test test=(Test) o.readObject(); 102 o.close(); 103 return test; 104 } catch (Exception e) { 105 // TODO Auto-generated catch block 106 e.printStackTrace(); 107 } 108 return null; 109 } 110 }