首页 > 代码库 > 数组博客

数组博客

一.   动手动脑1

  1. 代码

public class PassArray {

    

     public static void main(String[] args) {

            int a[] = { 1, 2, 3, 4, 5 };

            String output = "The values of the original array are:\n";

 

            for (int i = 0; i < a.length; i++)

                   output += "   " + a[i];

 

            output += "\n\nEffects of passing array " + "element call-by-value:\n"

                          + "a[3] before modifyElement: " + a[3];

 

            modifyElement(a[3]);//按值传递,值不变。

 

            output += "\na[3] after modifyElement: " + a[3];

 

            output += "\n Effects of passing entire array by reference";

 

            modifyArray(a); // array a passed call-by-reference按引用传递,值都变了

 

            output += "\n\nThe values of the modified array are:\n";

 

            for (int i = 0; i < a.length; i++)

                   output += "   " + a[i];

           

            System.out.println(output);

     }

 

     public static void modifyArray(int b[]) {

            for (int j = 0; j < b.length; j++)

                   b[j] *= 2;

     }

 

     public static void modifyElement(int e) {

            e *= 2;

     }

 

}

  2.实验结果:

    技术分享

  3.实验分析:分别是引用传递和值传递。使用引用传递时,如果方法中有代码更改了数组元素的值,实际上是直接修改了原始数组元素。后者按值传递,方法体中只是原始数据元素的一个拷贝,所以不会更改。

 二.课堂练习1

 

   1.实验代码:

 

            publicclass ArrayInRam {

 

     publicstaticvoid main(String[] args) {

 

            // 定义并初始化数组,使用静态初始化

 

            int[] a = { 5, 7, 20 };

 

            System.out.println("a数组中的元素:");

 

            // 循环输出a数组的元素

 

            for (int i = 0; i < a.length; i++) {

 

                   System.out.print(a[i] + ",");

 

            }

 

            // 定义并初始化数组b,使用动态初始化

 

            int[] b = newint[4];

 

            // 输出b数组的长度

 

            System.out.println("\nb数组的初始长度为:" + b.length);

 

            // 因为aint[]类型,b也是int[]类型,所以可以将a的值赋给b

 

            // b的长度改变的原因是:b引用指向a引用指向的数组

 

            b = a;

 

            System.out.println("b=a,赋值之后,b数组的元素为:");

 

            // 循环输出b数组的元素

 

           

 

            for (int i = 0; i < b.length; i++) {

 

                   System.out.print(b[i] + ",");

 

            }

 

 

 

            // 再次输出b数组的长度

 

            System.out.println("\n赋值之后,b数组的长度为:" + b.length);

 

     }

 

}

 

2.实验结果:

    技术分享

3.原因分析:b数组起初定义的长度为4,而将数组a赋值给数组b是让b引用指向a引用指向的数组,所以后面长度会变。

三.动手动脑2

   1.代码:

      

import java.io.*;

 

publicclass QiPan

{

     //定义一个二维数组来充当棋盘

     private String[][] board;

     //定义棋盘的大小

     privatestaticintBOARD_SIZE = 15;

     publicvoid initBoard()

     {

            //初始化棋盘数组

            board = new String[BOARD_SIZE][BOARD_SIZE];

            //把每个元素赋为"",用于在控制台画出棋盘

            for (int i = 0 ; i < BOARD_SIZE ; i++)

            {

                   for ( int j = 0 ; j < BOARD_SIZE ; j++)

                   {

                          board[i][j] = "";

                   }

            }

     }

     //在控制台输出棋盘的方法

     publicvoid printBoard()

     {

            //打印每个数组元素

            for (int i = 0 ; i < BOARD_SIZE ; i++)

            {

                   for ( int j = 0 ; j < BOARD_SIZE ; j++)

                   {

                          //打印数组元素后不换行

                          System.out.print(board[i][j]);

                   }

                   //每打印完一行数组元素后输出一个换行符

                   System.out.print("\n");

            }

     }

    publicstaticvoid main(String[] args)throws Exception

    {

        QiPan gb = new QiPan();

            gb.initBoard();

            gb.printBoard();

            //这是用于获取键盘输入的方法

            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

            String inputStr = null;

                System.out.println("请输入您下棋的座标,应以x,y的格式:");

            //br.readLine():每当在键盘上输入一行内容按回车,刚输入的内容将被br读取到。

            while ((inputStr = br.readLine()) != null)

            {

                   //将用户输入的字符串以逗号(,)作为分隔符,分隔成2个字符串

                   String[] posStrArr = inputStr.split(",");

                   //2个字符串转换成用户下棋的座标

                   int xPos = Integer.parseInt(posStrArr[0]);

                   int yPos = Integer.parseInt(posStrArr[1]);

                   //把对应的数组元素赋为"●"

                   gb.board[xPos - 1][yPos - 1] = "●";                           

                   /*

                    电脑随机生成2个整数,作为电脑下棋的座标,赋给board数组。

                    还涉及

                          1.座标的有效性,只能是数字,不能超出棋盘范围

                          2.如果下的棋的点,不能重复下棋。

                          3.每次下棋后,需要扫描谁赢了

                    */

                   gb.printBoard();

                   System.out.println("请输入您下棋的座标,应以x,y的格式:");

            }

    }

}

 

    2.实验结果截图:

    技术分享

3.程序分析:首先定义一个二维数组,长度均为15,然后建立一个棋盘方法,利用循环语句,每行15+号,一共1515+号,为棋盘的最初是状态,然后再建立一个输出方法,用一个循环把每一行的都棋盘输出,每行输出15个之后进行换行,然后在让用户输入坐标形式的下棋位置,再以逗号为分隔符,分成两部分x,y,然后将用户所选的下棋图标●将gb.board[x-1][y-1]位置的+号替换,输出结果即可。

四.动手动脑31):

   1.代码:

                   publicclass Num2Rmb

{

     private String[] hanArr = {"" , "" , "" , "" , "" ,

            "" , "" , "" , "" , ""};

     private String[] unitArr = {"" , "" , "","","十万","百万"};

     /**

      * 把一个四位的数字字符串变成汉字字符串

      * @param numStr 需要被转换的四位的数字字符串

      * @return四位的数字字符串被转换成的汉字字符串。

      */

     String toHanStr(String numStr)

     {

            String result = "";

            int numLen = numStr.length();

    

            for (int i = 0 ; i < numLen ; i++ )      

            {

 

                   int num = numStr.charAt(i) - 48;

                   if ( i != numLen - 1 && num != 0)

                   {

                          result += hanArr[num] + unitArr[numLen - 2 - i];

                   }

    

                   else

                   {

    

                          if(result.length()>0 && hanArr[num].equals("") && result.charAt(result.length()-1)==)

                                 continue;

                          result += hanArr[num];

                   }

            }

 

            if(result.length()==1)

                   return result;

           

            int index=result.length()-1;

            while(result.charAt(index)==){

                   index--;

            }

            if(index!=result.length()-1)

                   return result.substring(0,index+1);

            else {

                   return result;

            }

     }

 

    publicstaticvoid main(String[] args)

    {       

            Num2Rmb nr = new Num2Rmb();

            System.out.println("只支持整数(0~百万)");

 

            System.out.println(nr.toHanStr("0"));

            System.out.println(nr.toHanStr("1"));

            System.out.println(nr.toHanStr("10"));

            System.out.println(nr.toHanStr("15"));

            System.out.println(nr.toHanStr("110"));

            System.out.println(nr.toHanStr("123"));

            System.out.println(nr.toHanStr("105"));

            System.out.println(nr.toHanStr("1000"));

            System.out.println(nr.toHanStr("1100"));

            System.out.println(nr.toHanStr("1110"));

            System.out.println(nr.toHanStr("1005"));

            System.out.println(nr.toHanStr("1105"));

            System.out.println(nr.toHanStr("1111"));

            System.out.println(nr.toHanStr("10000"));

            System.out.println(nr.toHanStr("10001"));

            System.out.println(nr.toHanStr("10011"));

            System.out.println(nr.toHanStr("10111"));

            System.out.println(nr.toHanStr("11111"));

            System.out.println(nr.toHanStr("11000"));

            System.out.println(nr.toHanStr("11100"));

            System.out.println(nr.toHanStr("11110"));

            System.out.println(nr.toHanStr("101110"));

            System.out.println(nr.toHanStr("1001110"));

           

    }

}

 

    2.实验结果:

  技术分享

五.动手动脑32):

    1.代码:

     publicclass complicate {

 

     /**

      * @param args

      */

     private String [] han={ "","" , "" , "" , "" ,

                   "" , "" , "" , "" , ""};

     private String [] unit={"","","","","","","","拾萬","佰萬"};//121.21

    

     String toHan(String numstr)

     {

            String result="";

            int len=numstr.length();

            int position=0;

            position=numstr.indexOf(‘.‘);

            if(position>0)

            {

            for(int i=0;i<len;i++)

            {

                   int num=numstr.charAt(i)-48;

           

           

                   if((num!=0&&i<position))

                   {

                          result+=han[num]+unit[len-2-i];

                   }

                   elseif(num!=0&&i>position)

                   {

                          result+=han[num]+unit[len-1-i];

                   }

                   elseif(num==0&&i<len-1)

                   {

                          result+=han[num];

                   }

           

            }

            }

 

         return  result;

           

     }

     publicstaticvoid main(String[] args) {

            // TODO Auto-generated method stub

            complicate com=new complicate();

            System.out.println("请输入千万以内的钱,精确到分:");

            System.out.println(com.toHan("123.52"));

           

     }

 

}

 

    2.实验截图:

        技术分享

六.动手动脑4

   1.代码:

            import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

publicclass BigInteger {

 

     publicstaticvoid main(String[] args) throws IOException {

            // TODO Auto-generated method stub

            BigNumber input;

            System.out.println("输入一个正整数:");

            input = inputInteger();

            System.out.println("输入另一个正整数:");

            int a[] = inputArray();

            System.out.println("两个数的和是:");

            display(input.add(a));

           

     }

     publicstaticint[] inputArray()throws IOException{

            InputStreamReader reader = new InputStreamReader(System.in);

            BufferedReader input = new BufferedReader(reader);

            String number = input.readLine();

           

            char temp[] = number.toCharArray();

            int array[] = newint[temp.length];

            for(int i=0; i<temp.length; i++){

                   if(temp[i] < ‘0‘ || temp[i] > ‘9‘){

                          System.out.println("输入错误!");

                          System.exit(1);

                   }

                   array[i] = temp[i]-‘0‘;

            }

            return array;

     }

     publicstatic BigNumber inputInteger()throws IOException{

            InputStreamReader reader = new InputStreamReader(System.in);

            BufferedReader input = new BufferedReader(reader);

            String number = input.readLine();

           

            char temp[] = number.toCharArray();

            int array[] = newint[temp.length];

            for(int i=0; i<temp.length; i++){

                   if(temp[i] < ‘0‘ || temp[i] > ‘9‘){

                          System.out.println("输入错误!");

                          System.exit(1);

                   }

                   array[i] = temp[i]-‘0‘;

            }

            BigNumber a = new BigNumber(array);

            return a;

     }

     publicstaticvoid display(int[] a){

            for(int i = 0; i < a.length; i++)

                   System.out.print(a[i]);

            System.out.println();

     }

     public BigInteger(){}

     public BigInteger(int[] array){

            for(int i=0;i < array.length && i < this.array.length;i++){

                   this.array[i] = array[i];

                   len++;

            }

     }

     publicvoid display(){

            for(int i = 0; i < len;i++){

                   System.out.print(array[i]);

            }

     }

     publicvoid setIneger(int[] array){

            len=0;

            for(int i=0; i < this.array.length && i < array.length; i++){

                   this.array[i] = array[i];

                   len++;

            }

           

     }

     publicint[] getInteger(){returnthis.array;}

     publicint getLength(){returnthis.len;}

     publicint[] add(int[] addend){

            int firstlen = len;//第一个加数的长度。

            int secondlen = (int) addend.length;//第二个加数的长度。

            int gap = Math.abs(firstlen-secondlen);//两个数长度差。

            int thirdlen = firstlen > secondlen? firstlen:secondlen;

            int result[] = newint[thirdlen+1];         //相加过程

            int temp=0; //进位数。

            for(int i = thirdlen-1; i >=gap;i--){

                   if(firstlen < secondlen){

                          result[i+1] = (array[i-gap]+addend[i])%10 +temp;

                          temp = (array[i-gap]+addend[i])/10;

                   }else{

                          result[i+1] = (array[i]+addend[i-gap])%10 +temp;

                          temp = (array[i]+addend[i-gap])/10;

                   }

            }

            int j = 1;

            do{

                   if(firstlen < secondlen){

                          result[j] = addend[j-1];

                   }elseif(firstlen > secondlen){

                          result[j] = array[j-1];

                   }j++;

            }while(j < gap);

            if(temp != 0){

                   result[0] = temp;

            }else{

                   int s[] = newint[thirdlen];

                   for(int i=0; i < thirdlen; i++)

                          s[i] = result[i+1];

                   return s;

            }

            return result;

     }

    

     privateintarray[] = newint[20];

     privateintlen = 0;

}

2.实验截图:

  技术分享

3.实验分析:利用数字实现大数的表示,通过将大数的各个位上的数字分开,进行相加计算,相加满10进位。

七.生成随机数:

   1.设计思想:首先,定义一个长度为10的数字,然后通过for循环随机产生了10个数,赋值给output,然后再通过一个for循环把数组a里面的10个数字进行相加,最后在屏幕通过消息框输出。

 

 

   2.程序流程图

    技术分享

      技术分享

 

        技术分享

    3.程序源代码:

           import javax.swing.JOptionPane;

public class Random {

 

      /**

       * @param args

       */

      public static void main(String[] args) {

             // TODO Auto-generated method stub

             int a[]=new int[10];

             int sum=0;

             String output=new String();

             for(int i=0;i<a.length;i++)

             {

 

                a[i]=(int)(Math.random()*100);

 

             }

 

             output+="a[10]=";

 

             for(int i=0;i<a.length;i++)

 

             {

 

                 output+=a[i]+" ";

 

             }

 

             for(int i=0;i<a.length;i++)

 

             {

 

                    sum+=a[i];

 

             }

 

             output+="\nsum:"+sum;

 

              

 

             JOptionPane.showMessageDialog(null, output,"结果",

 

             JOptionPane.PLAIN_MESSAGE);

 

             }

 

}

 

   4.结果截图:

  技术分享技术分享技术分享

5.编程总结:注意开始定义数组和字符串的初始化,运用训话语句,随机生成10个数给数字a。

 

 


数组博客