zoukankan      html  css  js  c++  java
  • 数组动手动脑。

    1、阅读并运行示例PassArray.java,观察并分析程序输出的结果,小结,然后与下页幻灯片所讲的内容进行对照。

    程序源代码:

    // PassArray.java
    // Passing arrays and individual array elements to methods

    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: ";

      for (int i = 0; i < a.length; i++)
       output += "   " + a[i];

      output += " Effects of passing array " + "element call-by-value: "
        + "a[3] before modifyElement: " + a[3];

      modifyElement(a[3]);

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

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

      modifyArray(a); // array a passed call-by-reference

      output += " The values of the modified array are: ";

      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;
     }

    }

    程序截图:

    运行结果分析:

    首先程序输出的是a[i]的原始数据,再输出引用和按值传递(使用前者时,如果方法中有代码更改了数组元素的值,实际上是直接修改了原始的数组元素。使用后者则没有这个问题,方法体中修改的仅是原始数组元素的一个拷贝)后的值,最后输出加倍的值。

    2、阅读QiPan.java示例程序了解如何利用二维数组和循环语句绘制五子棋盘。

    程序源代码:

    package demo;


    import java.io.*;

    public class QiPan
    {
     //定义一个二维数组来充当棋盘
     private String[][] board;
     //定义棋盘的大小
     private static int BOARD_SIZE = 15;
     public void 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] = "╋";
       }
      }
     }
     //在控制台输出棋盘的方法
     public void 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(" ");
      }
     }
        public static void 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的格式:");
      }
        }
    }

     程序截图:

    3、(1)请编写一个程序将一个整数转换为汉字读法字符串。比如“1123”转换为“一千一百二十三”。

    程序源代码:package demo;import java.util.Scanner;
    public class change1 {
     private String[] hanArr={"零","一" , "二" , "三" , "四" , "五" ,"六" , "七" , "八" , "九" };
     private String[] unArr={"十" , "百" , "千","万","十万","百万"};
     
     private String toHanStr(String numS)
     {
      String result="";
      int numL=numS.length();
      for(int i=0;i<numL;i++)
      {
       int num=numS.charAt(i)-48; //把char类型的数字转化成int类型的数字,其ASCII码值相差48
       if(i!=numL-1&&num!=0)
       {
        result+=hanArr[num]+unArr[numL-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;
     }
     public static void main(String[] args){
      change1 nr=new change1();
      System.out.println("只支持整数(0~百万)");
      System.out.println(nr.toHanStr("1123"));
      System.out.println(nr.toHanStr("1023"w));
      System.out.println(nr.toHanStr("112369"));
      System.out.println(nr.toHanStr("1002356"));
     }
     
    }

    程序截图:

    (2)更进一步,能否将数字表示的金额改为“汉字表达? 比如将“¥123.52”转换为“壹佰贰拾叁元伍角贰分”。

    程序源代码:

    package demo;

    public class change2 {
     private String integerPart; //整数部分
     private String floatPart; //小数部分
     
     private static final char[] cnNumbers={'零','壹','贰','叁','肆','伍','陆','柒','捌','玖'};// 将数字转化为汉字的数组,因为各个实例都要使用所以设为静态
     private static final char[] series={'元','拾','百','仟','万','拾','百','仟','亿'};// 供分级转化的数组,因为各个实例都要使用所以设为静态
     
     public change2(String original)
     {
      integerPart="";
      floatPart=""; //初始化
      
      if(original.contains("."))  //所输入的金额中包含小数点
      {
       int dotIndex=original.indexOf(".");
       integerPart=original.substring(0,dotIndex);
       floatPart=original.substring(dotIndex+1);
      }
      else
      {
       integerPart=original;
      }
     }
     public String getCnString(){
      StringBuffer sb=new StringBuffer();
      //整数处理
      for(int i=0;i<integerPart.length();i++){
       int number=getNumber(integerPart.charAt(i));
       sb.append(cnNumbers[number]);
       sb.append(series[integerPart.length()-1-i]);
       }
      //小数处理
      if(floatPart.length()>0){
       sb.append("点");
       for(int i=0;i<floatPart.length();i++){
       int number=getNumber(floatPart.charAt(i));
       sb.append(cnNumbers[number]);
       }
     }
      return sb.toString();
      }
       private static int getNumber(char c){
      String str=String.valueOf(c);
      return Integer.parseInt(str);
      }
       public static void main(String[] args) {
        System.out.println(new change2("123.52").getCnString());
        }
    }

    程序截图:

    4、前面几讲介绍过JDK所提供的BigInteger能完成大数计算,如果不用它,直接使用数组表达大数,你能实现相同的功能吗?
    要求:
    (1)用你的大数类实现加和减两个功能
    (2)阅读BigInteger类源码,弄清楚它是使用什么算法实现加减乘除四种运算的?
    (3)通过互联网查找大数运算的相关资料,给你的大数类添加乘、除、求阶乘等其它功能。

    下面看看BigInteger有哪些重点的属性,主要的有下面三个:
    (1)final int signum
    signum属性是为了区分:正负数和0的标志位,JDK注释里面已经说的很明白了:
    The signum of this BigInteger: -1 for negative, 0 for zero, or 1 for positive. Note that the BigInteger zero must have a signum of 0. This is necessary to ensures that there is exactly one representation for each BigInteger value.
    (2)final int[] mag
    mag是magnitude的缩写形式,mag数组是存储BigInteger数值大小的,采用big-endian的顺序,也就是高位字节存入低地址,低位字节存入高地址,依次排列的方式。JDK原文注释如下:
    The magnitude of this BigInteger, in big-endian order: the zeroth element of this array is the most-significant int of the magnitude. The magnitude must be "minimal" in that the most-significant int (mag[0]) must be non-zero. This is necessary to ensure that there is exactly one representation for each BigInteger value. Note that this implies that the BigInteger zero has a zero-length mag array.
    (3)final static long LONG_MASK = 0xffffffffL;
    This mask is used to obtain the value of an int as if it were unsigned。

    程序源代码:

    public class BigNum
    {
    public static void main(String[] args)
    {
    String aa="";
    String bb="";
    char[] a={'1','2','0'};
    char[] b={'5','0'};
    int d=0;
    int e=0;
    for(int i=0;i<a.length;i++)
    {
    aa=aa+a[i];

    }

    d=Integer.parseInt(aa);
    System.out.println(d);
    for(int i=0;i<b.length;i++)
    {
    bb=bb+b[i];

    }

    e=Integer.parseInt(bb);
    System.out.println(e);
    int f=d+e;
    System.out.print(aa+" + "+bb+"="+f);
    }
    }

    程序截图:

    5、随机生成10个数,填充一个数组,然后用消息框显示数组内容,接着计算数组元素的和,将结果也显示在消息框中。

    程序设计思路:

    利用Random生成100以内的随机数,并存放到数组当中,输出随机数相加,并以对话框的形式输出。

    程序流程图:

    程序源代码:

    package demo;

    import javax.swing.JOptionPane;
    public class ArraySum {
     public static void main(String[] args){
      int[] arr=new int[10];
      int result=0;
      String output="";
      for(int i=0;i<arr.length;i++) //随机产生一个100以内的数
       arr[i]=(int)(Math.random()*100);
      output +="随机生成的十个数是:"+" "; //输出数组元素
      for(int i=0;i<arr.length;i++)
       output +=arr[i]+"  ";
          output +=" ";
      
      for(int i=0;i<arr.length;i++)//将元素相加
       result +=arr[i];
          output +="十个数相加等于:"+" "+result;
         
          JOptionPane.showMessageDialog(null, output,"输出",JOptionPane.INFORMATION_MESSAGE); 
          }
    }

    程序截图:

  • 相关阅读:
    【ArcGIS 10.2新特性】ArcGIS 10.2 for Desktop 新特性(二)
    手势(Gesture)的增加和识别
    [转]C#自定义开关按钮控件--附带第一个私活项目截图
    当年的试用期周工作心得
    FREESWITCH SEESION
    基于三星ARM9(S3C2410)的交通违章抓拍系统的开发
    Apache Kafka: Next Generation Distributed Messaging System---reference
    How and Why Unsafe is Used in Java---reference
    基于keepalived对redis做高可用配置---转载
    Java获取真实的IP地址--转载
  • 原文地址:https://www.cnblogs.com/th1314/p/6033195.html
Copyright © 2011-2022 走看看