java课堂_java课堂练习6

2024-01-18 23:40
文章标签 java 课堂 课堂练习

本文主要是介绍java课堂_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:\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;

}

}

输出结果:

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

770d358ebbc996b1f3b16ed4854cf1a7.png

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

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

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

动手动脑:

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

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("\n");

}

}

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

}

}

}

8013105054abdc7a8bec5eefd585bf7c.png

请编写一个程序将一个整数转换为汉字读法字符串。比如“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"));

}

}

结果:

674d558de31921065a7c727818e75aec.png

更进一步,能否将数字表示的金额改为“汉字表达? 比如将“¥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

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

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());

}

}

2110c0bd3bbc601c009b182f5d089441.png

前面几讲介绍过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

(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输出数组的内容

程序流程图:

ef6345502142e9a51ce19f4dade2fc87.png

package text;

import javax.swing.*;

public class text {

public static void main(String[] args) {

// TODO Auto-generated method stub

String output= "10个随机数为:\n";

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 +="\n\n十个数的和是:"+sum;

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

JOptionPane.PLAIN_MESSAGE);

}

}

结果截图:

67af9b9eed64cb30b8d8fc578fab1fc1.png

编辑总结:

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

利用JOptionPane.showMessageDialog(null,output," “JOptionPane.PLAIN_MESSAGE);

可以在对话框中输出结果。

这篇关于java课堂_java课堂练习6的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/620637

相关文章

分布式锁在Spring Boot应用中的实现过程

《分布式锁在SpringBoot应用中的实现过程》文章介绍在SpringBoot中通过自定义Lock注解、LockAspect切面和RedisLockUtils工具类实现分布式锁,确保多实例并发操作... 目录Lock注解LockASPect切面RedisLockUtils工具类总结在现代微服务架构中,分布

Java使用Thumbnailator库实现图片处理与压缩功能

《Java使用Thumbnailator库实现图片处理与压缩功能》Thumbnailator是高性能Java图像处理库,支持缩放、旋转、水印添加、裁剪及格式转换,提供易用API和性能优化,适合Web应... 目录1. 图片处理库Thumbnailator介绍2. 基本和指定大小图片缩放功能2.1 图片缩放的

Spring Boot集成/输出/日志级别控制/持久化开发实践

《SpringBoot集成/输出/日志级别控制/持久化开发实践》SpringBoot默认集成Logback,支持灵活日志级别配置(INFO/DEBUG等),输出包含时间戳、级别、类名等信息,并可通过... 目录一、日志概述1.1、Spring Boot日志简介1.2、日志框架与默认配置1.3、日志的核心作用

破茧 JDBC:MyBatis 在 Spring Boot 中的轻量实践指南

《破茧JDBC:MyBatis在SpringBoot中的轻量实践指南》MyBatis是持久层框架,简化JDBC开发,通过接口+XML/注解实现数据访问,动态代理生成实现类,支持增删改查及参数... 目录一、什么是 MyBATis二、 MyBatis 入门2.1、创建项目2.2、配置数据库连接字符串2.3、入

Springboot项目启动失败提示找不到dao类的解决

《Springboot项目启动失败提示找不到dao类的解决》SpringBoot启动失败,因ProductServiceImpl未正确注入ProductDao,原因:Dao未注册为Bean,解决:在启... 目录错误描述原因解决方法总结***************************APPLICA编

深度解析Spring Security 中的 SecurityFilterChain核心功能

《深度解析SpringSecurity中的SecurityFilterChain核心功能》SecurityFilterChain通过组件化配置、类型安全路径匹配、多链协同三大特性,重构了Spri... 目录Spring Security 中的SecurityFilterChain深度解析一、Security

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

Apache Ignite 与 Spring Boot 集成详细指南

《ApacheIgnite与SpringBoot集成详细指南》ApacheIgnite官方指南详解如何通过SpringBootStarter扩展实现自动配置,支持厚/轻客户端模式,简化Ign... 目录 一、背景:为什么需要这个集成? 二、两种集成方式(对应两种客户端模型) 三、方式一:自动配置 Thick

Spring WebClient从入门到精通

《SpringWebClient从入门到精通》本文详解SpringWebClient非阻塞响应式特性及优势,涵盖核心API、实战应用与性能优化,对比RestTemplate,为微服务通信提供高效解决... 目录一、WebClient 概述1.1 为什么选择 WebClient?1.2 WebClient 与

Java.lang.InterruptedException被中止异常的原因及解决方案

《Java.lang.InterruptedException被中止异常的原因及解决方案》Java.lang.InterruptedException是线程被中断时抛出的异常,用于协作停止执行,常见于... 目录报错问题报错原因解决方法Java.lang.InterruptedException 是 Jav