课后作业

动手动脑:

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

程序源代码: 

 1 // PassArray.java
 2 // Passing arrays and individual array elements to methods
 3 
 4 public class PassArray {
 5     
 6     public static void main(String[] args) {
 7         int a[] = { 1, 2, 3, 4, 5 };
 8         String output = "The values of the original array are:\n";
 9 
10         for (int i = 0; i < a.length; i++)
11             output += "   " + a[i];
12 
13         output += "\n\nEffects of passing array " + "element call-by-value:\n"
14                 + "a[3] before modifyElement: " + a[3];
15 
16         modifyElement(a[3]);
17 
18         output += "\na[3] after modifyElement: " + a[3];
19 
20         output += "\n Effects of passing entire array by reference";
21 
22         modifyArray(a); // array a passed call-by-reference
23 
24         output += "\n\nThe values of the modified array are:\n";
25 
26         for (int i = 0; i < a.length; i++)
27             output += "   " + a[i];
28         
29         System.out.println(output);
30     }
31 
32     public static void modifyArray(int b[]) {
33         for (int j = 0; j < b.length; j++)
34             b[j] *= 2;
35     }
36 
37     public static void modifyElement(int e) {
38         e *= 2;
39     }
40 
41 }

 

截图分析:

 

分析:按引用传递与按值传送数组类型方法参数的最大关键在于:

使用前者时,如果方法中有代码更改了数组元素的值,实际上是直接修改了原始的数组元素。

使用后者则没有这个问题,方法体中修改的仅是原始数组元素的一个拷贝。

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

程序源代码:  

 1 import java.io.*;
 2 
 3 public class Test3
 4 {
 5     //定义一个二维数组来充当棋盘
 6     private String[][] board;
 7     //定义棋盘的大小
 8     private static int BOARD_SIZE = 15;
 9     public void initBoard()
10     {
11         //初始化棋盘数组
12         board = new String[BOARD_SIZE][BOARD_SIZE];
13         //把每个元素赋为"╋",用于在控制台画出棋盘
14         for (int i = 0 ; i < BOARD_SIZE ; i++)
15         {
16             for ( int j = 0 ; j < BOARD_SIZE ; j++)
17             {
18                 board[i][j] = "╋";
19             }
20         }
21     }
22     //在控制台输出棋盘的方法
23     public void printBoard()
24     {
25         //打印每个数组元素
26         for (int i = 0 ; i < BOARD_SIZE ; i++)
27         {
28             for ( int j = 0 ; j < BOARD_SIZE ; j++)
29             {
30                 //打印数组元素后不换行
31                 System.out.print(board[i][j]);
32             }
33             //每打印完一行数组元素后输出一个换行符
34             System.out.print("\n");
35         }
36     }
37     public static void main(String[] args)throws Exception
38     {
39         Test3 gb = new Test3();
40         gb.initBoard();
41         gb.printBoard();
42         //这是用于获取键盘输入的方法
43         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
44         String inputStr = null;
45                 System.out.println("请输入您下棋的座标,应以x y的格式:");
46         //br.readLine():每当在键盘上输入一行内容按回车,刚输入的内容将被br读取到。
47         while ((inputStr = br.readLine()) != null)
48         {
49             //将用户输入的字符串以空格( )作为分隔符,分隔成2个字符串
50             String[] posStrArr = inputStr.split(" ");
51             //将2个字符串转换成用户下棋的座标
52             int xPos = Integer.parseInt(posStrArr[0]);
53             int yPos = Integer.parseInt(posStrArr[1]);
54             //把对应的数组元素赋为"●"。
55             gb.board[xPos - 1][yPos - 1] = "●";    
56             //电脑下棋的位置
57             xPos=(int)(Math.random()*15);
58             yPos=(int)(Math.random()*15);
59             gb.board[xPos - 1][yPos - 1] = "?";    
60             /*
61              电脑随机生成2个整数,作为电脑下棋的座标,赋给board数组。
62              还涉及
63                 1.座标的有效性,只能是数字,不能超出棋盘范围
64                 2.如果下的棋的点,不能重复下棋。
65                 3.每次下棋后,需要扫描谁赢了
66              */
67             gb.printBoard();
68             System.out.println("请输入您下棋的座标,应以x,y的格式:");
69         }
70     }
71 }

程序分析:

先建立二维字符串数组存储╋, 然后使用遍历描绘出棋盘,然后将输入的坐标点赋值为电脑和人各自的符号。在进行输赢判断。

 

3 编写一个程序将一个整数转换为汉字读法字符串。比如“1123”转换为“一千一百二十三”。 更进一步,能否将数字表示的金额改为“汉字表达? 比如将“¥123.52”转换为“壹佰贰拾叁元伍角贰分”。

程序源代码:

  1 import java.math.BigDecimal;
  2 import java.util.Scanner;
  3 /**王凤彬 20153140 2016.11.6
  4  * 数字转换为汉语中人民币的大写
  5  */
  6 public class Test4 {
  7     /**
  8      * 汉语中数字大写
  9      */
 10     private static final String[] CN_UPPER_NUMBER = { "零", "壹", "贰", "叁", "肆",
 11             "伍", "陆", "柒", "捌", "玖" };
 12     /**
 13      * 汉语中货币单位大写,这样的设计类似于占位符
 14      */
 15     private static final String[] CN_UPPER_MONETRAY_UNIT = { "分", "角", "元",
 16             "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟", "兆", "拾",
 17             "佰", "仟" };
 18     /**
 19      * 特殊字符:整
 20      */
 21     private static final String CN_FULL = "整";
 22     /**
 23      * 特殊字符:负
 24      */
 25     private static final String CN_NEGATIVE = "负";
 26     /**
 27      * 金额的精度,默认值为2
 28      */
 29     private static final int MONEY_PRECISION = 2;
 30     /**
 31      * 特殊字符:零元整
 32      */
 33     private static final String CN_ZEOR_FULL = "零元" + CN_FULL;
 34 
 35     /**
 36      * 把输入的金额转换为汉语中人民币的大写
 37      * 
 38      * @param numberOfMoney
 39      *            输入的金额
 40      * @return 对应的汉语大写
 41      */
 42     public static String number2CNMontrayUnit(BigDecimal numberOfMoney) {
 43         StringBuffer sb = new StringBuffer();
 44         // -1, 0, or 1 as the value of this BigDecimal is negative, zero, or
 45         // positive.
 46         int signum = numberOfMoney.signum();
 47         // 零元整的情况
 48         if (signum == 0) {
 49             return CN_ZEOR_FULL;
 50         }
 51         //这里会进行金额的四舍五入
 52         long number = numberOfMoney.movePointRight(MONEY_PRECISION)
 53                 .setScale(0, 4).abs().longValue();
 54         // 得到小数点后两位值
 55         long scale = number % 100;
 56         int numUnit = 0;
 57         int numIndex = 0;
 58         boolean getZero = false;
 59         // 判断最后两位数,一共有四中情况:00 = 0, 01 = 1, 10, 11
 60         if (!(scale > 0)) {
 61             numIndex = 2;
 62             number = number / 100;
 63             getZero = true;
 64         }
 65         if ((scale > 0) && (!(scale % 10 > 0))) {
 66             numIndex = 1;
 67             number = number / 10;
 68             getZero = true;
 69         }
 70         int zeroSize = 0;
 71         while (true) {
 72             if (number <= 0) {
 73                 break;
 74             }
 75             // 每次获取到最后一个数
 76             numUnit = (int) (number % 10);
 77             if (numUnit > 0) {
 78                 if ((numIndex == 9) && (zeroSize >= 3)) {
 79                     sb.insert(0, CN_UPPER_MONETRAY_UNIT[6]);
 80                 }
 81                 if ((numIndex == 13) && (zeroSize >= 3)) {
 82                     sb.insert(0, CN_UPPER_MONETRAY_UNIT[10]);
 83                 }
 84                 sb.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]);
 85                 sb.insert(0, CN_UPPER_NUMBER[numUnit]);
 86                 getZero = false;
 87                 zeroSize = 0;
 88             } else {
 89                 ++zeroSize;
 90                 if (!(getZero)) {
 91                     sb.insert(0, CN_UPPER_NUMBER[numUnit]);
 92                 }
 93                 if (numIndex == 2) {
 94                     if (number > 0) {
 95                         sb.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]);
 96                     }
 97                 } else if (((numIndex - 2) % 4 == 0) && (number % 1000 > 0)) {
 98                     sb.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]);
 99                 }
100                 getZero = true;
101             }
102             // 让number每次都去掉最后一个数
103             number = number / 10;
104             ++numIndex;
105         }
106         // 如果signum == -1,则说明输入的数字为负数,就在最前面追加特殊字符:负
107         if (signum == -1) {
108             sb.insert(0, CN_NEGATIVE);
109         }
110         // 输入的数字小数点后两位为"00"的情况,则要在最后追加特殊字符:整
111         if (!(scale > 0)) {
112             sb.append(CN_FULL);
113         }
114         return sb.toString();
115     }
116 
117     public static void main(String[] args) {
118         double money;
119         Scanner scanner= new Scanner(System.in);//扫描控制台输入 
120         money=scanner.nextDouble();
121         BigDecimal numberOfMoney = new BigDecimal(money);
122         String s = number2CNMontrayUnit(numberOfMoney);
123         System.out.println("你输入的金额为:"+ money +"  大写金额为 " +s.toString()+);
124     }
125 }

 

4 前面几讲介绍过JDK所提供的BigInteger能完成大数计算,如果不用它,直接使用数组表达大数,你能实现相同的功能吗?

要求:

1)用你的大数类实现加和减两个功能

2)阅读BigInteger类源码,弄清楚它是使用什么算法实现加减乘除四种运算的?

3)通过互联网查找大数运算的相关资料,给你的大数类添加乘、除、求阶乘等其它功能。

 

程序源代码:

  1 import java.io.*;
  2 public class BigNumber {
  3 
  4     public static void main(String[] args) throws IOException {
  5         // TODO Auto-generated method stub
  6         BigNumber a;
  7         System.out.println("输入一个正整数:");
  8         a = inputInteger();
  9         System.out.println("输入另一个正整数:");
 10         int b[] = inputArray();
 11         System.out.println("两个数的和是:");
 12         display(a.add(b));
 13         
 14     }
 15     public static int[] inputArray()throws IOException{
 16         InputStreamReader reader = new InputStreamReader(System.in);
 17         BufferedReader input = new BufferedReader(reader);
 18         String number = input.readLine();
 19         
 20         char temp[] = number.toCharArray();
 21         int array[] = new int[temp.length];
 22         for(int i=0; i<temp.length; i++){
 23             if(temp[i] < '0' || temp[i] > '9'){
 24                 System.out.println("输入错误!");
 25                 System.exit(1);
 26             }
 27             array[i] = temp[i]-'0';
 28         }
 29         return array;
 30     }
 31     public static BigNumber inputInteger()throws IOException{
 32         InputStreamReader reader = new InputStreamReader(System.in);
 33         BufferedReader input = new BufferedReader(reader);
 34         String number = input.readLine();
 35         
 36         char temp[] = number.toCharArray();
 37         int array[] = new int[temp.length];
 38         for(int i=0; i<temp.length; i++){
 39             if(temp[i] < '0' || temp[i] > '9'){
 40                 System.out.println("输入错误!");
 41                 System.exit(1);
 42             }
 43             array[i] = temp[i]-'0';
 44         }
 45         BigNumber a = new BigNumber(array);
 46         return a;
 47     }
 48     public static void display(int[] a){
 49         for(int i = 0; i < a.length; i++)
 50             System.out.print(a[i]);
 51         System.out.println();
 52     }
 53     public BigNumber(){}
 54     public BigNumber(int[] array){
 55         for(int i=0;i < array.length && i < this.array.length;i++){
 56             this.array[i] = array[i];
 57             len++;
 58         }
 59     }
 60     public void display(){
 61         for(int i = 0; i < len;i++){
 62             System.out.print(array[i]);
 63         }
 64     }
 65     public void setIneger(int[] array){
 66         len=0;
 67         for(int i=0; i < this.array.length && i < array.length; i++){
 68             this.array[i] = array[i];
 69             len++;
 70         }
 71         
 72     }
 73     public int[] getInteger(){return this.array;}
 74     public int getLength(){return this.len;}
 75     public int[] add(int[] addend){
 76         int firstlen = len;//第一个加数的长度。
 77         int secondlen = (int) addend.length;//第二个加数的长度。
 78         int gap = Math.abs(firstlen-secondlen);//两个数长度差。
 79         int thirdlen = firstlen > secondlen? firstlen:secondlen;
 80         int result[] = new int[thirdlen+1];        //相加过程
 81         int temp=0; //进位数。
 82         for(int i = thirdlen-1; i >=gap;i--){
 83             if(firstlen < secondlen){
 84                 result[i+1] = (array[i-gap]+addend[i])%10 +temp;
 85                 temp = (array[i-gap]+addend[i])/10;
 86             }else{
 87                 result[i+1] = (array[i]+addend[i-gap])%10 +temp;
 88                 temp = (array[i]+addend[i-gap])/10;
 89             }
 90         }
 91         int j = 1;
 92         do{
 93             if(firstlen < secondlen){
 94                 result[j] = addend[j-1];
 95             }else if(firstlen > secondlen){
 96                 result[j] = array[j-1];
 97             }j++;
 98         }while(j < gap);
 99         if(temp != 0){
100             result[0] = temp;
101         }else{
102             int s[] = new int[thirdlen];
103             for(int i=0; i < thirdlen; i++)
104                 s[i] = result[i+1];
105             return s;
106         }
107         return result;
108     }
109     
110     private int array[] = new int[20];
111     private int len = 0;
112 }

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

要求将设计思路、程序流程图、源程序代码、结果截图、编程总结等发表到博客园,并备份到课堂派

 

程序设计思想:

建立数组对每一个数赋值随机数,并相加输出结果即可。

程序流程图:

程序源代码:

 1 import java.util.*;
 2 import javax.swing.JOptionPane; 
 3 public class RandomNumber {
 4 // 王凤彬 20153140 信1505-1班
 5     public static void main(String[] args) {
 6         // TODO Auto-generated method stub
 7     int a[]= new int [10];
 8     int sum=0;
 9     int i=0;
10     String output=new String();
11     Random r=new Random(); 
12    for(int x:a){
13      x=r.nextInt();
14      sum+=x;
15      output+=i+1+"\t           "+x +"\n";
16      i++;
17    }
18    output+="The results is ";
19    JOptionPane.showMessageDialog(
20              null,output  + sum , "Results",
21              JOptionPane.PLAIN_MESSAGE );
22 
23  }
24 
25 }

结果截图:

 

 

编程总结:for语句的特殊使用方法。消息框的使用,等等。

posted @ 2016-11-06 14:24  风飘万点江满月  阅读(232)  评论(0编辑  收藏  举报