Java语言程序设计基础篇全习题答案16
java语言程序设计基础篇复习题答案
java语言程序设计基础篇复习题答案Java语言程序设计是计算机科学与技术专业中的一门重要课程,掌握好基础知识对于学习和应用Java编程语言至关重要。
本文将为大家提供一些Java语言程序设计基础篇复习题的答案,帮助大家更好地理解和掌握这门课程。
1. 什么是Java语言?Java语言是一种面向对象的编程语言,由Sun Microsystems公司于1995年推出。
它具有简单、跨平台、安全、高性能等特点,广泛应用于Web开发、企业级应用开发、移动应用开发等领域。
2. Java程序的基本结构是什么?Java程序的基本结构由类(class)组成,每个Java程序都必须包含一个public 类,且类名必须与文件名相同。
一个Java程序可以包含多个类,但只能有一个public类。
3. 如何定义一个类?在Java中,可以使用关键字class来定义一个类。
类的定义通常包含类的修饰符、类名、类体等部分。
例如:```public class MyClass {// 类体}```4. 如何定义一个方法?在Java中,可以使用关键字public、private、protected等修饰符来定义一个方法。
方法的定义通常包含返回类型、方法名、参数列表、方法体等部分。
例如:```public void myMethod() {// 方法体}```5. 如何定义一个变量?在Java中,可以使用关键字int、double、String等来定义一个变量。
变量的定义通常包含变量类型、变量名、初始值等部分。
例如:```int myVariable = 10;```6. 如何使用条件语句?在Java中,可以使用if语句和switch语句来实现条件判断。
if语句根据条件的真假执行相应的代码块,switch语句根据表达式的值执行相应的代码块。
例如:```int num = 10;if (num > 0) {System.out.println("num是正数");} else if (num < 0) {System.out.println("num是负数");} else {System.out.println("num是零");}int day = 3;switch (day) {case 1:System.out.println("星期一");break;case 2:System.out.println("星期二");break;// ...default:System.out.println("其他");break;}```7. 如何使用循环语句?在Java中,可以使用for循环、while循环和do-while循环来实现循环操作。
java语言程序设计课后习题答案
java语言程序设计课后习题答案第一章:计算机、程序和JAVA概述1、2、1什么是硬件和软件?答:硬件指计算机中可见的物理部分;而软件提供不可见的指令,这些指令控制硬件并使硬件完成特定的任务。
1、2、2列举计算机的5个主要硬件组件。
答:中央处理器(CPU);内存(主存);存储设备(磁盘、光盘);输入设备(鼠标、键盘);输出设备(显示器、打印机);通信设备(调制解调器、网卡)。
1、2、3编写“CPU”代表什么含义?测量CPU速度的单位是什么?答:CPU(Central Proceing Unit)中央处理单元,包括控制单元和算术、逻辑单元;单位是HZ,现在通常以MHZ,GHZ数量级衡量。
1、2、4什么是比特?什么是字节?答:bit是计算机物理设备中存储的最小单位;8个bit为1个byte。
1、2、5内存是用来做什么的?RAM代表什么?为什么内存成为RAM?答:内存用来存储程序和数据;RAM(Random-Acce Memory)-可随机访问存储介质;因为内存可以按任意顺序存取字节所以被称为RAM(按功能划分)。
1、2、6用于测量内存大小的单位是什么?用于测量磁盘大小的单位是什么?答:GB,TB1、2、7内存和永久存储设备的主要不同是什么?答:内存是易失性存储介质(断电即失),存储容量小,传输速度快;永久存储设备为非易失性存储介质(断电可留),存储容量大,传输速度慢。
1、3、1CPU能理解什么语言。
机器语言。
1、3、2什么是汇编语言?什么是汇编器?汇编语言能用短的描述性单词来表示每一条机器语言指令,是一种低级语言。
汇编器可以将汇编语言转换成机器语言。
1、3、3什么是高级编程语言?什么是源程序?很像英语,易于学习和使用的编程语言称为高级编程语言。
使用高级编程语言编写的程序称为源程序。
1、3、4什么是解释器?什么是编译器?解释器会逐条读取源代码中的语言,并立刻翻译成机器代码或者虚拟机器代码,然后立刻运行。
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基础入门》课后习题第1章Java开发入门一、填空题1、Java的三大体系分别是_JavaSE_____、_JavaEE_____、_JavaME_____。
2、Java程序的运行环境简称之为JRE_____。
3、编译Java程序需要使用_javac_____命令。
4、javac.exe和java.exe两个可执行程序存放在JDK安装目录的bin______目录下。
5、path______环境变量用来存储Java的编译和运行工具所在的路径,而_classpath_____环境变量则用来保存保存Java虚拟机要运行的“.class”文件路径。
二、选择题1、以下选项中,哪些属于JDK工具?(多选)ABCDA、Java编译器B、Java运行工具C、Java文档生成工具D、Java打包工具2、Java属于以下哪种语言?CA、机器语言B、汇编语言C、高级语言D、以上都不对3、下面哪种类型的文件可以在Java虚拟机中运行?DA、.javaB、.jreC、.exeD、.class4、安装好JDK后,在其bin目录下有许多exe可执行文件,其中java.exe命令的作用是以下哪一种?BA、Java文档制作工具B、Java解释器C、Java编译器D、Java启动器5、如果jdk的安装路径为:d:\jdk,若想在命令窗口中任何当前路径下,都可以直接使用javac和java命令,需要将环境变量path设置为以下哪个选项?B A.d:\jdk; B.d :\jdk\bin; C.d:\jre\bin; D.d:\jre;三、问答题1、简述Java的特点。
面向对象、跨平台性、健壮性、安全性、可移植性、多线程性、动态性等。
2、简述JRE与JDK的区别。
JRE(Java Runtime Environment,Java运行时环境),它相当于操作系统部分,提供了Java程序运行时所需要的基本条件和许多Java基础类,例如,IO类、GUI控件类、网络类等。
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程序设计基础”课程习题一、填空1.Java程序分两类___Applet___和application,Java Application 类型的程序,程序从___main方法___开始执行。
2.定义一个Java类时,通过关键字__extends____指明该类的父类。
一个类可以有___1___个父类。
3.用public修饰的类称为_公有类或公用类__。
用public修饰的类成员称为公有成员。
被说明为public的内容可以被__所有其他类___ 使用。
如果public类文件与使用它的类文件不在同一目录中,需要通过__import____语句引入。
4.用___private___ 修饰的类成员称为私有成员。
私有成员只能在__本类__ 中使用。
5.如果子类定义的成员变量与父类的成员变量同名,称为___方法覆盖___ ,要表明使用子类的成员变量,可以在成员变量前加上关键字__super___ 。
6.____Object__ 类是Java类库中所有类的父类。
7.Java字符使用__16位的字符集,该字符集成为__Unicode____ 。
8.当子类中定义的方法与父类方法同名时,称子类方法___覆盖___ 父类方法,子类默认使用自己的方法。
使用父类的同名方法,必须用关键字__super__ 说明。
9.Java源程序文件名的后缀是___.java___,Java字节码文件名的后缀是_.class_____。
10.Java类名的第一个字母通常要求___大写___。
11.Java程序由____类__组成,每个程序有一个主类,Java程序文件名应与____主__类的名称相同。
12.Java__Application_类型的程序需要main()方法,程序从__main____开始执行。
13.布尔型数据类型的关键字是_boolean__ ,占用位数是___1位___ ,有__true__ 和_false_两种值。
《Java语言程序设计(基础篇)》(第10版 梁勇 著)第十六章练习题答案
《Java语言程序设计(基础篇)》(第10版梁勇著)第十六章练习题答案16.1import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.control.RadioButton;import javafx.scene.control.ToggleGroup;import yout.BorderPane;import yout.HBox;import yout.Pane;import javafx.scene.paint.Color;import javafx.scene.text.Font;import javafx.scene.text.Text;import javafx.stage.Stage;public class Exercise16_01 extends Application {private double paneWidth = 500;private double paneHeight = 150;@Override // Override the start method in the Application class public void start(Stage primaryStage) {Text text = new Text(20, 40, "Programming is fun");text.setFont(new Font("Times", 20));Pane paneForText = new Pane();paneForText.getChildren().add(text);paneForText.setStyle("-fx-border-color: gray");RadioButton rbRed = new RadioButton("Red");RadioButton rbYellow = new RadioButton("Yellow");RadioButton rbBlack = new RadioButton("Black");RadioButton rbOrange = new RadioButton("Orange");RadioButton rbGreen = new RadioButton("Green");ToggleGroup group = new ToggleGroup();rbRed.setToggleGroup(group);rbYellow.setToggleGroup(group);rbBlack.setToggleGroup(group);rbBlack.setSelected(true);rbOrange.setToggleGroup(group);rbGreen.setToggleGroup(group);HBox hBox = new HBox(5);hBox.getChildren().addAll(rbRed, rbYellow, rbBlack, rbOrange, rbGreen); hBox.setAlignment(Pos.CENTER);Button btLeft = new Button("<=");Button btRight = new Button("=>");HBox hBoxForButtons = new HBox(5);hBoxForButtons.getChildren().addAll(btLeft, btRight);hBoxForButtons.setAlignment(Pos.CENTER);BorderPane borderPane = new BorderPane();borderPane.setTop(hBox);borderPane.setCenter(paneForText);borderPane.setBottom(hBoxForButtons);// Create a scene and place it in the stageScene scene = new Scene(borderPane, paneWidth, paneHeight + 40);primaryStage.setTitle("Exercise16_01"); // Set the stage titleprimaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stagerbRed.setOnAction(e -> text.setStroke(Color.RED));rbYellow.setOnAction(e -> text.setStroke(Color.YELLOW));rbBlack.setOnAction(e -> text.setStroke(Color.BLACK));rbOrange.setOnAction(e -> text.setStroke(Color.ORANGE));rbGreen.setOnAction(e -> text.setStroke(Color.GREEN));btLeft.setOnAction(e -> text.setX(text.getX() - 1));btRight.setOnAction(e -> text.setX(text.getX() + 1));}/*** The main method is only needed for the IDE with limited* JavaFX support. Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}16.1附加import javafx.application.Application;import javafx.scene.Scene;import yout.*;import javafx.scene.paint.Color;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.geometry.Pos;public class Exercise16_01Extra extends Application {final static double PANEL_WIDTH = 400;final static double PANEL_HEIGHT = 140;@Override // Override the start method in the Application classpublic void start(Stage primaryStage) {GridPane paneForOriginal = new GridPane();GridPane paneForInversed = new GridPane();TextField[][] tfOriginal = new TextField[3][3];TextField[][] tfInversed = new TextField[3][3];for (int i = 0; i < 3; i++) {for (int j = 0; j < 3; j++) {paneForOriginal.add(tfOriginal[i][j] = new TextField(), j, i); tfOriginal[i][j].setPrefColumnCount(4);paneForInversed.add(tfInversed[i][j] = new TextField(), j, i); tfInversed[i][j].setPrefColumnCount(4);}}BorderPane p1 = new BorderPane();p1.setCenter(paneForOriginal);p1.setTop(new Label("Original Matrix"));BorderPane p2 = new BorderPane();p2.setCenter(paneForInversed);final Label lblStatus = new Label("Inversed Matrix");p2.setTop(lblStatus);HBox hBox = new HBox(5);hBox.getChildren().addAll(p1, p2);BorderPane pane = new BorderPane();pane.setCenter(hBox);Button btGetInverse = new Button("Get Inverse");pane.setBottom(btGetInverse);BorderPane.setAlignment(btGetInverse, Pos.CENTER);Scene scene = new Scene(pane, PANEL_WIDTH, PANEL_HEIGHT);primaryStage.setTitle("Exercise16_01"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stagebtGetInverse.setOnAction(e -> {double[][] A = new double[3][3];for (int i = 0; i < 3; i++)for (int j = 0; j < 3; j++) {A[i][j] = Double.parseDouble(tfOriginal[i][j].getText()); }double[][] inverseA = Exercise08_03Extra.inverse(A);if (inverseA == null)lblStatus.setText("Invered matrix: No inverse matrix");else {for (int i = 0; i < 3; i++)for (int j = 0; j < 3; j++) {tfInversed[i][j].setText(inverseA[i][j] + "");}}});}/*** The main method is only needed for the IDE with limited* JavaFX support. Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}16.2import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.CheckBox;import javafx.scene.control.RadioButton;import javafx.scene.control.ToggleGroup;import yout.BorderPane;import yout.HBox;import yout.StackPane;import javafx.scene.paint.Color;import javafx.scene.shape.Circle;import javafx.scene.shape.Ellipse;import javafx.scene.shape.Rectangle;import javafx.stage.Stage;public class Exercise16_02 extends Application {private double paneWidth = 500;private double paneHeight = 150;@Override // Override the start method in the Application classpublic void start(Stage primaryStage) {StackPane pane = new StackPane();Circle circle = new Circle(20, 20, 50);circle.setStroke(Color.BLACK);circle.setFill(Color.WHITE);Rectangle rectangle = new Rectangle(20, 20, 80, 50);rectangle.setStroke(Color.BLACK);Ellipse ellipse = new Ellipse(20, 20, 50, 70);ellipse.setStroke(Color.BLACK);pane.setStyle("-fx-border-color: gray");pane.getChildren().add(circle);RadioButton rbCircle = new RadioButton("Circle");RadioButton rbRectangle = new RadioButton("Rectangle");RadioButton rbEllipse = new RadioButton("Ellipse");CheckBox chkFill = new CheckBox("Fill");ToggleGroup group = new ToggleGroup();rbCircle.setToggleGroup(group);rbCircle.setSelected(true);rbRectangle.setToggleGroup(group);rbEllipse.setToggleGroup(group);HBox hBox = new HBox(5);hBox.getChildren().addAll(rbCircle, rbRectangle, rbEllipse, chkFill); hBox.setAlignment(Pos.CENTER);BorderPane borderPane = new BorderPane();borderPane.setCenter(pane);borderPane.setBottom(hBox);// Create a scene and place it in the stageScene scene = new Scene(borderPane, paneWidth, paneHeight + 40); primaryStage.setTitle("Exercise16_02"); // Set the stage titleprimaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stagerbCircle.setOnAction(e -> {pane.getChildren().clear();pane.getChildren().add(circle);if (chkFill.isSelected()) {circle.setFill(Color.BLACK);}else {circle.setFill(Color.WHITE);}});rbRectangle.setOnAction(e -> {pane.getChildren().clear();pane.getChildren().add(rectangle);if (chkFill.isSelected()) {rectangle.setFill(Color.BLACK);}else {rectangle.setFill(Color.WHITE);}});rbEllipse.setOnAction(e -> {pane.getChildren().clear();pane.getChildren().add(ellipse);if (chkFill.isSelected()) {ellipse.setFill(Color.BLACK);}else {ellipse.setFill(Color.WHITE);}});chkFill.setOnAction(e -> {if (chkFill.isSelected()) {circle.setFill(Color.BLACK);rectangle.setFill(Color.BLACK);ellipse.setFill(Color.BLACK);}else {circle.setFill(Color.WHITE);rectangle.setFill(Color.WHITE);ellipse.setFill(Color.WHITE);}});}/*** The main method is only needed for the IDE with limited* JavaFX support. Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}16.2附加import javafx.application.Application;import javafx.scene.Scene;import yout.*;import javafx.scene.paint.Color;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.geometry.Pos;public class Exercise16_02Extra extends Application {final static double PANEL_WIDTH = 400;final static double PANEL_HEIGHT = 140;@Override // Override the start method in the Application class public void start(Stage primaryStage) {GridPane paneForOriginal = new GridPane();GridPane paneForInversed = new GridPane();TextField[][] tfA = new TextField[3][3];TextField[] tfB = new TextField[3];for (int i = 0; i < 3; i++) {for (int j = 0; j < 3; j++) {tfA[i][j] = new TextField();tfA[i][j].setPrefColumnCount(4);}tfB[i] = new TextField();tfB[i].setPrefColumnCount(4);}HBox[] hBoxes = new HBox[3];for (int i = 0; i < 3; i++) {hBoxes[i] = new HBox(5);hBoxes[i].getChildren().addAll(tfA[i][0], new Label("x"), tfA[i][1], new Label("y"), tfA[i][2], new Label("z = "), tfB[i]);}VBox vBox = new VBox(5);vBox.getChildren().addAll(hBoxes[0], hBoxes[1], hBoxes[2]);HBox hBox = new HBox(5);Label lblStatus = new Label();Button btSolveEquation = new Button("Solve Equation");hBox.getChildren().addAll(btSolveEquation, lblStatus);BorderPane pane = new BorderPane();pane.setCenter(vBox);pane.setBottom(hBox);Scene scene = new Scene(pane, PANEL_WIDTH, PANEL_HEIGHT);primaryStage.setTitle("Exercise16_02"); // Set the stage titleprimaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stagebtSolveEquation.setOnAction(e -> {double[][] A = new double[3][3];double[] B = new double[3];for (int i = 0; i < 3; i++) {for (int j = 0; j < 3; j++) {A[i][j] = Double.parseDouble(tfA[i][j].getText());}B[i] = Double.parseDouble(tfB[i].getText());}double[] result = Exercise08_02Extra.getSolution(A, B);if (result == null)lblStatus.setText("No solutions");elselblStatus.setText("Solution is x = "+ result[0] + ", y is = "+ result[1]+ ", and z is = " + result[2]);});}/*** The main method is only needed for the IDE with limited* JavaFX support. Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}16.3import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.RadioButton;import javafx.scene.control.ToggleGroup;import yout.BorderPane;import yout.HBox;import yout.Pane;import javafx.scene.paint.Color;import javafx.scene.shape.Circle;import javafx.scene.shape.Rectangle;import javafx.stage.Stage;public class Exercise16_03 extends Application {private double paneWidth = 200;private double paneHeight = 90;@Override // Override the start method in the Application class public void start(Stage primaryStage) {Pane pane = new Pane();Circle circleRed = new Circle(paneWidth / 2, 20, 10);Circle circleYellow = new Circle(paneWidth / 2, 50, 10);Circle circleGreen = new Circle(paneWidth / 2, 80, 10);circleRed.setStroke(Color.BLACK);circleYellow.setStroke(Color.BLACK);circleGreen.setStroke(Color.BLACK);circleRed.setFill(Color.WHITE);circleYellow.setFill(Color.WHITE);circleGreen.setFill(Color.WHITE);Rectangle rectangle = new Rectangle(paneWidth / 2 - 15, 5, 30, 90); rectangle.setFill(Color.WHITE);rectangle.setStroke(Color.BLACK);pane.getChildren().addAll(rectangle, circleRed, circleYellow, circleGreen);RadioButton rbRed = new RadioButton("Red");RadioButton rbYellow = new RadioButton("Yellow");RadioButton rbGreen = new RadioButton("Green");ToggleGroup group = new ToggleGroup();rbRed.setToggleGroup(group);rbYellow.setToggleGroup(group);rbGreen.setToggleGroup(group);HBox hBox = new HBox(5);hBox.getChildren().addAll(rbRed, rbYellow, rbGreen);hBox.setAlignment(Pos.CENTER);BorderPane borderPane = new BorderPane();borderPane.setCenter(pane);borderPane.setBottom(hBox);// Create a scene and place it in the stageScene scene = new Scene(borderPane, paneWidth, paneHeight + 40);primaryStage.setTitle("Exercise16_03"); // Set the stage titleprimaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stagerbRed.setOnAction(e -> {circleRed.setFill(Color.RED);circleYellow.setFill(Color.WHITE);circleGreen.setFill(Color.WHITE);});rbYellow.setOnAction(e -> {circleYellow.setFill(Color.YELLOW);circleRed.setFill(Color.WHITE);circleGreen.setFill(Color.WHITE);});rbGreen.setOnAction(e -> {circleGreen.setFill(Color.GREEN);circleYellow.setFill(Color.WHITE);circleRed.setFill(Color.WHITE);});}/*** The main method is only needed for the IDE with limited* JavaFX support. Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}16.3附加import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import yout.*;import javafx.scene.paint.Color;import javafx.scene.control.*;import javafx.scene.shape.Rectangle;import javafx.stage.Stage;public class Exercise16_03Extra extends Application {@Override // Override the start method in the Application classpublic void start(Stage primaryStage) {HBox hBox = new HBox(5);TextField tfRed = new TextField();tfRed.setPrefColumnCount(4);TextField tfBlue = new TextField();tfBlue.setPrefColumnCount(4);TextField tfGreen = new TextField();tfGreen.setPrefColumnCount(4);hBox.getChildren().addAll(new Label("Red"), tfRed, new Label("Blue"), tfBlue, new Label("Green"), tfGreen);hBox.setAlignment(Pos.CENTER);BorderPane pane = new BorderPane();MandelbrotCanvas canvas = new MandelbrotCanvas();pane.setCenter(canvas);pane.setBottom(hBox);// Create a scene and place it in the stageScene scene = new Scene(pane, 425, 450);primaryStage.setTitle("Exercise16_03"); // Set the stage titleprimaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stagetfRed.setOnAction(e -> {canvas.setRed(Integer.parseInt(tfRed.getText()));canvas.paint();});tfBlue.setOnAction(e -> {canvas.setBlue(Integer.parseInt(tfBlue.getText()));canvas.paint();});tfGreen.setOnAction(e -> {canvas.setGreen(Integer.parseInt(tfGreen.getText()));canvas.paint();});}/*** The main method is only needed for the IDE with limited* JavaFX support. Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}class MandelbrotCanvas extends Pane {final static int COUNT_LIMIT = 60;MandelbrotCanvas() {paint();}private void paint() {this.getChildren().clear();for (double x = -2.0; x < 2.0; x += 0.01)for (double y = -2.0; y < 2.0; y += 0.01) {Rectangle rectangle = new Rectangle(x * 100 + 200, y * 100 + 200, 1.0, 1.0);this.getChildren().add(rectangle); // Fill the rectangle with the specified colorint c = count(new Complex(x, y));if (c == COUNT_LIMIT)rectangle.setFill(Color.BLACK); // c is in a Mandelbrot set elserectangle.setFill(Color.rgb(c * red % 256, c * blue % 256, c * green % 256));}}int red = 77;int blue = 58;int green = 159;public void setRed(int red) {this.red = red;}public void setBlue(int blue) {this.blue = blue;}public void setGreen(int green) {this.green = green;}/** Returns the iteration count */int count(Complex c) {Complex z = new Complex(0, 0); // z0for (int i = 0; i < COUNT_LIMIT; i++) {z = z.multiply(z).add(c); // Get z1, z2, ...if (z.abs() > 2) return i; // The sequence is unbounded}return COUNT_LIMIT; // Indicates a bounded sequence}}}16.4import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import bel;import javafx.scene.control.TextField;import yout.GridPane;import javafx.stage.Stage;public class Exercise16_04 extends Application {private double paneWidth = 250;private double paneHeight = 60;@Override // Override the start method in the Application class public void start(Stage primaryStage) {TextField tfMile = new TextField();TextField tfKilometer = new TextField();tfMile.setAlignment(Pos.BOTTOM_RIGHT);tfKilometer.setAlignment(Pos.BOTTOM_RIGHT);GridPane pane = new GridPane();pane.setAlignment(Pos.CENTER);pane.add(new Label("Mile"), 0, 0);pane.add(tfMile, 1, 0);pane.add(new Label("Kilometer"), 0, 1);pane.add(tfKilometer, 1, 1);// Create a scene and place it in the stageScene scene = new Scene(pane, paneWidth, paneHeight);primaryStage.setTitle("Exercise16_04"); // Set the stage titleprimaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stagetfMile.setOnAction(e -> {double mile = new Double(tfMile.getText().trim()).doubleValue();double kilometer = mile / 0.6241;tfKilometer.setText(new Double(kilometer).toString());});tfKilometer.setOnAction(e -> {double kilometer = newDouble(tfKilometer.getText().trim()).doubleValue();double mile = 0.6241 * kilometer;tfMile.setText(new Double(mile).toString());});}/*** The main method is only needed for the IDE with limited* JavaFX support. Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}16.4附加import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.*;import yout.*;import javafx.stage.Stage;public class Exercise16_04Extra extends Application {private double paneWidth = 520;private double paneHeight = 240;private String singleFilerScheme ="Single Filers\nTaxable Income\t\tRate\n" +"Up to $27,050\t\t15%\n"+"$27,051 - $65,550\t27.5%\n" +"$65,551 - $136,750\t30.5%\n" +"$136,751 - $297,350\t35.5%\n" +"$297,351 or more\t39.1%";private String marriedJointlyFilerScheme ="Married Jointly Fliers\nTaxable Income\t\tRate\n" +"Up to $45,200\t\t15%\n"+"$45,201 - $109,250\t27.5%\n" +"$109,251 - $166,500\t30.5%\n" +"$166,501 - $297,350\t35.5%\n" +"$297,351 or more\t39.1%";private String marriedSeparatelyFilerScheme ="Married Separately Fliers\nTaxable Income\t\tRate\n" +"Up to $22,600\t\t15%\n"+"$22,601 - $54,655\t27.5%\n" +"$54,656 - $83,250\t30.5%\n" +"$83,251 - $148,675\t35.5%\n" +"$148,676 or more\t39.1%";private String headOfHouseFilerScheme ="Head of Household Fliers\nTaxable Income\t\tRate\n" +"Up to $36,250\t\t15%\n"+"$36,251 - $93,650\t27.5%\n" +"$93,651 - $151,650\t30.5%\n" +"$151,651 - $297,350\t35.5%\n" +"$297,351 or more\t39.1%";@Override // Override the start method in the Application classpublic void start(Stage primaryStage) {RadioButton singleFiler = new RadioButton("Single filers");singleFiler.setSelected(true);RadioButton marriedJointly = new RadioButton("Married filing jointly or qualifying widow(er)");RadioButton marriedSeparately = new RadioButton("Married filing separately");RadioButton headOfHousehold = new RadioButton("Head of Household");ToggleGroup group = new ToggleGroup();singleFiler.setToggleGroup(group);marriedJointly.setToggleGroup(group);marriedSeparately.setToggleGroup(group);headOfHousehold.setToggleGroup(group);VBox vBox = new VBox(5);vBox.getChildren().addAll(singleFiler, marriedJointly, marriedSeparately,headOfHousehold);HBox hBox = new HBox(5);Label lblDescription = new Label(singleFilerScheme);hBox.getChildren().addAll(vBox, lblDescription);GridPane pane = new GridPane();pane.setHgap(5);pane.setVgap(5);TextField tfTaxableIncome = new TextField();TextField tfTax = new TextField();tfTaxableIncome.setPrefColumnCount(8);tfTax.setPrefColumnCount(8);tfTax.setEditable(false);pane.setAlignment(Pos.CENTER);pane.add(new Label("Taxable income"), 0, 0);pane.add(tfTaxableIncome, 1, 0);pane.add(new Label("Tax"), 0, 1);pane.add(tfTax, 1, 1);Button btComputeTax = new Button("Compute Tax");pane.add(btComputeTax, 1, 2);VBox vBoxAll = new VBox(5);vBoxAll.getChildren().addAll(new Label("Select Tax Status"), hBox, pane);// Create a scene and place it in the stageScene scene = new Scene(vBoxAll, paneWidth, paneHeight);primaryStage.setTitle("Exercise16_04"); // Set the stage titleprimaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stagesingleFiler.setOnAction(e -> lblDescription.setText(singleFilerScheme)); marriedJointly.setOnAction(e ->lblDescription.setText(marriedJointlyFilerScheme));marriedSeparately.setOnAction(e ->lblDescription.setText(marriedSeparatelyFilerScheme));headOfHousehold.setOnAction(e ->lblDescription.setText(headOfHouseFilerScheme));btComputeTax.setOnAction(e -> {Tax tax = new Tax(); // Programming Exercise 10.8int status = 0;if (singleFiler.isSelected())status = 0;else if (marriedJointly.isSelected())status = 1;else if (marriedSeparately.isSelected())status = 2;else if (headOfHousehold.isSelected())status = 3;tax.setFilingStatus(status);tax.setTaxableIncome(Double.parseDouble(tfTaxableIncome.getText() + ""));tfTax.setText(tax.findTax() + "");});}/*** The main method is only needed for the IDE with limited* JavaFX support. Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}16.5import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import bel;import javafx.scene.control.TextField;import yout.GridPane;import javafx.stage.Stage;public class Exercise16_05 extends Application {private double paneWidth = 250;private double paneHeight = 90;@Override // Override the start method in the Application class public void start(Stage primaryStage) {TextField tfDecimal = new TextField();TextField tfHex = new TextField();TextField tfBinary = new TextField();tfDecimal.setAlignment(Pos.BOTTOM_RIGHT);tfHex.setAlignment(Pos.BOTTOM_RIGHT);tfBinary.setAlignment(Pos.BOTTOM_RIGHT);tfHex.setAlignment(Pos.BOTTOM_RIGHT);GridPane pane = new GridPane();pane.setAlignment(Pos.CENTER);pane.setHgap(10);pane.add(new Label("Decimal"), 0, 0);pane.add(tfDecimal, 1, 0);pane.add(new Label("Hex"), 0, 1);pane.add(tfHex, 1, 1);pane.add(new Label("Binary"), 0, 2);pane.add(tfBinary, 1, 2);// Create a scene and place it in the stageScene scene = new Scene(pane, paneWidth, paneHeight);primaryStage.setTitle("Exercise16_05"); // Set the stage titleprimaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stagetfDecimal.setOnAction(e -> {int decimal = Integer.parseInt(tfDecimal.getText());tfHex.setText(Integer.toHexString(decimal));tfBinary.setText(Integer.toBinaryString(decimal));});tfHex.setOnAction(e -> {int decimal = Integer.parseInt(tfHex.getText(), 16);tfDecimal.setText(decimal + "");tfBinary.setText(Integer.toBinaryString(decimal));});tfBinary.setOnAction(e -> {int decimal = Integer.parseInt(tfBinary.getText(), 2);tfDecimal.setText(decimal + "");tfHex.setText(Integer.toHexString(decimal));});}/*** The main method is only needed for the IDE with limited* JavaFX support. Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}16.5附加import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.*;import yout.*;import javafx.stage.Stage;public class Exercise16_05Extra extends Application {private double paneWidth = 240;private double paneHeight = 200;private Button bt1 = new Button("1");private Button bt2 = new Button("2");private Button bt3 = new Button("3");private Button bt4 = new Button("4");private Button bt5 = new Button("5");private Button bt6 = new Button("6");private Button bt7 = new Button("7");private Button bt8 = new Button("8");private Button bt9 = new Button("9");private Button bt0 = new Button("0");private Button btAdd = new Button("+");private Button btSubtract = new Button("-");private Button btMultiply = new Button("*");private Button btDivide = new Button("/");private Button btRemainder = new Button("%");private Button btSqrt = new Button("sqrt");private Button btDecimal = new Button(".");private Button btEqual = new Button("=");private TextField tf = new TextField();@Override // Override the start method in the Application class public void start(Stage primaryStage) {GridPane pane = new GridPane();pane.setHgap(5);pane.setVgap(5);pane.add(new Button("MC"), 0, 0);pane.add(bt7, 1, 0);pane.add(bt8, 2, 0);pane.add(bt9, 3, 0);pane.add(btDivide, 4, 0);pane.add(btSqrt, 5, 0);pane.add(new Button("MR"), 0, 1);pane.add(bt4, 1, 1);pane.add(bt5, 2, 1);pane.add(bt6, 3, 1);pane.add(btMultiply, 4, 1);pane.add(btRemainder, 5, 1);pane.add(new Button("MS"), 0, 2);pane.add(bt1, 1, 2);pane.add(bt2, 2, 2);pane.add(bt3, 3, 2);pane.add(btSubtract, 4, 2);pane.add(new Button("1/x"), 5, 2);pane.add(new Button("M+"), 0, 3);pane.add(bt0, 1, 3);pane.add(new Button("+/-"), 2, 3);pane.add(btDecimal, 3, 3);pane.add(btAdd, 4, 3);pane.add(btEqual, 5, 3);HBox hBox = new HBox(5);hBox.getChildren().addAll(new Button("Back"), new Button("CE"), new Button("C"));hBox.setAlignment(Pos.BASELINE_RIGHT);VBox vBox = new VBox(5);vBox.getChildren().addAll(tf, hBox, pane);// Create a scene and place it in the stageScene scene = new Scene(vBox, paneWidth, paneHeight);primaryStage.setTitle("Exercise16_05"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stage}/*** The main method is only needed for the IDE with limited* JavaFX support. Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}16.6import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import bel;import javafx.scene.control.RadioButton;import javafx.scene.control.TextField;。
Java程序设计基础习题答案
Java程序设计基础习题答案Java程序设计基础课后习题参考答案第2章1. 关于Java Application 的入口方法main()的检验:main()方法的参数名是否可以改变?main()方法的参数个数是否可以改变?该方法名是否可以改变?参考答案:(1)main()方法的参数名可以改变。
(2)main()方法的参数个数不可以改变。
(3)该方法名不可以改变。
2. 当一个程序没有main()方法时,能编译吗?如果能编译,能运行吗?参考答案:当一个程序没有main()方法是,是可以编译通过的,但是不能给运行,因为找不到一个主函数入口。
3. 下列语句能否编译通过?byte i = 127;byte j = 128;long l1 = 999999;long l2 = 9999999999;参考答案:byte i 和long l1可以编译通过。
而byte j 和long l2 超出自身数据类型范围,所以编译失败。
4. 下列语句能否编译通过?float f1 = 3.5;float f2 = 3.5f;参考答案:java中浮点型的数据在不声明的情况下都是double型的,如果要表示一个数据是float型的,必须在数据后面加上“F”或“f”;因此,float f1 无法编译通过。
5. 验证int 和char,int和double等类型是否可以相互转换。
参考答案:(1)char类型可以转换为int 类型的,但是int类型无法转换为char类型的;(2)int 可以转换为double类型的,但是double类型无法转换为int 类型的。
6. 计算下列表达式,注意观察运算符优先级规则。
若有表达式是非法表达式,则指出不合法之处且进行解释。
(1) 4+5 == 6*2 (2) (4=5)/6(3) 9%2*7/3>17 (4) (4+5)<=6/3(5) 4+5%3!=7-2 (6) 4+5/6>=10%2参考答案:表达式(2)为不合法表达式,只能将值赋值给一个变量,因此其中(4=5)将5赋值给4是不合法的。
JAVA语言程序设计(基础篇)答案
3.4import javax.swing.*;public class AdditionTutor{public static void main(String[] args){int number1=(int)(System.currentTimeMillis()%100);int number2=(int)(System.currentTimeMillis()*5%100);String answerString=JOptionPane.showInputDialog("what is "+ number1 +"+ "+ number2+" ?");int answer=Integer.parseInt(answerString);JOptionPane.showMessageDialog(null,number1 +" + "+ number2 +" = "+answer+" is "+(number1+number2==answer));}}3.10import javax.swing.JOptionPane;public class ComputeTaxWithSelectionStatement{public static void main(String[] args){//Prompt the user to enter filing statusString statusString = JOptionPane.showInputDialog("Enter the filing status:\n"+"(0-single filer,1-married jointly,\n"+"2-married separately,3-head of household)");int status = Integer.parseInt(statusString);//Prompt the user to enter taxable incomeString incomeString = JOptionPane.showInputDialog("Enter the taxable income:");double income = Double.parseDouble(incomeString);//Comput taxdouble tax=0;if (status == 0){//Compute tax for single filersif (income <= 6000)tax = income * 0.10;else if (income <= 27950)tax = 6000 * 0.10 + (income - 6000) * 0.15;else if (income <= 67700)tax = 6000 * 0.10 + (27950 - 6000) * 0.15 +(income - 27950) * 0.27;else if (income <= 141250)tax = 6000 * 0.10 + (27950 - 6000) * 0.15 +(67700 - 27950) * 0.27 + (income - 67700) * 0.30;else if (income <=307050)tax = 6000 * 0.10 + (27950 - 6000) * 0.15 +(67700 - 27950) * 0.27 + (141250 - 67700) * 0.30 +(income - 141250) * 0.35;elsetax = 6000 * 0.10 + (27950 - 6000) * 0.15 +(67700 - 27950) * 0.27 + (141250 -67700) * 0.30 +(307050 - 141250) * 0.35 + (income - 307050) * 0.386;}else if (status == 1){//Compute tax for married file jointly if (income <= 12000)tax = income * 0.10;else if (income <= 46700)tax = 12000 * 0.10 + (income - 12000) * 0.15;else if (income <= 112850)tax = 12000 * 0.10 + (46700 - 12000) * 0.15 +(income - 46700) * 0.27;else if (income <= 171950)tax = 12000 * 0.10 + (46700 - 12000) * 0.15 +(112850 - 46700) * 0.27 + (income - 112850) * 0.30;else if (income <= 307050)tax = 12000 * 0.10 + (46700 - 12000) * 0.15 +(112850 - 46700) * 0.27 + (141250 - 112850) * 0.30 +(income - 307050) * 0.35;elsetax = 12000 * 0.10 + (46700 - 12000) * 0.15 +(112850 - 46700 ) * 0.27 + (171950 - 112850) * 0.30 +(307050 - 171950) * 0.35 + (income - 307050) * 0.386;}else if (status == 2){//Compute tax for married separately if (income <= 6000)tax = income * 0.10;else if (income <= 23350)tax = 6000 * 0.10 + (income - 6000) * 0.15;else if (income <= 56425)tax = 6000 * 0.10 + (23350 - 6000) * 0.15 +(income - 23350) * 0.27;else if (income <= 85975)tax = 6000 * 0.10 + (23350 - 6000) * 0.15 +(56425 - 23350) * 0.27 + (income - 56425) * 0.30;else if (income <= 153525)tax = 6000 * 0.10 + (23350 - 6000) * 0.15 +(56425 - 23350) * 0.27 + (85975 - 56425) * 0.30 +(income - 85975) * 0.35;elsetax = 6000 * 0.10 + (23350 - 6000) * 0.15 +(56425 - 23350) * 0.27 + (85975 - 56425) * 0.30 +(153525 - 85975) * 0.35 + (income - 153525) * 0.386;}else if (status == 3){//Compute tax for head of householdif (income <= 10000)tax = income * 0.10;else if (income <= 37450)tax = 10000 * 0.10 + (income - 10000) * 0.15;else if (income <= 96700)tax = 10000 * 0.10 + (37450 - 10000) * 0.15 +(income - 37450) * 0.27;else if (income <= 156600)tax = 10000 * 0.10 + (37450 - 10000) * 0.15 +(96700 - 37450) * 0.27 + (income - 96700) * 0.30;else if (income <= 307050)tax = 10000 * 0.10 + (37450 - 10000) * 0.15 +(96700 - 37450) * 0.27 + (156600 - 96700) * 0.30 +(income - 156600) * 0.35;elsetax = 10000 * 0.10 + (37450 - 10000) * 0.15 +(96700 - 37450) * 0.27 + (156600 - 96700) * 0.30 +(307050 - 156600) * 0.35 + (income - 307050) * 0.386;}else{System.out.println("Error: invalid status");System.exit(0);}//Display the resultJOptionPane.showMessageDialog(null,"Tax is " +(int)(tax * 100) / 100.0);}}4.11public class ZhengChu{public static void main(String[] args){int count=0;for(int i=100;i<=200;i++){if((i%5==0||i%6==0)&&i%30!=0){System.out.print(" "+ i);count++;if(count%10==0)System.out.println();}}}}4.14public class ASCII{public static void main(String[] args){int count = 0;for(int i = 33; i <= 126; i++){count++;char ch = (char)i;System.out.print(" " + ch);if(count % 10 == 0)System.out.println();}}}4.17import javax.swing.JOptionPane;public class FindSalesAmount{/**Main method*/public static void main(String[] args){//The commission soughtString COMMISSION_SOUGHTString = JOptionPane.showInputDialog("Enter the COMMISSION_SOUGHT :");double COMMISSION_SOUGHT = Double.parseDouble(COMMISSION_SOUGHTString);double commission = 0;double salesAmount;for (salesAmount = 0.01;commission <= COMMISSION_SOUGHT;){salesAmount += 0.01; //防止犯off-by-one错误,先判断在做自加!if (salesAmount >= 10000.01)commission =5000 * 0.08 + 5000 * 0.1 + (salesAmount - 10000) * 0.12;else if (salesAmount >= 5000.01)commission = 5000 * 0.08 + (salesAmount - 5000) * 0.10;elsecommission = salesAmount * 0.08;}String output ="The sales amount $" + (int)(salesAmount * 100) / 100.0 +"\n is needed to make a commission of $" + COMMISSION_SOUGHT;JOptionPane.showMessageDialog(null,output);}}5.6import javax.swing.JOptionPane;public class PrintPyramid{public static void main(String[] args){String input = JOptionPane.showInputDialog("Enter the number of lines:");int numberOfLines = Integer.parseInt(input);displayPattern(numberOfLines);}public static void displayPattern(int n){for (int row = 1;row <= n;row++){for (int column = 1;column <= n - row;column++)System.out.print(" ");for (int num = row;num >= 1;num--)System.out.print((num >= 10) ? " " + num : " " + num);System.out.println();}}}5.18public class MathSuanFa{public static void main(String[] args){double A = Math.sqrt(4);double B = (int)Math.sin(2 * Math.PI);double C = (int)Math.cos(2 * Math.PI);double D = (int)Math.pow(2, 2);double E = (int)Math.log(Math.E);double F = (int)(Math.exp(1)*100000)/100000.0;double G = (int)Math.max(2, Math.min(3, 4));double H = (int)Math.rint(-2.5);double I = (int)Math.ceil(-2.5);double J = (int)Math.floor(-2.5);int K = (int)Math.round(-2.5f);int L = (int)Math.round(-2.5);double M = (int)Math.rint(2.5);double N = (int)Math.ceil(2.5);double O = (int)Math.floor(2.5);int P = (int)Math.round(2.5f);int Q = (int)Math.round(2.5);int R = (int)Math.round(Math.abs(-2.5));System.out.println(A +" "+ B +" "+ C +" "+ D +" "+ E +" "+ F +" "+ G +" "+ H +" "+ I +" "+ J +" "+ K +" "+ L +" "+ M +" "+ N +" "+ O +" "+ P +" "+ Q +" "+ R);}}6.9import javax.swing.JOptionPane;public class Array{public static void main (String[] args){String incomeString = JOptionPane.showInputDialog("Enter the number of array size:");int income = Integer.parseInt(incomeString);int arraySize = income;int [] myList = new int [arraySize];int m;for ( m = 0; m < arraySize; m++){String elementString = JOptionPane.showInputDialog("Enter the " + (m + 1) + " element of the array");int element = Integer.parseInt(elementString);myList[m] = element;}int minElement = myList[0];for (int i=1; i < arraySize; i++){if (myList[i] < minElement)minElement = myList[i];}JOptionPane.showMessageDialog(null,"The min element is: " + minElement); }}。
普通高等教育十一五国家级规划教材《JAVA程序设计》课后习题答案大全
}
public void set(int length,int width){
this.length=length;
this.width=width;
}
public void get(){
System.out.println("此长方形的长为"+length+"宽为"+width);
{
Rect A=new Rect();
A.set(20,30);
A.get();
A.area();
A.crea();
}
}
3.运行结果:
五.问答题
1. 答:
Java中使用static修饰的变量和方法称为类变量(或称静态变量)和类方法(或称静态方法),没用static修饰符的变量和方法称为实例变量和实例方法。
BufferedReader n;
year=new InputStreamReader(System.in);
n=new BufferedReader(year);
System.out.print("请输入一年份:");
String s=n.readLine();
int leapyear=Integer.parseInt(s);//把输入的字符串转换成整型
if(leapyear%4==0 && leapyear%100!=0 || leapyear%400==0)
System.out.print(leapyear+"年是闰年!");
else
System.out.print(leapyear+"年不是闰年!");
《Java语言程序设计-基础篇》答案-第16章
16.30 答:略
16.31 答:否,要求其数据域成员全部是可序列化的或使用 transient 忽略不可序列化 的成员。 静态成员不进行序列化。
16.32 答:可以。前提是数据元素是可序列化的。
16.33 答:否。
.com 16.34 答:发生 java.io.NotSerializableException。 daw 16.35 答:可以。
m 16.2 答:分别使用 File 类的如下方法完成相应操作: co (1)public boolean exists() w. 测试此抽象路径名表示的文件或目录是否存在。 a 返回:当且仅当此抽象路径名表示的文件或目录存在时,返回 true;否 hd 则返回 false .k (2)public boolean delete() www 删除此抽象路径名表示的文件或目录。如果此路径名表示一个目录,则
该始终检查返回值,以确保重命名操作成功。 参数:dest - 指定文件的新抽象路径名 返回:当且仅当重命名成功时,返回 true;否则返回 false (4)public long length() 返回由此抽象路径名表示的文件的长度。如果此路径名表示一个目录, 则返回值是不确定的。 返回:此抽象路径名表示的文件的长度,以字节为单位;如果文件不存
kh 不能直接读写对象。 www. 16.36 答:略。 网 16.37 答:输出:IO Exception
案 答 后 课
该目录必须为空才能删除。
网 返回:当且仅当成功删除文件或目录时,返回 true;否则返回 false 案 (3)public boolean renameTo(File dest与平台有关的:重命名操作无法将一个文件 后 从一个文件系统移动到另一个文件系统,该操作不是不可分的,如果已 课经存在具有目标抽象路径名的文件,那么该操作可能无法获得成功。应
Java语言程序设计基础篇课后答案-机械工业出版社[资料]
Java语言程序设计基础篇课后答案-机械工业出版社Java语言程序设计1 / 81&[编程练习题答案]Java语言程序设计(基础篇)(进阶篇)第13、14、15、24、25、26、28、29、30、31章部分习题答案,奇数题和部分双数题是我自己做的,在此和大家分享(^_^~Chapter 13 Exercise 13.2 / 13.8 / 13.11import javax.swing.*;import java.awt.*;public class Exercise13_2 extends JFrame {// Create two buttonsprivate OvalButton jbtOk = new OvalButton("OK");private OvalButton jbtCancel = new OvalButton("Cancel");/** Default constructor */public Exercise13_2() {// Set the window titlesetTitle("Exercise13_2");// Set FlowLayout manager to arrange the componentsJava语言程序设计2 / 81// inside the framegetContentPane().setLayout(new FlowLayout());// Add buttons to the framegetContentPane().add(jbtOk);getContentPane().add(jbtCancel);}/** Main method */public static void main(String[] args) {Exercise13_2 frame = new Exercise13_2();frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.pack();frame.setVisible(true);}}class OvalButton extends JButton {public OvalButton() {}public OvalButton(String text) {super(text);}protected void paintComponent(Graphics g) {// Draw an ovalsuper.paintComponent(g);g.drawOval(5, 5, getWidth() - 10, getHeight() - 10); }/** Override get method for preferredSize */public Dimension getPreferredSize() {return new Dimension(100, 50);}/** Override get method for minimumSize */public Dimension getMinimumSize() {return new Dimension(100, 50);}}Java语言程序设计3 / 81import java.awt.*;import javax.swing.*;public class Exercise13_8 extends JFrame {public static void main(String[] args) {JFrame frame = new Exercise13_8();frame.setSize(300, 300);frame.setTitle("Exercise13_8");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);}public Exercise13_8() {getContentPane().add(new OctagonPanel());}}class OctagonPanel extends JPanel {protected void paintComponent(Graphics g) {super.paintComponent(g);int xCenter = getWidth() / 2;int yCenter = getHeight() / 2;int radius =(int) (Math.min(getWidth(), getHeight()) * 0.4);// Create a Polygon objectPolygon polygon = new Polygon();// Add points to the polygonpolygon.addPoint(xCenter + radius, yCenter);polygon.addPoint((int)(xCenter + radius * Math.cos(2 *Math.PI / 8)),(int)(yCenter - radius * Math.sin(2 * Math.PI / 8)));polygon.addPoint((int)(xCenter + radius * Math.cos(2 * 2 * Math.PIJava语言程序设计4 / 81/ 8)),(int)(yCenter - radius * Math.sin(2 * 2 * Math.PI / 8)));polygon.addPoint((int)(xCenter + radius * Math.cos(3 * 2 * Math.PI/ 8)),(int)(yCenter - radius * Math.sin(3 * 2 * Math.PI / 8)));polygon.addPoint((int)(xCenter + radius * Math.cos(4 * 2 * Math.PI/ 8)),(int)(yCenter - radius * Math.sin(4 * 2 * Math.PI / 8)));polygon.addPoint((int)(xCenter + radius * Math.cos(5 * 2 * Math.PI/ 8)),(int)(yCenter - radius * Math.sin(5 * 2 * Math.PI / 8)));polygon.addPoint((int)(xCenter + radius * Math.cos(6 * 2 * Math.PI/ 8)),(int)(yCenter - radius * Math.sin(6 * 2 * Math.PI / 8))); polygon.addPoint((int)(xCenter + radius * Math.cos(7 * 2* Math.PI/ 8)),(int)(yCenter - radius * Math.sin(7 * 2 * Math.PI / 8)));// Draw the polygong.drawPolygon(polygon);}}import javax.swing.*;import java.awt.*;public class Exercise13_11 extends JFrame {public Exercise13_11(){add(new SquareFunction());}/*** @param args*/public static void main(String[] args) {Java语言程序设计5 / 81// TODO 自动生成方法存根Exercise13_11 frame = new Exercise13_11();frame.setTitle("Exercise13.11");frame.setSize(300,200);frame.setLocationRelativeTo(null);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);}}class SquareFunction extends JPanel {public SquareFunction(){}protected void paintComponent(Graphics g){super.paintComponent(g);g.drawLine(10, this.getHeight()-20, this.getWidth()-10,this.getHeight()-20);g.drawLine(this.getWidth()-30, this.getHeight()-15,this.getWidth()-10, this.getHeight()-20);g.drawLine(this.getWidth()-30, this.getHeight()-25,this.getWidth()-10, this.getHeight()-20);g.drawString("X", this.getWidth()-10,this.getHeight()-30);g.drawLine(this.getWidth()/2, 20, this.getWidth()/2,this.getHeight()-5);g.drawLine(this.getWidth()/2, 20, this.getWidth()/2-5,35);g.drawLine(this.getWidth()/2, 20, this.getWidth()/2+5,35);g.drawString("Y", this.getWidth()/2 + 10, 30);Polygon p = new Polygon();double scaleFactor = 0.01;for (int x=-100; x<=100; x++){p.addPoint(x+this.getWidth()/2,this.getHeight()-20-(int)(scaleFactor*x*x));}g.drawPolyline(p.xpoints, p.ypoints, p.npoints);}}Java语言程序设计6 / 81Chapter 14 Exercise 14.4 / 14.8 / 14.9package chapter14;import javax.swing.*;import java.awt.event.*;import java.awt.*;public class Exercise14_4 extends JFrame {public Exercise14_4(){MousePosition p = new MousePosition();add(p);}/*** @param args*/public static void main(String[] args) {// TODO 自动生成方法存根Exercise14_4 frame = new Exercise14_4();frame.setTitle("Exercise14.4");frame.setSize(300, 200);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setLocationRelativeTo(null);frame.setVisible(true);}static class MousePosi。
自考04747《Java语言程序设计(一)》课后习题答案全集
第一章 Java语言基础 (5)1.1 指出JA V A语言的主要特点和JA V A程序的执行过程。
(5)1.2 说出开发与运行JA V A程序的重要步骤。
(5)1.3 如何区分应用程序和小应用程序? (5)1.4 说出JA V A源文件的命名规则。
(5)1.6 JA V A语言使用什么字符集?共有多少个不同的字符? (5)1.7 JA V A语言标识符的命名规则是什么? (6)1.8 JA V A有那些基本数据类型,它们的常量又是如何书写的? (6)1.9 指出下列内容哪些是JA V A语言的整型常量,哪些是浮点数类型常量,哪些两者都不是。
(6)第二章运算和语句 (7)2.1 Java的字符能参加算术运算吗? (7)2.2 占字节多的变量能直接赋值给占字节少的变量么? (7)2.3 试用Java语言表达式描述以下数学计算式或逻辑条件: (7)2.4 设在求以下表达式之前,整型变量a的值是4,试指出在求了以下表达式之后,变量a、b和c的值。
(7)2.6 若一个数恰好等于它的因子之和,则这个数称为“完全数”。
编写程序求1000之内的所有完全数。
(7)2.7 编写输入正实数x,求平方不超过x的最大整数n,并输出。
(8)2.8 输入正整数n,输出由n行n列星号字符组成的三角形图案。
(11)2.9 设有整型变量x和y的值分别为5和110。
试指出执行了以下循环语句后,变量x和y的值分别多少? (12)2.10求小于999的所有水仙花数。
(12)2.11 编程序解百鸡问题:鸡翁一,值钱五;鸡母一,值钱三;鸡雏三,值钱一。
百钱买百鸡。
求鸡翁、鸡母和鸡雏各几何? (13)2.12 编写程序,按下面的公式计算自然对数底e的值:e=1+1/1!+1/2!+1/3!+1/4!+...... (13)2.13 编写程序,用如下公式计算圆周率PI的近似值:PI=4-4/3+4/5-4/7+4/9-4/11... (14)2.14 回文整数是指正读法和反读相同的整数,编写一个程序,输入一个整数,判断他是否为回文整数。
《Java语言程序设计基础教程》习题解答
《Java语言程序设计基础教程》练习思考题参考答案数据结构(C++版) 22第1章 Java程序设计概述1.9 练习思考题1、Java运行平台包括三个版本,请选择正确的三项:()A. J2EEB. J2MEC. J2SED. J2E解答:A,B,C2、Java JDK中反编译工具是:()A. javacB. javaC. jdbD. javap解答:D3、public static void main方法的参数描述是:()A. String args[]B. String[] argsC. Strings args[]D. String args解答:A,B4、在Java中,关于CLASSPATH环境变量的说法不正确的是:()A. CLASSPATH一旦设置之后不可修改,但可以将目录添加到该环境变量中。
B. 编译器用它来搜索各自的类文件。
C. CLASSPATH是一个目录列表。
D. 解释器用它来搜索各自的类文件。
解答:A5、编译Java Application源文件将产生相应的字节码文件,扩展名为()A. .javaB. .classC. .htmlD. .exe解答:B6、开发与运行Java程序需要经过的三个主要步骤为____________、____________和____________。
7、如果一个Java Applet源程序文件只定义有一个类,该类的类名为MyApplet,则类MyApplet必须是______类的子类并且存储该源程序文件的文件名为______。
8、如果一个Java Applet程序文件中定义有3个类,则使用Sun公司的JDK编译器编译该源程序文件将产生______个文件名与类名相同而扩展名为______的字节码文件。
9、开发与运行Java程序需要经过哪些主要步骤和过程?10、Java程序是由什么组成的?一个程序中必须要有public类吗?Java源文件的命名规则是怎么样的?11、编写一个简单的Java应用程序,该程序在命令行窗口输出两行文字:“你好,很高兴学习Java”和“We are students”。
Java语言程序设计课后习题答案全集
《J a v a语言程序设计(一)》课后习题答案全集(总55页)--本页仅作为文档封面,使用时请直接删除即可----内页可以根据需求调整合适字体及大小--指出JAVA语言的主要特点和JAVA程序的执行过程。
答:(1)强类型;(2)编译和解释;(3)自动无用内存回收功能;(4)面向对象;(5)与平台无关;(6)安全性;(7)分布式计算;(8)多线程;程序执行过程如图所示:编写源文件,编译器编译源文件转换成字节码,解释器执行字节码。
说出开发与运行JAVA程序的重要步骤。
答:(1)编写源文件:使用一个文本编译器,如Edit或记事本,不可以使用Word.将编好的源文件保存起来,源文件的扩展名必须是.java;(2)编译Java源文件:使用Java编译器编译源文件得到字节码文件;(3)运行Java程序:Java程序分为两类——Java应用程序必须通过Java解释器来解释执行其字节码文件;Java小应用程序必须通过支持Java标准的浏览器来解释执行。
如何区分应用程序和小应用程序答:应用程序在与源文件名字相同的类中,有main()方法,该方法代表应用程序的入口; 小应用程序必须有一个Applet类的子类,该类称作主类,必须用public修饰。
说出JAVA源文件的命名规则。
答:源文件命名规则和类命名规则一样,所有的单词首字母都用大写字母,且必须和源文件的public类同名。
JAVA语言使用什么字符集共有多少个不同的字符答:Java语言使用Unicode字符集,共有65535个字符。
JAVA语言标识符的命名规则是什么(1)由字母(包括英文字母、下划线字符、美元字符、文字字符)和数字字符组成(2)限定标识符的第一个字符不能是数字字符(3)不能和关键字重名(4)长度不能超过255个字符JAVA有那些基本数据类型,它们的常量又是如何书写的指出下列内容哪些是JAVA语言的整型常量,哪些是浮点数类型常量,哪些两者都不是。
整型常量: 4)0xABCL,8)003,10)077,12)056L浮点数类型常量:3)-1E-31,5).32E31 13)0.,14).0两者都不是: 1),2),6),7),9),11)第二章 运算和语句Java 的字符能参加算术运算吗可以。
Java程序设计基础习题答案
Java程序设计基础习题答案第1章1选择题(1)BCD (2)D (3)CD (4)CD第2章1、错误:-0x3221 fa00 8.33E e-10整数:1856 4l 021 0xa6 0xa2e3 35 -78999 0L浮点数:0x3.45 -3.81 1.34e-8 -.67e3 25. 053.249 -1E3八进制数:053.249 021十六进制数:0xa6 0x3.45 0xa2e32、正确的标识符:_book, book3, _9days, I, copy_file, _56, up_down, if_count, agentEventListener 错误的标识符:int, println, static, a$, 5files, -number, date:x, +digit, $abcd,3、(1)int i改为static int i。
(2)j=i 改为j=(short)i。
(3)i为数组,应该改为int i[] = new int[10]。
同时后面也要做相应修改。
(4)将k=i&j改为k= (Boolean)i&j。
4、x=10, y=6, z=false(1)false(2)x=16(3)true(4)x=60(5)6(6)6(7)true(8)false5、x=5, y=7, z=0(1)35(2)-1(3)6(4)13(5)36、(1)x>=y?10:3 y%=(2)x<10 i>6 j==5 && || y=(3)b+c +d a-=(4)a<b ||x &y第3章1、选择题(1)C (2)B (3)无答案,全部正确,不过A for(;;);t选项是个死循环,但不存在语法错误(4)C (5)A (6)B2、(1)全部为0(2)m=34 0到99所有被3整除的数N=15 0到99所有被7整除的数3、(1)char ch =0;try{System.out.println("please input:");ch = (char)System.in.read();} catch(Exception e){e.printStackTrace();}switch(ch) {case 'L':System.out.println("Left");break;case 'R':System.out.println("Right");break;default:System.out.println("Not Known");}(2)int i =1, n=0;for(n=11;n<0;n--)i =i*n;(3)int i =1, n=0;i=1;n=0;for(i=1;i<11;i++)System.out.println("number: " + i +" sum: " + (n=n+i)); (4)int n=4,i=0, j=0;int a[][] = new int[n][n];for(i=0;i<n;i++)for(j=0;j<n;j++)if (i==j)a[i][j] = 1;elsea[i][j] = 0;第4章1选择题(1)D (2)B (3)C (4)B (5)AC (6)C 2判断题m in main = aa in main = 4return from testV ar2 : a in testV ar3 is 547554m+a= 603、编程题(1)public class abc {public abc() {} int factorial(int x) {int rst =1;for(int i=1;i<=x;i++)rst *= i;return rst;}void printf(int x, int rst) {System.out.println(x+"的阶乘是: " +rst);}public static void main(String args[]) {int i =0;abc myabc = new abc();myabc.printf(6,myabc.factorial(6));myabc.printf(9,myabc.factorial(9));}}(2)int factorial(int x) {if (x <1) return 0;else {if(x==1) return 1;elsereturn x*factorial(x-1);}}第5章1、选择题(1)B (2)D (3) A (4)A (5)C (6)A (7)A (8)C (9)D (10)D2、运行结果:X=130, y=45X+y=175x-y=95x*y=5850x/y=2.888888888888889更改后的两个类:class Excer{public static void main(String[] args) {new Excer().math();}int x=130, y=45;Math myMath = new Math();System.out.println("x="+x+" , y="+y);System.out.println("x+y=" + myMath.plus(x,y));System.out.println("x-y=" + myMath.minus(x,y));System.out.println("x*y=" + myMath.multi(x,y));System.out.println("x/y=" + myMath.div(x,y));}}class Math {int plus(int a, int b) {return a+b;}int minus(int a, int b) {return a-b;}int multi(int a, int b) {return a*b;}float div(int a, int b) {return((float)a/b);}}3、编程题(1)class PlayCard {private Poker poker;public PlayCard() {poker = new Poker();}public String play() {int i=0,j=0;java.util.Random ab = new java.util.Random();i = ab.nextInt(13);j = ab.nextInt(4);return (poker.nums[i] + " of " + poker.colors[j]); }public String play(int x, int y) {return (poker.nums[x] + " of " + poker.colors[y]); }}(2)class Poker {public String nums[];public String colors[];nums = new String[13];colors = new String[4];nums[0] = "Ace";nums[1] = "Two";nums[2] = "Three";nums[3] = "Four";nums[4] = "Five";nums[5] = "Six";nums[6] = "Seven";nums[7] = "Eight";nums[8] = "Nine";nums[9] = "Ten";nums[10] = "Jack";nums[11] = "Queen";nums[12] = "King";colors[0] = "Diamonds";colors[1] = "Clubs";colors[2] = "Hearts";colors[3] = "Spades";}}(3)public static void main(String args[]) {PlayCard pcard = new PlayCard();for(int i=0;i<13;i++)for(int j=0;j<4;j++)System.out.println(pcard.play(i,j));}第6章1、选择题(1)B (2)B (3)C (4)B (5)D (6)C (7)AB (8)BC2、阅读程序(1)methodFour覆盖了父类的方法(2)mehtodTwo重载了父类的方法(3)6个以上,其中本身4个方法,从ClassA继承了2个方法methodOne,和static methodThree,从Object类继承了几个方法,如Equal等。
《Java语言程序设计:基础篇》课后复习题答案-第十六章
Chapter16Event-Driven Programming1.A WindowEvent is generated by an instance of the Window class or its subclass.JButton is not a subclass of Window,therefore,it cannot generate theWindowEvent.JButton can generate MouseEvent and ActionEvent.2.A listener must have a correct method to handle the event.To ensure that alistener have the method,a listener must be an instance of a listener interface,where a method is defined.To register a listener object,you invoke the source object's add X Listener's method;for example,button.AddActionListener(this).To implement a listener interface,you add implements X listener and implement all the handlers in the listener'sobject.3.Yes.Yes.Yes.4.To override a method defined in the listener interface,you provide the code in thebody of the method for handling the event.You need to override all the methodsdefined in the listener interface.If a handler is not used in the program,you can giveit an empty body.5.Objects of an inner class are often created in the outerclass.But you can also create an object of an inner classfrom another class.If the inner class is nonstatic,youmust first create an instance of the outer class,then usethe following syntax to create an object for the innerclass:OuterClass.InnerClass innerObject=outerObject.new InnerClass();If the inner class is static,use the following syntax tocreate an object for it:OuterClass.InnerClass innerObject=new OuterClass.InnerClass();6.Yes.7.If class A is an inner class in class B,the.class filefor A is B$A.class.If class B contains two anonymousinner classes,the.class file names for these twoclasses are B$+1and B$+2.8.(a)1.java.awt.event package should be imported to use ActionEvent andActionListener in this program;2.java.swing should be javax.swing3.actionPerform should be actionPerformed;5.jbtOK is not in the scope of the actionPerformed method;5.no listener is registered with jbtOK.(b)missing)in Line;9.The setSize method specifies the width and height of a frame,whereas the packmethod let the JVM automatically sets the size for the frame according to the size of the components in the frame.e getSource()in the EventObject class to get the source of an egetWhen()in the ActionEvent class to get the timestamp for an action event,usegetWhen()in the InputEvent class to get the timestamp a mouse event or a keye getPoint(),or getX()and getY()to get the mouse point position for amouse e getKeyChar()to get the key character for a key event.11.The listener interface for move pressed,released,clicked,entered,and exited isMouseListener.The listener interface for mouse moved and dragged isMouseMotionListener.12.Not every key in the keyboard has a Unicode.For example,the function keys,modifier keys,action keys,and control keys are not Unicode characters.Thekey code in the KeyEvent class are defined asconstants.Their value is the same as the Unicodevalue if the key is Unicode character.13.The keyPressed handler is invoked after a key is pressed.The keyReleased handler is invoked after a key is released.The keyTyped handler invoked after a Unicode character key is typed.14.You create a timer using the constructorpublic Timer(int delay,ActionListener listener)Use the start method to start the timer,and the stop method to stop the timer.15.The Timer class does not have a no-arg constructor.You can add multiplelisteners by invoking the timer.addActionListener(listener).。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Chapter 16 Applets and Multimedia
1. Every applet is an instance of java.awt.Applet. Not every applet is an instance of
javax.swing.JApplet. Only the Swing applets are instances of JApplet.
2. See the section "The Applet Class."
3. The components are added to the content pane of the applets. The default layout
manager of the content pane of JApplet is BorderLayout.
4. (a) The void should be removed to declare a constructor.
(b) The jlblMessage is declared in Line 2 as a data field, but redeclared in Line 5
as a local variable. The local variable is assigned with new JLabel("It is Java"),
but the data field is still null. In Line 12, jlblMessage is null, which causes
NullPointerException.
5. See the section "The <applet> HTML Tag." You use the <param> tag to pass
parameters to an applet.
getParameter() method is defined in the Applet class.
6. The
7. Revision 1 is wrong because the getParameter method is an instance method and
it cannot be invoked before an instance of the applet is created. Revision 2 is
wrong because the init method is invoked after the applet instance is created.
8.An application has a main() method and runs as a
standalone. An applet does not need a main method and
must run from a Web browser. Applications and applets are
compiled in the same way.
Applets are not allowed to read from, or write to, the file system of the computer.
Applets are not allowed to run any programs on the browser's computer. Applets
are not allowed to establish connections between the user's computer and another
computer except with the server where the applets are stored.
9. No.
10. Yes. You can create an instance of JApplet and place it in a frame and use it.
11. You will see garbage displayed in the cell.
12. To create an URL object for the file /liang/anthem/us.mid on the
Internet, use new URL(“/liang/anthem/us.mid”). To create an
URL object for the file anthem/us.mid, use
URL url = this.getClass().getResource(filename);
13. First create an URL for the image source, then use new ImageIcon(url) to create
an ImageIcon for the source.
14. You can use AIFF, MIDI, and RMF in addition to AU and WAS files in Java 2.
15. First create an URL for the audio source, then use the Applet.getAudioClip(url)
method to obtain an audio clip.
16. You can use the play(), stop(), and loop() methods to play, stop, or
repeatedly play the audio, respectively.。