Java语言程序设计编程题(programming exercises)答案第7章

合集下载

Java程序设计课后练习答案

Java程序设计课后练习答案

《J a v a 程序设计》课后练习答案第一章Java 概述一、选择题1. (A )是在Dos命令提示符下编译Java程序的命令,(B )是运行Java程序的命令。

A. javacB. javaC. javadocD. javaw2. (D )不是Java程序中有效的注释符号。

A. lassB. .jarC. .javD. .java二、简答题1 、Java 的跨平台的含义是什么为什么Java 可以跨平台Java语言的一个非常重要的特点就是平台无关性。

它是指用Java编写的应用程序编译后不用修改就可在不同的操作系统平台上运行。

Java 之所以能平台无关,主要是依靠Java 虚拟机(JVM来实现的。

JVM是一种抽象机器,它附着在具体操作系统之上,本身具有一套虚机器指令,并有自己的栈、寄存器组等。

Java 编程人员在编写完Java 程序后,Java 编译器将Java 源代码文件编译后生成字节码文件(一种与操作系统无关的二进制文件)。

字节码文件通过Java虚拟机(JVM里的类加载器加载后,经过字节码校验,由解释器解释成当前电脑的操作系统能够识别的目标代码并最终运行。

以下图展示了Java 程序从编译到最后运行的完整过程。

2、简述Java 语言的特点Java 具有以下特点:1)、简单性Java语言的语法规则和C语言非常相似,只有很少一部分不同于C语言,并且Java 还舍弃了C语言中复杂的数据类型(如:指针和结构体),因此很容易入门和掌握。

2)、可靠性和安全性Java 从源代码到最终运行经历了一次编译和一次解释,每次都有进行检查,比其它只进行一次编译检查的编程语言具有更高的可靠性和安全性。

3)、面向对象Java 是一种完全面向的编程语言,因此它具有面向对象编程语言都拥有的封装、继承和多态三大特点。

、平台无关和解释执行4)Java语言的一个非常重要的特点就是平台无关性。

它是指用Java编写的应用程序编译后不用修改就可在不同的操作系统平台上运行。

《JAVA程序设计》习题集及参考答案_IT168文库

《JAVA程序设计》习题集及参考答案_IT168文库

《JA V A程序设计》习题集及参考答案一、填空题1.Java是面向对象的解释型的高级编程语言,其程序源代码的扩展名为.java生成的字节码文件名的扩展名为.class,Java解释器把各种平台间的差异隐藏起来,这种由解释器包裹起来的完整的软硬件平台称为Java 虚拟机。

2.Java Application 是独立、完整的程序,在命令行调用独立的解释器软件(java.exe)即可运行,其程序主类必须有一个main()方法,完整的方法头为public static void main(String aegs[]) 。

3.把方法看作是数据的特性,而不把数据和方法分开,JA V A正是体现了这种建立面向对象系统过程中重要步骤的思想.。

4.建立类类型的变量(引用)后,系统只分配引用空间,程序员要调用new来创建对象实例,然后才分配相应的存储空间。

5.如果需要在同一类中书写多个方法,让它们对不同的变量进行同样的操作,就需要重载方法名。

如果子类中定义方法所用的名字、返回类型和参数表和父类中方法使用的完全一样,称子类方法覆盖了父类中的方法。

覆盖的同名方法中,子类方法不能比父类方法的访问权限更严格。

6.容器中组件的位置由容器的布局管理器决定,容器不仅可以容纳组件,还可以容纳其它容器这一点非常重要,由此可以设计出复杂的图形用户界面布局。

7.Java抽象窗口工具中提供了多种容器,其中最重要的两种是框架和面板。

8.JDK1.1引入了委托模型处理机制,组件必须注册一个事件处理程序,事件对象只传递给已经注册的监听程序,每种事件都有一个对应的监听程序类以实现相应的监听程序接口,并定义了事件对象的接收和处理方法。

9.异常处理的重要性在于,程序不但要发现异常,还要捕获异常并编写代码来处理10.类是同种对象集合的抽象,而属于类的某一个对象则被称为是类的一个实例,对象是具有状态、行为、标志三种属性的计算机软件结构。

11.用户自己定义的Applet子类是Java Applet的标志。

java语言程序设计课后习题答案

java语言程序设计课后习题答案

java语言程序设计课后习题答案Java语言程序设计是计算机科学与技术专业的重要课程之一,通过课后习题的解答,可以帮助学生巩固所学知识,提高编程能力。

本文将回答一些Java语言程序设计的常见习题,帮助读者更好地理解与运用Java语言。

1. 基本数据类型Java中的基本数据类型有byte、short、int、long、float、double、char和boolean。

它们分别用于表示不同的数据类型,如整数、浮点数、字符和布尔值等。

在Java中,基本数据类型的大小是固定的,不会受到不同机器架构的影响。

2. 变量与常量在Java中,使用关键字"var"、"final"和数据类型来声明变量。

变量可以根据需要进行赋值与修改。

而常量在声明时需要使用关键字"final"来修饰,并且一旦赋值后就不能再修改。

3. 运算符Java中的运算符有算术运算符、赋值运算符、关系运算符、逻辑运算符和位运算符等。

它们用于执行不同的操作,如数学运算、赋值、比较和逻辑判断等。

4. 条件语句条件语句用于根据条件来执行不同的代码块。

Java中的条件语句有if语句、if-else语句、switch语句等。

通过条件语句,可以根据不同的条件来执行相应的代码逻辑。

5. 循环语句循环语句用于重复执行一段代码块。

Java中的循环语句有for循环、while循环和do-while循环等。

通过循环语句,可以方便地处理需要重复执行的操作。

6. 数组数组是一种存储相同类型数据的集合。

在Java中,数组可以存储基本数据类型或引用类型的数据。

数组有固定的长度,在声明时需要指定数组的大小,并且可以通过索引访问数组中的元素。

7. 方法方法用于封装一段特定的代码,可以通过方法名来调用执行。

Java中的方法可以有返回值,也可以没有返回值。

通过方法的调用,可以提高代码的复用性和可读性。

8. 类与对象类是面向对象编程的基本单位,用于封装数据和方法。

Java语言程序设计课后习题答案全集

Java语言程序设计课后习题答案全集

Java语言程序设计课后习题答案全集Java语言程序设计是一门广泛应用于软件开发领域的编程语言,随着其应用范围的不断扩大,对于掌握Java编程技巧的需求也逐渐增加。

为了帮助读者更好地掌握Java编程,本文将提供Java语言程序设计课后习题的全集答案,供读者参考。

一、基础知识题1. 代码中的注释是什么作用?如何使用注释.答:注释在代码中是用来解释或者说明代码的功能或用途的语句,编译器在编译代码时会自动忽略注释。

在Java中,有三种注释的方式:- 单行注释:使用"// " 可以在代码的一行中加入注释。

- 多行注释:使用"/* */" 可以在多行中添加注释。

- 文档注释:使用"/** */" 可以添加方法或类的文档注释。

2. 什么是Java的数据类型?请列举常见的数据类型。

答:Java的数据类型用来指定变量的类型,常见的数据类型有:- 基本数据类型:包括整型(byte、short、int、long)、浮点型(float、double)、字符型(char)、布尔型(boolean)。

- 引用数据类型:包括类(class)、接口(interface)、数组(array)等。

二、代码编写题1. 编写Java程序,输入两个整数,求和并输出结果。

答:```javaimport java.util.Scanner;public class SumCalculator {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.print("请输入第一个整数:");int num1 = scanner.nextInt();System.out.print("请输入第二个整数:");int num2 = scanner.nextInt();int sum = num1 + num2;System.out.println("两个整数的和为:" + sum);}}```三、综合应用题1. 编写Java程序,实现学生信息管理系统,要求包括以下功能:- 添加学生信息(姓名、年龄、性别、学号等);- 修改学生信息;- 删除学生信息;- 查询学生信息。

《Java程序设计》课后习题参考答案

《Java程序设计》课后习题参考答案

《Java程序设计》课后习题参考答案Java程序设计课后习题参考答案1. 介绍在 Java 程序设计课程中,课后习题是帮助学生巩固知识、加深理解和提高编程能力的重要环节。

本文将为大家提供《Java程序设计》课后习题的参考答案,以帮助学生更好地学习和掌握 Java 编程。

2. 基本概念Java 程序设计课后习题涵盖了从基础到高级的各种知识点,包括但不限于变量、数据类型、条件语句、循环语句、数组、类、对象、继承、多态等内容。

通过解答这些习题,学生可以加深对这些概念的理解,并且通过实际操作来巩固他们的编程能力。

3. 习题解答策略当解答课后习题时,以下几个策略可以帮助你更好地理解和解决问题:3.1 仔细阅读题目要求。

确保自己充分理解题目所要求的功能和目标。

3.2 分析问题。

在着手解答问题之前,先理清思路,分析问题的要点和关键部分。

3.3 设计算法。

根据问题的要求,设计一个合适的算法来解决问题。

3.4 编写代码。

用 Java 编程语言将你设计的算法转化为代码实现。

3.5 测试和调试。

对编写的代码进行测试和调试,确保程序能够正常运行,并且得到正确的结果。

4. 习题参考答案示例下面我们将列举几个常见的习题参考答案示例,以帮助大家更好地理解和学习 Java 程序设计:4.1 变量与数据类型:习题要求定义一个整型变量并赋值为10,然后输出该变量的值。

```public class VariableExample {public static void main(String[] args) {int num = 10;System.out.println("变量的值为:" + num);}}```4.2 条件语句:习题要求判断一个数是否是偶数,如果是,则输出“偶数”,否则输出“奇数”。

```public class EvenOddExample {public static void main(String[] args) {int num = 5;if (num % 2 == 0) {System.out.println("偶数");} else {System.out.println("奇数");}}}```4.3 循环语句:习题要求输出1到10之间的所有偶数。

java语言程序设计试题及答案

java语言程序设计试题及答案

java语言程序设计试题及答案一、选择题(每题2分,共20分)1. Java语言是______。

A. 编译型语言B. 解释型语言C. 编译解释型语言D. 机器语言答案:C2. 下列哪个是Java语言的基本数据类型?A. StringB. IntegerC. booleanD. Object答案:C3. Java程序的执行入口是以下哪个方法?A. main()B. start()C. run()D. execute()答案:A4. 下列哪个是Java的访问控制修饰符?A. publicC. finalD. abstract答案:A5. Java中,哪个关键字用于定义接口?A. classB. interfaceC. packageD. enum答案:B6. Java中的异常处理是通过哪两个关键字实现的?A. try-catchB. if-elseC. for-whileD. switch-case答案:A7. 下列哪个是Java集合框架中的接口?A. ArrayListB. ListB. MapD. Set答案:B8. Java中,哪个关键字用于实现多态?B. implementsC. newD. override答案:A9. 下列哪个是Java的垃圾回收机制?A. JVMB. GC(Garbage Collection)C. JIT(Just-In-Time)D. JIT Compiler答案:B10. Java语言支持的编程范式包括哪些?A. 过程式编程B. 面向对象编程C. 函数式编程D. 所有以上答案:D二、填空题(每空3分,共15分)1. Java语言是______和______的结合体。

答案:编译型;解释型2. Java的三大特性是______、______和______。

答案:封装;继承;多态3. 在Java中,______关键字用于定义类。

答案:class4. Java的______类是所有Java类的父类。

java程序设计考试试题及答案

java程序设计考试试题及答案

java程序设计考试试题及答案一、选择题(每题2分,共20分)1. Java中,下列哪个关键字用于声明一个类?()A. classB. publicC. privateD. static答案:A2. 下列哪个选项是Java语言的特性?()A. 多线程B. 编译型C. 动态链接D. 所有选项答案:D3. 在Java中,哪个修饰符用于声明一个方法只能由类本身和子类访问?()A. publicB. protectedC. privateD. static答案:B4. Java中,下列哪个关键字用于声明一个接口?()A. classB. interfaceC. publicD. abstract答案:B5. 在Java中,下列哪个关键字用于创建一个抽象类?()A. abstractB. finalC. staticD. interface答案:A6. 下列哪个选项是Java集合框架中的主要接口?()A. ListB. SetC. MapD. 所有选项答案:D7. Java中,下列哪个关键字用于声明一个方法没有返回值?()A. voidB. returnC. nullD. none答案:A8. Java中,下列哪个关键字用于声明一个方法可以被重写?()A. overrideB. extendsC. implementsD. abstract答案:D9. 在Java中,下列哪个关键字用于声明一个变量是静态的?()A. staticB. finalC. transientD. volatile答案:A10. Java中,下列哪个关键字用于声明一个变量是常量?()A. finalB. staticC. transientD. volatile答案:A二、填空题(每题2分,共20分)1. Java程序的执行入口点是________方法。

答案:main2. 在Java中,________关键字用于声明一个变量的值不能被修改。

自考04747《Java语言程序设计(一)》编程题全集(50题及答案)

自考04747《Java语言程序设计(一)》编程题全集(50题及答案)

【程序1】ﻫ题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月得兔子总数为多少?ﻫ//这就是一个菲波拉契数列问题public class lianxi01{ﻫpublic staticvoid main(String[]args) {System、out、println("第1个月得兔子对数: 1”);System、out、println("第2个月得兔子对数: 1");intf1= 1,f2 =1,f,M=24;ﻫfor(int i=3;i〈=M; i++){ﻫf= f2;f2= f1+f2;ﻫf1 = f;System、out、println("第”+ i+”个月得兔子对数:"+f2);}ﻫ}ﻫ}【程序2】题目:判断101-200之间有多少个素数,并输出所有素数。

ﻫ程序分析:判断素数得方法:用一个数分别去除2到sqrt(这个数),如果能被整除,则表明此数不就是素数,反之就是素数。

ﻫpublicclass lianxi02 {ﻫpublic staticvoidmain(String[]args){ﻫint count = 0;ﻫfor(int i=101; i〈200;i+=2){ booleanb=false;for(int j=2; j〈=Math、sqrt(i);j++)ﻫ{ﻫif(i % j == 0){ b = false;break;}ﻫelse { b =true;}ﻫ}ﻫif(b== true) {coun t++;System、out、println(i );}}ﻫSystem、out、println( "素数个数就是: " + count);}}【程序3】ﻫ题目:打印出所有得"水仙花数”,所谓”水仙花数"就是指一个三位数,其各位数字立方与等于该数本身.例如:153就是一个"水仙花数",因为153=1得三次方+5得三次方+3得三次方。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

7.1 import java.util.Scanner;public class Exercise01 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.println("Enter a 4-by-4 matrix row by row:");int[][] matrix = new int[4][4];for (int i = 0; i < 4; i++) {for (int j = 0; j < 4; j++) {matrix[i][j] = input.nextInt();}}System.out.println("Sum of the matrix is " + sumMatrix(matrix));}public static int sumMatrix(int[][] m) {int sum = 0;for (int i = 0; i < m.length; i++) {for (int j = 0; j < m[i].length; j++) {sum += m[i][j];}}return sum;}}7.2 import java.util.Scanner;public class Exercise02 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.println("Enter a 4-by-4 matrix row by row:");int[][] matrix = new int[4][4];for (int i = 0; i < matrix.length; i ++) {for (int j = 0; j < matrix[i].length; j++) {matrix[i][j] = input.nextInt();}}System.out.println("Sum of the elements in the major diagonal is " + sumMajorDiagonal(matrix));}public static int sumMajorDiagonal(int[][] m) {int sum = 0;for (int i = 0, j = 0; i < m.length && j < m[0].length; i++, j++)sum += m[i][j];return sum;}}7.3 public class Exercise03 {public static void main(String[] args) {//Student's answers to the questionschar[][] answers = {{'A', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D'},{'D', 'B', 'A', 'B', 'C', 'A', 'E', 'E', 'A', 'D'},{'E', 'D', 'D', 'A', 'C', 'B', 'E', 'E', 'A', 'D'},{'C', 'B', 'A', 'E', 'D', 'C', 'E', 'E', 'A', 'D'},{'A', 'B', 'D', 'C', 'C', 'D', 'E', 'E', 'A', 'D'},{'B', 'B', 'E', 'C', 'C', 'D', 'E', 'E', 'A', 'D'},{'B', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D'},{'E', 'B', 'E', 'C', 'C', 'D', 'E', 'E', 'A', 'D'}};//Key to the questionschar[] keys = {'D', 'B', 'D', 'C', 'C', 'D', 'A', 'E', 'A', 'D'};int[][] countOfCorrect = new int[answers.length][2];//Grand all answersfor (int i = 0; i < answers.length; i++) {//Grade one studentint correctCount = 0;for (int j = 0; j < answers[i].length; j++) {if (answers[i][j] == keys[j])correctCount++;}countOfCorrect[i][1] = correctCount;countOfCorrect[i][0] = i;}for (int i = 0; i < countOfCorrect.length; i++) {int currentStudent = countOfCorrect[i][0];int min = countOfCorrect[i][1];int minIndex = i;for (int j = i + 1; j < countOfCorrect.length; j++) {if (countOfCorrect[j][1] < min) {currentStudent = countOfCorrect[j][0];min = countOfCorrect[j][1];minIndex = j;}}if (minIndex != i) {countOfCorrect[minIndex][0] = countOfCorrect[i][0];countOfCorrect[minIndex][1] = countOfCorrect[i][1];countOfCorrect[i][0] = currentStudent;countOfCorrect[i][1] = min;}}for (int j = 0; j < countOfCorrect.length; j++)System.out.println("Student " + countOfCorrect[j][0] + "'s correct count is " + countOfCorrect[j][1]);}}7.4 public class Exercise04 {public static void main(String[] args) {int[][] workHours = {{2, 4, 3, 4, 5, 8, 8},{7, 3, 4, 3, 3, 4, 4},{9, 3, 4, 7, 3, 4, 1},{3, 5, 3, 4, 6, 3, 8},{3, 4, 4, 6, 3, 4, 4},{3, 7, 4, 8, 3, 8, 4},{6, 3, 5, 9, 2, 7, 9}};int[][] totalWorkHours = new int[workHours.length][2];for (int i = 0; i < workHours.length; i++) {int sum = 0;for (int j = 0; j < workHours[i].length; j++) {sum += workHours[i][j];}totalWorkHours[i][0] = i;totalWorkHours[i][1] = sum;}int[][] sortTotalWorkHours = sortArray(totalWorkHours);for (int j = 0; j < sortTotalWorkHours.length; j++)System.out.println("Employee " + sortTotalWorkHours[j][0] + "'s total work hours is " + sortTotalWorkHours[j][1]);}public static int[][] sortArray(int[][] array) {for (int i = 0; i < array.length; i++) {int currentEmployee = array[i][0];int currentMaxWorkHours = array[i][1];int currentMaxIndex = i;for (int j = i + 1; j < array.length; j++) {if (array[j][1] > currentMaxWorkHours) {currentEmployee = array[j][0];currentMaxWorkHours = array[j][1];currentMaxIndex = j;}}if (currentMaxIndex != i) {array[currentMaxIndex][0] = array[i][0];array[currentMaxIndex][1] = array[i][1];array[i][0] = currentEmployee;array[i][1] = currentMaxWorkHours;}}return array;}}7.5 import java.util.Scanner;public class Exercise05 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.println("Enter a 4-by-4 matrix1:");int[][] matrix1 = new int[4][4];int[][] matrix2 = new int[4][4];for (int i = 0; i < matrix1.length; i++) {for (int j = 0; j < matrix1[i].length; j++)matrix1[i][j] = input.nextInt();}System.out.println("Enter a 4-by-4 matrix2:");for (int i = 0; i < matrix2.length; i++) {for (int j = 0; j < matrix2[i].length; j++)matrix2[i][j] = input.nextInt();}int[][] sumOfMatrix = addMatrix(matrix1, matrix2);printMatrix(matrix1, matrix2, sumOfMatrix);}public static int[][] addMatrix(int[][] a, int[][] b) {int[][] sum = new int[a.length][a[0].length];for (int i = 0; i < a.length; i++) {for (int j = 0; j < a[i].length; j++)sum[i][j] = a[i][j] + b[i][j];}return sum;}public static void printMatrix(int[][] matrix1, int[][] matrix2, int[][] sumOfMatrix) { for (int i = 0; i < matrix1.length; i++) {for (int j = 0; j < matrix1[i].length; j++) {System.out.print((matrix1[i][j] < 10 ? " " : "") + matrix1[i][j] + " ");}if (i != Math.ceil(matrix1.length / 2))System.out.print(" ");elseSystem.out.print("+ ");for (int j = 0; j < matrix2[i].length; j++) {System.out.print((matrix2[i][j] < 10 ? " " : "") + matrix2[i][j] + " ");}if (i != Math.ceil(matrix1.length / 2))System.out.print(" ");elseSystem.out.print("= ");for (int j = 0; j < matrix1[i].length; j++) {System.out.print((sumOfMatrix[i][j] < 10 ? " " : "") + sumOfMatrix[i][j] + "");}System.out.println();}}}7.6 import java.util.Scanner;public class Exercise06 {public static void main(String[] args) {Scanner input = new Scanner(System.in);double[][] matrix1 = new double[3][3];double[][] matrix2 = new double[3][3];System.out.println("Enter a 3-by-3 matrix1:");for (int i = 0; i < matrix1.length; i++) {for (int j = 0; j < matrix1[i].length; j++)matrix1[i][j] = input.nextDouble();}System.out.println("Enter a 3-by-3 matrix2:");for (int i = 0; i < matrix2.length; i++) {for (int j = 0; j < matrix2[i].length; j++)matrix2[i][j] = input.nextDouble();}double[][] multiplyMatrix = multiplyMatrix(matrix1, matrix2);for (int i = 0; i < matrix1.length; i++) {for (int j = 0; j < matrix1[i].length; j++) {System.out.print(matrix1[i][j] + " ");}if (i != Math.ceil(matrix1.length / 2))System.out.print(" ");elseSystem.out.print("* ");for (int j = 0; j < matrix2[i].length; j++) {System.out.print(matrix2[i][j] + " ");}if (i != Math.ceil(matrix1.length / 2))System.out.print(" ");elseSystem.out.print("= ");for (int j = 0; j < matrix1[i].length; j++) {System.out.print((int)(multiplyMatrix[i][j] * 10) / 10.0 + " ");}System.out.println();}}public static double[][] multiplyMatrix(double[][] a, double[][] b) {double[][] multiply = new double[a.length][a[0].length];for (int i = 0; i < a.length; i++) {for (int j = 0; j < multiply[i].length; j++) {for (int m = 0; m < a.length; m++)multiply[i][j] += a[i][m] * b[m][j];}}return multiply;}}7.7 public class Exercise07 {public static void main(String[] args) {double[][] points = {{-1, 0, 3}, {-1, -1, -1}, {4, 1, 1}, {2, 0.5, 9}, {3.5, 2, -1}, {3, 1.5, 3}, {-1.5, 4, 2}, {5.5, 4, -0.5}};//p1 and p2 are the indices in the points arrayint p1 = 0, p2 = 1; //Initial two pointsdouble shortestDistance = distance(points[p1][0], points[p1][1], points[p1][2],points[p2][0], points[p2][1], points[p2][2]); //Initialize shortestDistance//Compute distance for every two pointsfor (int i = 0; i < points.length; i++) {for (int j = i + 1; j < points.length; j++) {double distance = distance(points[i][0], points[i][1], points[i][2],points[j][0], points[j][1], points[j][2]); //Find distanceif (distance < shortestDistance) {p1 = i; //Update p1p2 = j; //Update p2shortestDistance = distance; //Update shortestDistance}}}//Display resultSystem.out.println("The closest two points are " + "(" + points[p1][0] + ", " +points[p1][1] + points[p1][2] + ") and (" +points[p2][0] + ", " + points[p2][1] + points[p2][2] + ")");}public static double distance(double x1, double y1, double z1, double x2, double y2, double z2) {return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1) + (z2 - z1) * (z2 - z1));}}7.8 import java.util.Scanner;public class Exercise08 {public static void main(String[] args) {double[][] points = {{-1, 3}, {-1, -1}, {1, 1}, {0, 0.5},{2, 0.5}, {2, -1}, {3, 3}, {4, 2}, {4, -0.5}};//p1 and p2 are the indices in the points arrayint p1 = 0, p2 = 1; //Initial two pointsdouble shortestDistance = distance(points[p1][0], points[p1][1],points[p2][0], points[p2][1]); //Initialize shortestDistanceint[][] indices = new int[points.length][2];int k = 0;indices[k][0] = p1;indices[k][1] = p2;//Compute distance for every two pointsfor (int i = 0; i < points.length; i++) {for (int j = i + 1; j < points.length; j++) {double distance = distance(points[i][0], points[i][1],points[j][0], points[j][1]); //Find distanceif (distance < shortestDistance) {indices[k][0] = i; //Update p1indices[k][1] = j; //Update p2shortestDistance = distance; //Update shortestDistance}else if (distance == shortestDistance) {k++;indices[k][0] = i;indices[k][1] = j;}}}// Display all closest pairsfor (int i = 0; i <= k; i++) {p1 = indices[i][0]; p2 = indices[i][1];System.out.println("The closest two points are " +"(" + points[p1][0] + ", " + points[p1][1] + ") and (" +points[p2][0] + ", " + points[p2][1] + ")");}System.out.println("Their distance is " + shortestDistance);}public static double distance(double x1, double y1, double x2, double y2) { return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));}}7.9 import java.util.Scanner;public class Exercise09 {public static void main(String[] args) {char[][] ticTacToe = new char[3][3];printTable(ticTacToe);enterX(ticTacToe);}/*** Player X to enter X*/public static void enterX(char[][] ticTacToe) {Scanner input = new Scanner(System.in);System.out.print("Enter a row (0, 1 or 2) for player X: ");int rowForX = input.nextInt();System.out.print("Enter a column (0, 1 or 2) for player X: ");int columnForX = input.nextInt();ticTacToe[rowForX][columnForX] = 'X';printTable(ticTacToe);if (status(ticTacToe)) {enterO(ticTacToe);}}/*** Player O to enter O*/public static void enterO(char[][] ticTacToe) {Scanner input = new Scanner(System.in);System.out.print("Enter a row (0, 1 or 2) for player O: ");int rowForO = input.nextInt();System.out.print("Enter a column (0, 1 or 2) for player O: ");int columnForO = input.nextInt();ticTacToe[rowForO][columnForO] = 'O';printTable(ticTacToe);if (status(ticTacToe)) {enterX(ticTacToe);}}/*** Display the board*/public static void printTable(char[][] array) {System.out.println("-------------");for (int i = 0; i < array.length; i++) {System.out.print("|");for (int j = 0; j < array[i].length; j++) {if (array[i][j] == 'X' | array[i][j] == 'O')System.out.print(" " + array[i][j] + " ");elseSystem.out.print(" ");System.out.print("|");}System.out.println();System.out.println("-------------");}}/*** Return false if one player wins or all the cells have been filled, return true if nobody wins */public static boolean status(char[][] array) {//return false if find one row, column or diagonal with all Xs or Osint i = 0, j = 0;while (i < 3 && j < 3) {if (array[i][j] == 'X' || array[i][j] == 'O') {if (i == 0 && j == 0) {if ((array[i][j] == array[i][j + 1] && array[i][j + 1] == array[i][j + 2]) ||(array[i][j] == array[i + 1][j] && array[i + 1][j] == array[i + 2][j]) ||(array[i][j] == array[i + 1][j + 1] && array[i + 1][j + 1] == array[i + 2][j + 2])) {System.out.println("Player " + array[i][j] + " won");return false;}}if (i == 1 && j == 1) {if ((array[i][j] == array[i][j - 1] && array[i][j] == array[i][j + 1]) ||(array[i][j] == array[i - 1][j] && array[i][j] == array[i + 1][j]) ||(array[i][j] == array[i - 1][j + 1] && array[i][j] == array[i + 1][j -1])) {System.out.println("Player " + array[i][j] + " won");return false;}}if (i == 2 && j == 2) {if ((array[i][j] == array[i][j - 1] && array[i][j] == array[i][j - 2]) ||(array[i][j] == array[i - 1][j] && array[i][j] == array[i - 2][j])) {System.out.println("Player " + array[i][j] + " won");return false;}}}i++;j++;}//return true if not all the cells have been filledfor (int m = 0; m < array.length; m++) {for (int n = 0; n < array[m].length; n++) {if (array[m][n] != 'X' && array[m][n] != 'O')return true;}}//return false if all the cells have been filledSystem.out.println("It's a draw");return false;}}7.10 public class Exercise10 {public static void main(String[] args) {int[][] ticTacToe = new int[3][3];for (int i = 0; i < ticTacToe.length; i++) {for (int j = 0; j < ticTacToe[i].length; j++)ticTacToe[i][j] = (int)(Math.random() * 2);}for (int i = 0; i < ticTacToe.length; i++) {for (int j = 0; j < ticTacToe[i].length; j++)System.out.print(ticTacToe[i][j]);System.out.println();}all0sOr1s(ticTacToe);}public static void all0sOr1s(int[][] array) {int i = 0, j = 0;while (i < array.length && j < array.length) {if (i == 0 && j == 0) {if (array[i][j] == array[i][j + 1] && array[i][j + 1] == array[i][j + 2])System.out.println("All " + array[i][j] + "s on row 0");if (array[i][j] == array[i + 1][j] && array[i + 1][j] == array[i + 2][j])System.out.println("All " + array[i][j] + "s on column 0");if (array[i][j] == array[i + 1][j + 1] && array[i + 1][j + 1] == array[i + 2][j + 2])System.out.println("All " + array[i][j] + "s on major diagonal");}if (i == 1 && j == 1) {if (array[i][j] == array[i][j - 1] && array[i][j] == array[i][j + 1])System.out.println("All " + array[i][j] + "s on row 1");if (array[i][j] == array[i - 1][j] && array[i][j] == array[i + 1][j])System.out.println("All " + array[i][j] + "s on column 1");if (array[i][j] == array[i - 1][j + 1] && array[i][j] == array[i + 1][j -1])System.out.println("All " + array[i][j] + "s on sub-diagonal");}if (i == 2 && j == 2) {if (array[i][j] == array[i][j - 1] && array[i][j] == array[i][j - 2])System.out.println("All " + array[i][j] + "s on row 2");if (array[i][j] == array[i - 1][j] && array[i][j] == array[i - 2][j])System.out.println("All " + array[i][j] + "s on column 2");}i++;j++;}}}7.11 import java.util.Scanner;public class Exercise11 {public static void main(String[] args) {//Create a ScannerScanner input = new Scanner(System.in);//Prompt the user to enter a numberSystem.out.print("Enter a number between 0 and 511: ");int number = input.nextInt();//Change the number to binaryint[][] matrix = decimalToBinary(number);//Display the matrix with charactersprintMatrix(matrix);}/*** Change a decimal number to a binary number*/public static int[][] decimalToBinary(int number) {int[][] matrix = new int[3][3];for (int i = matrix.length - 1; i >= 0; i--) {for (int j = matrix[i].length - 1; j >= 0; j--) {matrix[i][j] = number % 2;number = number / 2;}}return matrix;}/*** Print the matrix with characters*/public static void printMatrix(int[][] matrix) {for (int i = 0; i < matrix.length; i++) {for (int j = 0; j < matrix[i].length; j++) {if (matrix[i][j] == 0)System.out.print("H ");if (matrix[i][j] == 1)System.out.print("T ");}System.out.println();}}}7.12 import java.util.Scanner;public class Exercise12 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter the taxable income: ");double income = input.nextDouble();System.out.print("0-single filer, 1-married joinly,\n" +"2-married separately, 3-head of household\n" +"Enter the filing status: ");int status = input.nextInt();System.out.println("Tax is " + (int)(computeTax(income, status) * 100) / 100.0);}public static double computeTax(double income, int status) {double[] rates = {0.10, 0.15, 0.25, 0.28, 0.33, 0.35};int[][] brackets = {{8350, 33950, 82250, 171550, 372950}, //Single filer{16700, 67900, 137050, 208850, 372950}, //Married jointly{8350, 33950, 68525, 104425, 186475}, //Married separately{11950, 45500, 117450, 190200, 372950} //Head of household };double tax = 0;if (status == 0) {if (income <= brackets[0][0])tax = income * rates[0];else if (income <= brackets[0][1])tax = brackets[0][0] * rates[0] +(income - brackets[0][0]) * rates[1];else if (income <= brackets[0][2])tax = brackets[0][0] * rates[0] +(brackets[0][1] - brackets[0][0]) * rates[1] +(income - brackets[0][1]) * rates[2];else if (income <= brackets[0][3])tax = brackets[0][0] * rates[0] +(brackets[0][1] - brackets[0][0]) * rates[1] +(brackets[0][2] - brackets[0][1]) * rates[2] +(income - brackets[0][2]) * rates[3];else if (income <= brackets[0][4])tax = brackets[0][0] * rates[0] +(brackets[0][1] - brackets[0][0]) * rates[1] +(brackets[0][2] - brackets[0][1]) * rates[2] +(brackets[0][3] - brackets[0][2]) * rates[3] +(income - brackets[0][3]) * rates[4];elsetax = brackets[0][0] * rates[0] +(brackets[0][1] - brackets[0][0]) * rates[1] +(brackets[0][2] - brackets[0][1]) * rates[2] +(brackets[0][3] - brackets[0][2]) * rates[3] +(brackets[0][4] - brackets[0][3]) * rates[3] +(income - brackets[0][4]) * rates[5];}if (status == 1) {if (income <= brackets[1][0])tax = income * rates[0];else if (income <= brackets[1][1])tax = brackets[1][0] * rates[0] +(income - brackets[1][0]) * rates[1];else if (income <= brackets[1][2])tax = brackets[1][0] * rates[0] +(brackets[1][1] - brackets[1][0]) * rates[1] +(income - brackets[1][1]) * rates[2];else if (income <= brackets[1][3])tax = brackets[1][0] * rates[0] +(brackets[1][1] - brackets[1][0]) * rates[1] +(brackets[1][2] - brackets[1][1]) * rates[2] +(income - brackets[1][2]) * rates[3];else if (income <= brackets[1][4])tax = brackets[1][0] * rates[0] +(brackets[1][1] - brackets[1][0]) * rates[1] +(brackets[1][2] - brackets[1][1]) * rates[2] +(brackets[1][3] - brackets[1][2]) * rates[3] +(income - brackets[1][3]) * rates[4];elsetax = brackets[1][0] * rates[0] +(brackets[1][1] - brackets[1][0]) * rates[1] +(brackets[1][2] - brackets[1][1]) * rates[2] +(brackets[1][3] - brackets[1][2]) * rates[3] +(brackets[1][4] - brackets[1][3]) * rates[3] +(income - brackets[1][4]) * rates[5];}if (status == 2) {if (income <= brackets[2][0])tax = income * rates[0];else if (income <= brackets[2][1])tax = brackets[2][0] * rates[0] +(income - brackets[2][0]) * rates[1];else if (income <= brackets[2][2])tax = brackets[2][0] * rates[0] +(brackets[2][1] - brackets[2][0]) * rates[1] +(income - brackets[2][1]) * rates[2];else if (income <= brackets[2][3])tax = brackets[2][0] * rates[0] +(brackets[2][1] - brackets[2][0]) * rates[1] +(brackets[2][2] - brackets[2][1]) * rates[2] +(income - brackets[2][2]) * rates[3];else if (income <= brackets[2][4])tax = brackets[2][0] * rates[0] +(brackets[2][1] - brackets[2][0]) * rates[1] +(brackets[2][2] - brackets[2][1]) * rates[2] +(brackets[2][3] - brackets[2][2]) * rates[3] +(income - brackets[2][3]) * rates[4];elsetax = brackets[2][0] * rates[0] +(brackets[2][1] - brackets[2][0]) * rates[1] +(brackets[2][2] - brackets[2][1]) * rates[2] +(brackets[2][3] - brackets[2][2]) * rates[3] +(brackets[2][4] - brackets[2][3]) * rates[3] +(income - brackets[2][4]) * rates[5];}if (status == 3) {if (income <= brackets[3][0])tax = income * rates[0];else if (income <= brackets[3][1])tax = brackets[3][0] * rates[0] +(income - brackets[3][0]) * rates[1];else if (income <= brackets[3][2])tax = brackets[3][0] * rates[0] +(brackets[3][1] - brackets[3][0]) * rates[1] +(income - brackets[3][1]) * rates[2];else if (income <= brackets[3][3])tax = brackets[3][0] * rates[0] +(brackets[3][1] - brackets[3][0]) * rates[1] +(brackets[3][2] - brackets[3][1]) * rates[2] +(income - brackets[3][2]) * rates[3];else if (income <= brackets[3][4])tax = brackets[3][0] * rates[0] +(brackets[3][1] - brackets[3][0]) * rates[1] +(brackets[3][2] - brackets[3][1]) * rates[2] +(brackets[3][3] - brackets[3][2]) * rates[3] +(income - brackets[3][3]) * rates[4];elsetax = brackets[3][0] * rates[0] +(brackets[3][1] - brackets[3][0]) * rates[1] +(brackets[3][2] - brackets[3][1]) * rates[2] +(brackets[3][3] - brackets[3][2]) * rates[3] +(brackets[3][4] - brackets[3][3]) * rates[3] +(income - brackets[3][4]) * rates[5];}return tax;}}7.13 import java.util.Scanner;public class Exercise13 {public static void main(String[] args) {//Create a ScannerScanner input = new Scanner(System.in);//Prompt the user to enter the number of rows and columns of the arraySystem.out.print("Enter the number of rows and columns of the array: ");int rows = input.nextInt();int columns = input.nextInt();//Prompt the user to enter the arraySystem.out.println("Enter the array:");double[][] array = new double[rows][columns];for (int i = 0; i < array.length; i++) {for (int j = 0; j < array[i].length; j++)array[i][j] = input.nextDouble();}//Display the location of the largest element in the arrayint[] location = findLocation(array);System.out.println("The location of the largest element is at (" + location[0] + ", " + location[1] + ")");}/*** Return the location of the largest element in the array*/public static int[] findLocation(double[][] array) {//Assume array[0][0] is the largest elementdouble largest = array[0][0];int[] location = {0, 0};//Repeatedly find the largest elementfor (int i = 0; i < array.length; i++) {for (int j = 0; j < array[i].length; j++) {if (array[i][j] > largest) {largest = array[i][j];location[0] = i;location[1] = j;}}}return location;}}7.14 import java.util.Scanner;public class Exercise14 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter the size of the matrix: ");int size = input.nextInt();int[][] matrix = new int[size][size];for (int i = 0; i < matrix.length; i++) {for (int j = 0; j < matrix[i].length; j++)matrix[i][j] = (int)(Math.random() * 2);}printMatrix(matrix);find0sAnd1s(matrix);}public static void printMatrix(int[][] array) {for (int i = 0; i < array.length; i++) {for (int j = 0; j < array[i].length; j++)System.out.print(array[i][j]);System.out.println();}}public static void find0sAnd1s(int[][] array) {int i = 0, j= 0;int countRow = 0, countColumn = 0, countMajorDiagonal = 0;while (i < array.length && j < array.length) {int a = array[0][0];int b = array[i][j];for (int n = 0; n < array.length; n++) {if (array[i][n] != b)break;else {if (n == array.length - 1) {System.out.println("All " + b + "s on row " + i);countRow++;}}}for (int n = 0; n < array.length; n++) {if (array[n][j] != b)break;else {if (n == array.length - 1) {System.out.println("All " + b + "s on column " + j);countColumn++;}}}if (b != a)countMajorDiagonal++;i++;j++;}if (countRow == 0)System.out.println("No same numbers on a row");if (countColumn == 0)System.out.println("No same number on a column");if (countMajorDiagonal == 0)System.out.println("All " + array[0][0] + "s on the major diagonal");if (countMajorDiagonal > 0)System.out.println("No same numbers on the major diagonal");for (int p = 1, q = array.length - 2; p < array.length && q >= 0; p++, q--) {if (array[p][q] != array[0][array.length - 1]) {System.out.println("No same numbers on the sub-diagonal");break;}else {if (p == array.length - 1 && q == 0)System.out.println("All " + array[0][array.length - 1] + "s on the sub-diagonal");}}}}7.15 public class Exercise15 {public static void main(String[] args) {double[][] set1 = {{-1, -1}, {2, 2}, {3, 3}, {4, 4}};double[][] set2 = {{0, 1}, {1, 2}, {4, 5}, {5, 6}};double[][] set3 = {{0, 1}, {1, 2}, {4, 5}, {4.5, 4}};System.out.println("Is set1 on the same line? " + isOnSameLine(set1));。

相关文档
最新文档