java课堂练习6

动手动脑:

阅读并运行示例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;
}

}

输出结果:

The values of the original array are:
1 2 3 4 5

Effects of passing array element call-by-value:
a[3] before modifyElement: 4
a[3] after modifyElement: 4
Effects of passing entire array by reference

The values of the modified array are:
2 4 6 8 10

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

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

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

动手动脑:

以下代码的输出结果是什么?为什么会有这个结果?

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

int[] b = new int[4];

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

b = a; System.out.println("b数组的长度为:" + b.length);

测试用代码:ArrayInRam.java

结果:

a数组中的元素:
5,7,20,
b数组的初始长度为:4
b=a,赋值之后,b数组的元素为:
5,7,20,
赋值之后,b数组的长度为:3

开始使数组b是开辟了长度为4的空间,所以b数组的初始长度为:4,后来将a的长度赋给b,a的长度为3,赋值之后,b数组的长度为:3。

动手动脑:

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

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的格式:");
}
}
}

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

public class Num2Rmb
{
private String[] hanArr = {"零" , "壹" , "贰" , "叁" , "肆" ,
"伍" , "陆" , "柒" , "捌" , "玖"};
private String[] unitArr = {"十" , "百" , "千","万","十万","百万"};

/**
* 把一个四位的数字字符串变成汉字字符串
* @param numStr 需要被转换的四位的数字字符串
* @return 四位的数字字符串被转换成的汉字字符串。
*/
private String toHanStr(String numStr)
{
String result = "";
int numLen = numStr.length();
//依次遍历数字字符串的每一位数字
for (int i = 0 ; i < numLen ; i++ )
{
//把char型数字转换成的int型数字,因为它们的ASCII码值恰好相差48
//因此把char型数字减去48得到int型数字,例如'4'被转换成4。
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;
}
}

public static void 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"));

}
}

结果:

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

package text;

public class text {
// 整数部分
private String integerPart;
// 小数部分
private String floatPart;

// 将数字转化为汉字的数组,因为各个实例都要使用所以设为静态
private static final char[] cnNumbers={'零','壹','贰','叁','肆','伍','陆','柒','捌','玖'};

// 供分级转化的数组,因为各个实例都要使用所以设为静态
private static final char[] series={'元','拾','百','仟','万','拾','百','仟','亿'};

/**
* 构造函数,通过它将阿拉伯数字形式的字符串传入
* @param original
*/
public text(String original){
// 成员变量初始化
integerPart="";
floatPart="";

if(original.contains(".")){
// 如果包含小数点
int dotIndex=original.indexOf(".");
integerPart=original.substring(0,dotIndex);
floatPart=original.substring(dotIndex+1);
}
else{
// 不包含小数点
integerPart=original;
}
}

/**
* 取得大写形式的字符串
* @return
*/
public String getCnString(){
// 因为是累加所以用StringBuffer
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();
}

/**
* 将字符形式的数字转化为整形数字
* 因为所有实例都要用到所以用静态修饰
* @param c
* @return
*/
private static int getNumber(char c){
String str=String.valueOf(c);
return Integer.parseInt(str);
}

/**
* @param args
*/
public static void main(String[] args) {

System.out.println(new text("123.52").getCnString());
}
}

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

要求:

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

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

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

 

(1)BigInteger历史介绍
在java中,存在很多种类的数据类型,例如byte short char int float double long,而BigInteger属于其中一个比较特殊的数据类型,也是本教程关注的重点。BigInteger在JDK1.1中就已经存在了,属于java.math包的类。从名字来看,BigInteger比Integer表示数值的范围更大一些。BigInteger类的基本结构如下所示:
java.lang.Object
|_java.lang.Number
|_java.math.BigInteger
BigInteger已实现的接口:Serializable, Comparable<BigInteger>

(2)BigInteger是不可变的任意精度的整数。所有操作中,都以二进制补码形式表示 BigInteger(如 Java 的基本整数类型)。BigInteger 提供所有 Java 的基本整数操作符的对应物,并提供 java.lang.Math 的所有相关方法。另外,BigInteger 还提供以下运算:模算术、GCD 计算、质数测试、素数生成、位操作以及一些其他操作。

(3)BigInteger属性分析
下面看看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。

import java.math.BigInteger;

public class text {

public static void main(String[] args) {

// TODO Auto-generated method stub

  BigInteger aa =new BigInteger("100");

  BigInteger bb= new BigInteger("25");

  BigInteger sub=aa.subtract(bb);//大整数的减

  BigInteger add=aa.add(bb);//大整数的加

  BigInteger mul=aa.multiply(bb);//大整数的乘

  BigInteger div=aa.divide(bb);//大整数的除

  System.out.println("大整数的减:"+sub.toString());

  System.out.println("大整数的加:"+add.toString());

  System.out.println("大整数的乘:"+mul.toString());

  System.out.println("大整数的除:"+div.toString());

  }

}

大整数的减:75

大整数的加:125

大整数的乘:2500

大整数的除:4

 

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

设计思路:

1.使用random随机产生10个数,存入数组中

2.使用for循环把结果存入数组中

3.使用for循环求出数组中所有元素的和

4.使用JTextArea和JOptionPane输出数组的内容

程序流程图:

package text;

import javax.swing.*;


public class text {

public static void main(String[] args) {

// TODO Auto-generated method stub


String output= "10个随机数为: ";
int sum=0;
int a []=new int [10];
for(int i = 0;i<10;i++)
{
a[i]=(int) (Math.random()*10);
output += " "+a[i];
sum += a[i];
}

output +=" 十个数的和是:"+sum;

JOptionPane.showMessageDialog(null,output,"结果",
JOptionPane.PLAIN_MESSAGE);

}
}

结果截图:

编辑总结:

总结:利用Math.Random()*n可以生成任意n内的随机数;

利用JOptionPane.showMessageDialog(null,output," “JOptionPane.PLAIN_MESSAGE);
可以在对话框中输出结果。

原文地址:https://www.cnblogs.com/xxdcxy/p/6030401.html