《Java语言程序设计(基础篇)》(第10版 梁勇 著)第三十五章练习题答案

合集下载

java语言程序设计基础篇 复习题答案

java语言程序设计基础篇 复习题答案

java语言程序设计基础篇复习题答案Java语言程序设计基础篇复习题答案Java语言是一种广泛应用于软件开发领域的高级编程语言,具有跨平台、面向对象、简单易学等特点。

在学习Java语言的过程中,复习题是一种非常有效的巩固知识的方式。

本文将为大家提供一些Java语言程序设计基础篇的复习题答案,希望能够帮助大家更好地理解和掌握Java语言。

1. 以下代码的输出结果是什么?```javapublic class Test {public static void main(String[] args) {int x = 5;int y = 10;System.out.println("x + y = " + (x + y));System.out.println("x - y = " + (x - y));System.out.println("x * y = " + (x * y));System.out.println("x / y = " + (x / y));}}```答案:```x + y = 15x - y = -5x * y = 50x / y = 0```2. 以下代码的输出结果是什么?```javapublic class Test {public static void main(String[] args) { int x = 5;int y = 10;boolean result = (x > y) && (x != y); System.out.println(result);}}```答案:```false```3. 以下代码的输出结果是什么?```javapublic class Test {public static void main(String[] args) {int x = 5;int y = 10;boolean result = (x < y) || (x == y);System.out.println(result);}}```答案:```true```4. 以下代码的输出结果是什么?```javapublic class Test {public static void main(String[] args) {int x = 5;int y = 10;if (x > y) {System.out.println("x is greater than y"); } else if (x < y) {System.out.println("x is less than y");} else {System.out.println("x is equal to y");}}}```答案:```x is less than y```5. 以下代码的输出结果是什么?```javapublic class Test {public static void main(String[] args) {int x = 5;int y = 10;int max = (x > y) ? x : y;System.out.println("The maximum value is: " + max); }}```答案:```The maximum value is: 10```通过以上复习题的答案,我们可以看到Java语言程序设计基础篇中的一些基本概念和语法。

java语言程序设计基础篇第十版课后答案

java语言程序设计基础篇第十版课后答案

第一章1.1public class Test{public static void main(String[]args){System.out.println("Welcome to Java!"); System.out.println("Welcome to Computer Science!");System.out.println("Progr amming is fun.");}}1.2public class Test{public static void main(String[]args){for(int i=0;i<=4;i++){System.out.println("Welcome to Java!");}}}1.3public class Test{public static void main(String[]args){System.out.println("]");System.out.printl n("]");System.out.println("]]");System.out.println("]]");}}public class Test{public static void main(String[]args){System.out.println("A"); System.out.println("A A");System.out.println("AAAAA");System.out.println("A A");}}public class Test{public static void main(String[]args){System.out.println("V V");System.out.println("V V");System.out.println("V V");System.out.println(" V");}}1.4public class Test{public static void main(String[]args){System.out.println("a a^2a^3");System.out.println("111");System.out.println("248");System.out.println("3 927");System.out.println("41664");}}1.5public class Test{public static void main(String[]args){System.out.println((9.5*4.5-2.5*3)/(45.5-3.5) );}}1.6public class Test{public static void main(String[]args){int i=1,sum=0;for(;i<=9;i++)sum+ =i;System.out.println(sum);}1.7public class Test{public static void main(String[]args){System.out.println(4*(1.0-1.0/3+1.0/5-1.0/7+1.0/9-1.0/11));System.out.println(4*(1.0-1.0/3+1.0/5-1.0/7+1.0/9-1.0/11+1.0/13));}}1.8public class Test{public static void main(String[]args){final double PI=3.14; double radius=5.5;System.out.println(2*radius*PI);System.out.println(PI*radius*radius);}}1.9public class Test{public static void main(String[]args){System.out.println(7.9*4.5);System.out.p rintln(2*(7.9+4.5));}}1.10public class Test{public static void main(String[]args){double S=14/1.6;double T=45*60+30;double speed=S/T;System.out.println(speed);}1.11public class Test{public static void main(String[]args){int BN=312032486; //original person numbers double EveryYS,EveryYBP,EveryYDP,EveryYMP;EveryY S=365*24*60*60;EveryYBP=EveryYS/7;EveryYDP=EveryYS/13;Every YMP=EveryYS/45;int FirstYP,SecondYP,ThirdYP,FourthYP,FivthYP;FirstYP=(int)(BN+EveryYBP+EveryYMP-EveryYDP);SecondYP=(int)(FirstYP +EveryYBP+EveryYMP-EveryYDP);ThirdYP=(int)(SecondYP+EveryYBP+Ev eryYMP-EveryYDP);FourthYP=(int)(ThirdYP+EveryYBP+EveryYMP-EveryYD P);FivthYP=(int)(FourthYP+EveryYBP+EveryYMP-EveryYDP);System.out.pri ntln(FirstYP);System.out.println(SecondYP);System.out.println(ThirdYP);Syste m.out.println(FourthYP);System.out.println(FivthYP);}}1.12public class Test{public static void main(String[]args){double S=24*1.6; double T=(1*60+40)*60+35;double speed=S/T;System.out.println(sp eed);}}1.13import java.util.Scanner;public class Test{public static void main(String[]args){Scanner input=new Scan ner(System.in);System.out.println("input a,b,c,d,e,f value please:");double a=input.nextDouble();double b=input.nextDouble();double c=input.nextDouble();double d=input. nextDouble();double e=input.nextDouble();第二章package cn.Testcx;import java.util.Scanner;public class lesson2{public static void main(String[]args){@SuppressWarnings("resource")Scanner in put=new Scanner(System.in);System.out.print("请输入一个摄氏温度:");double Celsius=input.nextDouble();double Fahrenheit=(9.0/5)*Celsius+3 2;System.out.println("摄氏温度:"+Celsius+"度"+"转换成华氏温度为:"+Fahrenheit+"度");System.out.print("请输入圆柱的半径和高:");double radius=input.nextDouble();int higth=input.nextInt();double are as=radius*radius*Math.PI;double volume=areas*higth;System.out.println("圆柱体的面积为:"+areas);System.out.println("圆柱体的体积为:"+volume);System.out.print("输入英尺数:");double feet=input.nextDouble();double meters=feet*0.305;System.out.print ln(feet+"英尺转换成米:"+meters);System.out.print("输入一个磅数:");double pounds=input.nextDouble();double kilograms=pounds*0.454;Syste m.out.println(pounds+"磅转换成千克为:"+kilograms);System.out.println("输入分钟数:");long minutes=input.nextInt();long years=minutes/(24*60*365);long days=(minutes%(24*60*365))/(24*60);System.out.println(minutes+"分钟"+"有"+years+"年和"+days+"天");long totalCurrentTimeMillis=System.currentTimeMillis();long totalSeconds=t otalCurrentTimeMillis/1000;long currentSeconds=totalSeconds%60;long totalM inutes=totalSeconds/60;long currentMinutes=(totalSeconds%(60*60))/60;long currenthours=(totalMinutes/60)%24;System.out.print("输入时区偏移量:");byte zoneOffset=input.nextByte();long currentHour=(currenthours+(zoneOf fset*1))%24;System.out.println("当期时区的时间为:"+currentHour+"时"+currentMinutes+"分"+currentSeconds+"秒");System.out.print("请输入v0,v1,t:");double v0=input.nextDouble();double v1=input.nextDouble();doublet=input.nextDouble();float a=(float)((v1-v0)/t);System.out.println("平均加速度a="+a);System.out.println("输入水的重量、初始温度、最终温度:");double water=input.nextDouble();double initialTemperature=input.nextDou ble();double finalTemperature=input.nextDouble();double Q=water*(finalTemp erature-initialTemperature)*4184;System.out.println("所需热量为:"+Q);System.out.print("输入年数:");int numbers=input.nextInt();long oneYearsSecond=365*24*60*60;Longpop ulation=(long)((312032486+((oneYearsSecond/7.0)+(oneYearsSecond/45.0)-(oneYearsSecond/13.0))*numbers));System.out.println("第"+numbers+"年后人口总数为:"+population);System.out.print("输入速度单位m/s和加速度a单位m/s2:");double v=input.nextDouble();double a1=input.nextDouble();double l engthOfAirplane=(Math.pow(v,2))/(2*a1);System.out.println("最短长度为:"+lengthOfAirplane);System.out.print("输入存入的钱:");double money=input.nextInt();double monthRate=5.0/1200;for(int i=1;i<7; i++){double total=money*(Math.pow(1+monthRate,i));System.out.println("第"+i+"个月的钱为:"+total);//告诉我书上的银行在哪里,我要去存钱,半年本金直接翻6倍、、、}System.out.print("用户请输入身高(英寸)、体重(磅):");double height=input.nextDouble();double weight=input.nextDouble(); double BMI=(weight*0.45359237)/(Math.pow((height*0.0254),2));System.out.println("BMI的值为"+BMI);System.out.print("输入x1和y1:");System.out.print("输入x2和y2:");double x1=input.nextDouble();double y1=input.nextDouble();double x2 =input.nextDouble();double y2=input.nextDouble();double point1=Math.pow((x2-x1),2);double point2=Math.pow((y2-y1),2);double distance=Math.pow((point1+point2),(1.0/2));//也可以Math.pow((point1+point2),0.5)System.out.println("两点间的距离为:"+distance);System.out.print("输入六边形的边长:");double side=input.nextDouble();double area=(3*(Math.pow(3,0.5))*(Math.p ow(side,2)))/2;System.out.println("六边形的面积为:"+area);}}。

java程序设计(雍俊海)课后部分标准答案

java程序设计(雍俊海)课后部分标准答案

第一章1 • 1谁是java语言创始人J a mes Gosli n g, J a va语言的创始人之一1.2j ava语言有哪些优缺点?P 2页(1)简单性(2)网络特性(3)面向对象性(4)平台无关性/可移植性(5)鲁棒性也指程序稳定性(6)安全性(7)多线程性,采用多线程机制是提高程序运行效率的方法,但增加了程序的设计难度(8)解释性,缺点,解释执行语言要不编译执行语言需要额外的语句解释不龙及运行时间。

1. 4请简述环境变相path和c 1 asspa t h作用环境变量运行路径(path)和类路径(classpath)1. 5java程序可以分为几种,分别是什么?两种,应用程序和小应用程序applt1. 6 査看j ava 在线帮助文档,列举岀system, o ut. pr i n tl n 和s ys t em. out. print 的不同点。

S y s t em. o u t. printin 自动换行,system, ou t . print 不自动换行。

1.7试着编写一个j ava程序,在控制台窗口中输岀如下信息。

Publ i c clas s TestPubli c sta t i c void m a in(strng args[]){ system, out. print In (M*** **** *次* **** *** ****");s ys t em. o ut・ pr i ntln(v ** p ra c ti c e makes pe r f e c t ,?):system・ ou t ・ p ri n tin ( ” ******* ***** ***** * **次”);}1.8编写一个j ava程序,在网页中显示如下信息。

import ja v a ・ a w t .Graph i cs;import javax. swing・ JAppl e t;p u b 1 i c c 1 ass J_H e lloAp p let extend s JA p plet{pu b lie v o i d p a i nt (Gr a phics g){g. cle a rRect (0, 0F g e t W i d th() > g etH e igh t ());g . draw S trin g ( "** * * **** **** * * * * * * 次 ** *** * * * ********** * * ************", ] 0, 2 0);g. d rawStri n g (" * * 熟能生巧",10, 30);g. dra w Stri ng ( " * **** * **** * 次 ********** * *** * *** * **** * * 次*************", ] 0, 40);}}网页:< h tml><head><t i tie >java 小程序 </ t itle> </h e ad> <body><APP LET CODE「J_Hel 1 oAp p let. class' WIDTH二〃200〃h e i g ht = '40,z> </appl e t > <BR></bo d y></html>1. 9请阐述编写j a va程序的具体步骤:第二章:2.2 U"算下而java表达式的值,并写出表达式结果在j ava中的数据类型(1)1+4/5+ ( i nt) 5. 2/2. 5=3. 0 //数据类型:浮点类型(2)1+4/5+ ( i nt) (5.2/2. 5)=3 / / 数据类型:整型(3)1+4/5 + 5. 2/2. 5=3. 08 //数据类型:浮点类型(4 ) 1. 0+4/5+5. 2/2. 5=3. 08 //数据类型:浮点类型(5)1+4/5. 0 +5.2/2. 5=3. 8 8 //数据类型:浮点类型(6)设已定义了变量i nt a =12,请计算表达式(++a) + (a++)因为a=12则 + +a=13现在护1 3所以a++二1 3所以表达式(++a)+(a++)=2 6 //数据类型:整型(7)10 >>2=2 //数据类型:整型(8)10&1 1 |12结果为t rue //数据类型:布尔型(9)5“7结果为2 即为真(10)(-5)1 (^5)结果为一5 //数据类型:整型J N字节码正确结果。

《Java语言程序设计(基础篇)》(第10版 梁勇 著)第三十二章练习题答案

《Java语言程序设计(基础篇)》(第10版 梁勇 著)第三十二章练习题答案

《Java语言程序设计(基础篇)》(第10版梁勇著)第三十二章练习题答案32.1import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.Button;import bel;import javafx.scene.control.TextField;import yout.BorderPane;import yout.HBox;import yout.VBox;import javafx.stage.Stage;public class Exercise32_01 extends Application {private Button btView = new Button("View");private Button btInsert = new Button("Insert");private Button btUpdate = new Button("Update");private Button btClear = new Button("Clear");private TextField tfID = new TextField();private TextField tfLastName = new TextField();private TextField tfFirstName = new TextField();private TextField tfMi = new TextField();private TextField tfAddress = new TextField();private TextField tfCity = new TextField();private TextField tfState = new TextField();private TextField tfTelephone = new TextField();private Label lblStatus = new Label();// The Statement for processing queriesprivate Statement stmt;@Override // Override the start method in the Application class public void start(Stage primaryStage) {VBox vBox = new VBox(5);HBox hBox1 = new HBox(5);hBox1.getChildren().addAll(new Label("ID"), tfID);HBox hBox2 = new HBox(5);hBox2.getChildren().addAll(new Label("Last Name"), tfLastName, new Label("First Name"), tfFirstName, new Label("MI"), tfMi);tfLastName.setPrefColumnCount(8);tfFirstName.setPrefColumnCount(8);tfMi.setPrefColumnCount(1);HBox hBox3 = new HBox(5);hBox3.getChildren().addAll(new Label("Address"), tfAddress);HBox hBox4 = new HBox(5);hBox4.getChildren().addAll(new Label("City"), tfCity,new Label("State"), tfState);HBox hBox5 = new HBox(5);hBox5.getChildren().addAll(new Label("Telephone"), tfTelephone); vBox.getChildren().addAll(hBox1, hBox2, hBox3, hBox4, hBox5);HBox hBox = new HBox(5);hBox.getChildren().addAll(btView, btInsert, btUpdate, btClear);hBox.setAlignment(Pos.CENTER);BorderPane pane = new BorderPane();pane.setCenter(vBox);pane.setTop(lblStatus);pane.setBottom(hBox);// Create a scene and place it in the stageScene scene = new Scene(pane, 400, 200);primaryStage.setTitle("ExtraExercise32_01"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stageinitializeDB();btView.setOnAction(e -> view());btInsert.setOnAction(e -> insert());btUpdate.setOnAction(e -> update());btClear.setOnAction(e -> clear());}private void initializeDB() {try {// Connect to the local InterBase databaseConnection conn = DriverManager.getConnection// ("dbc:odbc:exampleMDBDataSource", "", "" );("jdbc:mysql://localhost/javabook", "scott", "tiger");System.out.println("Database connected\n");lblStatus.setText("Database connected");// Create a statementstmt = conn.createStatement();}catch (Exception ex) {lblStatus.setText("Connection failed: " + ex);}}/**View record by ID*/private void view() {// Build a SQL SELECT statementString query = "SELECT * FROM Staff WHERE ID = "+ "'" + tfID.getText().trim() + "'";try {// Execute queryResultSet rs = stmt.executeQuery(query);loadToTextField(rs);}catch(SQLException ex) {lblStatus.setText("Select failed: " + ex);}}/**Load the record into text fields*/private void loadToTextField(ResultSet rs) throws SQLException { if (rs.next()) {tfLastName.setText(rs.getString(2));tfFirstName.setText(rs.getString(3));tfMi.setText(rs.getString(4));tfAddress.setText(rs.getString(5));tfCity.setText(rs.getString(6));tfState.setText(rs.getString(7));tfTelephone.setText(rs.getString(8));lblStatus.setText("Record found");}elselblStatus.setText("Record not found");}/**Insert a new record*/private void insert() {// Build a SQL INSERT statementString insertStmt ="INSERT INTO Staff(ID, LastName, FirstName, mi, Address, " + " City, State, Telephone) VALUES('" +tfID.getText().trim() + "','" +tfLastName.getText().trim() + "','" +tfFirstName.getText().trim() + "','" +tfMi.getText().trim() + "','" +tfAddress.getText().trim() + "','" +tfCity.getText().trim() + "','" +tfState.getText().trim() + "','" +tfTelephone.getText().trim() + "');";try {stmt.executeUpdate(insertStmt);}catch (SQLException ex) {lblStatus.setText("Insertion failed: " + ex);}lblStatus.setText("record inserted");}/**Update a record*/private void update() {// Build a SQL UPDATE statementString updateStmt = "UPDATE Staff " +"SET LastName = '" + tfLastName.getText().trim() + "'," +"FirstName = '" + tfFirstName.getText().trim() + "'," +"mi = '" + tfMi.getText().trim() + "'," +"Address = '" + tfAddress.getText().trim() + "'," +"City = '" + tfCity.getText().trim() + "'," +"State = '" + tfState.getText().trim() + "'," +"Telephone = '" + tfTelephone.getText().trim() + "' " +"WHERE ID = '" + tfID.getText().trim() + "'";try {stmt.executeUpdate(updateStmt);lblStatus.setText("Record updated");}catch(SQLException ex) {lblStatus.setText("Update failed: " + ex);}}/**Clear text fields*/private void clear() {tfID.setText(null);tfLastName.setText(null);tfFirstName.setText(null);tfMi.setText(null);tfAddress.setText(null);tfCity.setText(null);tfState.setText(null);tfTelephone.setText(null);}/*** The main method is only needed for the IDE with limited* avaFX support. Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}32.2import java.sql.*;import javafx.scene.Scene;import yout.HBox;import javafx.stage.Stage;import javafx.application.Application;public class Exercise32_02 extends Application {private String[] dataName;private double[] data;@Override // Override the start method in the Application class public void start(Stage primaryStage) {initializeDB();ChartModel chartModel = new ChartModel();chartModel.setChartData(dataName, data);PieChart pieChart = new PieChart();BarChart barChart = new BarChart();HBox hBox = new HBox(5);hBox.getChildren().addAll(pieChart, barChart);// Create a scene and place it in the stageScene scene = new Scene(hBox, 420, 80);primaryStage.setTitle("Exercise32_02"); // Set the stage titleprimaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stagepieChart.setModel(chartModel);barChart.setModel(chartModel);}private void initializeDB() {try {Connection conn = DriverManager.getConnection// ("dbc:odbc:exampleMDBDataSource", "", "" );("jdbc:mysql://localhost/javabook", "scott", "tiger");System.out.println("Database connected\n");// Connect to the sample databaseStatement stmt = conn.createStatement();ResultSet rs = stmt.executeQuery("select deptId, count(*) from Student where deptId is not null group by deptId;");// Count rowsint count = 0;while (rs.next()) {count++;}dataName = new String[count];data = new double[count];// We have to obtain the result set againrs = stmt.executeQuery("select deptId, count(*) from Student where deptId is not null group by deptId;");int i = 0;while (rs.next()) {dataName[i] = rs.getString(1);data[i] = rs.getInt(2);i++;}}catch (Exception ex) {ex.printStackTrace();}}/*** 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);}}32.3import javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import bel;import javafx.scene.control.TextField;import javafx.stage.Stage;import java.sql.*;import javafx.collections.FXCollections;import javafx.geometry.HPos;import boBox;import javafx.scene.control.PasswordField;import yout.BorderPane;import yout.GridPane;public class Exercise32_03 extends Application {@Override // Override the start method in the Application classpublic void start(Stage primaryStage) {// Create a scene and place it in the stageScene scene = new Scene(new DBConnectionPane(), 420, 80);primaryStage.setTitle("DB Connection"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stage primaryStage.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);}}class DBConnectionPane extends BorderPane {private Connection connection;private Label lblConnectionStatus = new Label("No connection");private Button btConnect = new Button("Connect to DB");private ComboBox<String> cboDriver = new ComboBox<>(FXCollections.observableArrayList("com.mysql.jdbc.Driver", "sun.jdbc.odbc.JdbcOdbcDriver","oracle.jdbc.driver.OracleDriver"));private ComboBox<String> cboURL = new ComboBox<>(FXCollections.observableArrayList("jdbc:mysql://localhost/javabook","jdbc:odbc:exampleMDBDataSource","jdbc:oracle:thin:@:1521:ora9i"));private TextField tfUsername = new TextField();private PasswordField pfPassword = new PasswordField();/** Creates new form DBConnectionPanel */public DBConnectionPane() {cboDriver.setEditable(true);cboURL.setEditable(true);GridPane gridPane = new GridPane();gridPane.add(new Label("JDBC Drive"), 0, 0);gridPane.add(new Label("Database URL"), 0, 1);gridPane.add(new Label("Username"), 0, 2);gridPane.add(new Label("Password"), 0, 3);gridPane.add(cboDriver, 1, 0);gridPane.add(cboURL, 1, 1);gridPane.add(tfUsername, 1, 2);gridPane.add(pfPassword, 1, 3);gridPane.add(btConnect, 1, 4);GridPane.setHalignment(btConnect, HPos.RIGHT);this.setTop(lblConnectionStatus);this.setCenter(gridPane);btConnect.setOnAction(e -> connectDB());}private void connectDB() {// Get database information from the user inputString driver = cboDriver.getValue();String url = cboURL.getValue();String username = tfUsername.getText().trim();String password = new String(pfPassword.getText());// Connection to the databasetry {Class.forName(driver);connection = DriverManager.getConnection(url, username, password);lblConnectionStatus.setText("Connected to " + url); }catch (ng.Exception ex) {ex.printStackTrace();}}/** Return connection */public Connection getConnection() {return connection;}}32.4import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.Button;import bel;import javafx.scene.control.TextField;import javafx.stage.Stage;import javafx.scene.control.ScrollPane;import javafx.scene.control.TextArea;import yout.BorderPane;import yout.HBox;public class Exercise32_04 extends Application {private TextField tfSSN = new TextField();private TextArea taResult = new TextArea();private Label lblStatus = new Label();private Button btShowGrade = new Button("Show Grade");// Statement for executing queriesprivate Statement stmt;@Override // Override the start method in the Application class public void start(Stage primaryStage) {HBox hBox = new HBox(5);hBox.getChildren().addAll(new Label("SSN"), tfSSN,btShowGrade);hBox.setAlignment(Pos.CENTER);BorderPane pane = new BorderPane();pane.setCenter(new ScrollPane(taResult));pane.setTop(hBox);pane.setBottom(lblStatus);// Create a scene and place it in the stageScene scene = new Scene(pane, 420, 80);primaryStage.setTitle("Exercise32_04"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stageinitializeDB();btShowGrade.setOnAction(e -> showGrade());}private void initializeDB() {try {// Load the JDBC driverClass.forName("com.mysql.jdbc.Driver");System.out.println("Driver loaded");// Establish a connectionConnection connection = DriverManager.getConnection("jdbc:mysql://localhost/javabook", "scott", "tiger");// ("jdbc:oracle:thin:@:1521:ora9i",// "scott", "tiger");System.out.println("Database connected");// Create a statementstmt = connection.createStatement();}catch (Exception ex) {ex.printStackTrace();}}private void showGrade() {String ssn = tfSSN.getText();try {String queryString = "select firstName, mi, " +"lastName, title, grade from Student, Enrollment, Course " +"where Student.ssn = '" + ssn +"' and Enrollment.courseId = Course.courseId " +" and Enrollment.ssn = Student.ssn";ResultSet rset = stmt.executeQuery(queryString);taResult.setText(null);int countRow = 0;while (rset.next()) {String lastName = rset.getString(1);String mi = rset.getString(2);String firstName = rset.getString(3);String title = rset.getString(4);String grade = rset.getString(5);// Display resulttaResult.appendText(firstName + " " + mi +" " + lastName + "'s grade on course " + title + " is " +grade + "\n");countRow++;}if (countRow > 0)lblStatus.setText(countRow + " courses found");elselblStatus.setText("no courses found for this SSN");}catch (SQLException ex) {ex.printStackTrace();}}/*** 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);}}32.5import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.ResultSetMetaData;import java.sql.SQLException;import java.sql.Statement;import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.Button;import bel;import javafx.scene.control.TextField;import javafx.stage.Stage;import javafx.scene.control.ScrollPane;import javafx.scene.control.TextArea;import yout.BorderPane;import yout.HBox;public class Exercise32_05 extends Application {private TextField tfTableName = new TextField();private TextArea taResult = new TextArea();private Button btShowContents = new Button("Show Contents"); private Label lblStatus = new Label();// Statement for executing queriesprivate Statement stmt;@Override // Override the start method in the Application class public void start(Stage primaryStage) {HBox hBox = new HBox(5);hBox.getChildren().addAll(new Label("Table Name"), tfTableName, btShowContents);hBox.setAlignment(Pos.CENTER);BorderPane pane = new BorderPane();pane.setCenter(new ScrollPane(taResult));pane.setTop(hBox);pane.setBottom(lblStatus);// Create a scene and place it in the stageScene scene = new Scene(pane, 420, 80);primaryStage.setTitle("Exercise32_05"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stageinitializeDB();btShowContents.setOnAction(e -> showContents());}private void initializeDB() {try {// Load the JDBC driverClass.forName("com.mysql.jdbc.Driver");System.out.println("Driver loaded");// Establish a connectionConnection connection = DriverManager.getConnection("jdbc:mysql://localhost/javabook", "scott", "tiger");// ("jdbc:oracle:thin:@:1521:ora9i",// "scott", "tiger");System.out.println("Database connected");// Create a statementstmt = connection.createStatement();}catch (Exception ex) {ex.printStackTrace();}}private void showContents() {String tableName = tfTableName.getText();try {String queryString = "select * from " + tableName;ResultSet resultSet = stmt.executeQuery(queryString);ResultSetMetaData rsMetaData = resultSet.getMetaData();for (int i = 1; i <= rsMetaData.getColumnCount(); i++) {taResult.appendText(rsMetaData.getColumnName(i) + " "); }taResult.appendText("\n");// Iterate through the result and print the student nameswhile (resultSet.next()) {for (int i = 1; i <= rsMetaData.getColumnCount(); i++)taResult.appendText(resultSet.getObject(i) + " "); taResult.appendText("\n");}}catch (SQLException ex) {ex.printStackTrace();}}/*** 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);}}32.6import java.sql.Connection;import java.sql.DatabaseMetaData;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.ResultSetMetaData;import java.sql.SQLException;import java.sql.Statement;import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.Button;import boBox;import bel;import javafx.stage.Stage;import javafx.scene.control.ScrollPane;import javafx.scene.control.TextArea;import yout.BorderPane;import yout.HBox;public class Exercise32_06 extends Application {private ComboBox<String> cboTableName = new ComboBox<>(); private TextArea taResult = new TextArea();private Button btShowContents = new Button("Show Contents"); private Label lblStatus = new Label();// Statement for executing queriesprivate Statement stmt;@Override // Override the start method in the Application class public void start(Stage primaryStage) {HBox hBox = new HBox(5);hBox.getChildren().addAll(new Label("Table Name"),cboTableName, btShowContents);hBox.setAlignment(Pos.CENTER);BorderPane pane = new BorderPane();pane.setCenter(new ScrollPane(taResult));pane.setTop(hBox);pane.setBottom(lblStatus);// Create a scene and place it in the stageScene scene = new Scene(pane, 420, 80);primaryStage.setTitle("Exercise32_06"); // Set the stage titleprimaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stageinitializeDB();btShowContents.setOnAction(e -> showContents());}private void initializeDB() {try {// Load the JDBC driverClass.forName("com.mysql.jdbc.Driver");System.out.println("Driver loaded");// Establish a connectionConnection connection = DriverManager.getConnection("jdbc:mysql://localhost/javabook", "scott", "tiger");// ("jdbc:oracle:thin:@:1521:ora9i",// "scott", "tiger");System.out.println("Database connected");// Create a statementstmt = connection.createStatement();DatabaseMetaData dbMetaData = connection.getMetaData();ResultSet rsTables = dbMetaData.getTables(null, null, null,new String[] {"TABLE"}); System.out.print("User tables: ");while (rsTables.next()) {cboTableName.getItems().add(rsTables.getString("TABLE_NAME")); }cboTableName.getSelectionModel().selectFirst();}catch (Exception ex) {ex.printStackTrace();}}private void showContents() {String tableName = cboTableName.getValue();try {String queryString = "select * from " + tableName;ResultSet resultSet = stmt.executeQuery(queryString);ResultSetMetaData rsMetaData = resultSet.getMetaData();for (int i = 1; i <= rsMetaData.getColumnCount(); i++) {taResult.appendText(rsMetaData.getColumnName(i) + " "); }taResult.appendText("\n");// Iterate through the result and print the student nameswhile (resultSet.next()) {for (int i = 1; i <= rsMetaData.getColumnCount(); i++)taResult.appendText(resultSet.getObject(i) + " "); taResult.appendText("\n");}}catch (SQLException ex) {ex.printStackTrace();}}/*** 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);}}32.7/*Statement for creating a tablecreate table Quiz(questionId int,question varchar(4000),choicea varchar(1000),choiceb varchar(1000),choicec varchar(1000),choiced varchar(1000),answer varchar(5));*/import java.io.*;import java.util.*;import java.sql.*;public class Exercise32_07 {private ArrayList<Quiz> chapters = new ArrayList<Quiz>(); private PreparedStatement pstmt1;static class Quiz {String question = "";String choicea = "";String choiceb = "";String choicec = "";String choiced = "";String answer;String hint;}public static void main(String[] args) {new Exercise32_07();}/** Initialize global variables */public Exercise32_07() {try {readTest(chapters);initializeJdbc();int questionNo = 1;for (Quiz question : chapters) {storeQuiz(questionNo++, question);}}catch (Exception ex) {ex.printStackTrace();}}private void readTest(List<Quiz> testForAChapter) throwsException {// Create a buffered reader for reading questions from a fileBufferedReader in = new BufferedReader(new FileReader("Quiz.txt"));// Quiz countint questionCount = 0;boolean beginningOfQuiz = true; // for the first one// Text line from the question fileString line = "";Quiz question = null;// Read and process each line from the text fileloop:while ((line = in.readLine()) != null) {// Process a blank line in the text fileif (line.length() < 1) {continue;}// Determine question statement and multiple choicesif (line.charAt(0) == 'a' && line.charAt(1) == '.') {question.choicea = line.substring(2);}else if (line.charAt(0) == 'b' && line.charAt(1) == '.') {question.choiceb = line.substring(2);}else if (line.charAt(0) == 'c' && line.charAt(1) == '.') {question.choicec = line.substring(2);}else if (line.charAt(0) == 'd' && line.charAt(1) == '.') {question.choiced = line.substring(2);}else if (line.matches("(\\d)+\\..*")) { // Start a new questionbeginningOfQuiz = true;questionCount++; // Increase question countquestion = new Quiz(); // Create a new testtestForAChapter.add(question); // Add to the listquestion.question += line;}else if(line.toUpperCase().indexOf("ANSWER") == 0) { // End of question section// Extract answer and explanationStringTokenizer st = new StringTokenizer(line.substring(7),".\n\r\t ");question.answer = st.nextToken().toUpperCase();if (st.hasMoreTokens()) {question.hint = st.nextToken("\n\r");}}else if (line.charAt(0) == ' ') { // Process spaces before lineString spaces = "";for (int j = 0;((j < line.length()) && (line.charAt(j) == ' ')); j++) { spaces += "&nbsp";}question.question += spaces;question.question += line;}else {if (beginningOfQuiz && Character.isDigit(line.charAt(0)) &&line.charAt(1) == '.') {question.question += line.substring(2);beginningOfQuiz = false;}else if (beginningOfQuiz && Character.isDigit(line.charAt(0)) &&Character.isDigit(line.charAt(1))&& line.charAt(2) == '.') {question.question += line.substring(3);beginningOfQuiz = false;}else {question.question += line;}}}// Close the filein.close();}/** Initialize database connection */private void initializeJdbc() {try {// Load the JDBC driverClass.forName("com.mysql.jdbc.Driver");System.out.println("Driver loaded");// Declare driver and connection string// String connectionString = "jdbc:odbc:exampleMDBDataSource";// For MySQLString connectionString = "jdbc:mysql://localhost/javabook";// For Oracle// String connectionString = "jdbc:oracle:" +//"thin:scott/tiger@:1521:orcl";// Connect to the sample databaseConnection conn = DriverManager.getConnection(connectionString, "scott", "tiger");// Create a statement to insert questionspstmt1 = conn.prepareStatement("insert into Quiz " +"(questionId, question, choicea, choiceb, choicec, choiced, answer)" + "values (?, ?, ?, ?, ?, ?, ?)");}catch (Exception ex) {ex.printStackTrace();}}/** Store a question to the database */private void storeQuiz(int questionNo,Quiz question) throws SQLException {pstmt1.setInt(1, questionNo);pstmt1.setString(2, question.question);pstmt1.setString(3, question.choicea);pstmt1.setString(4, question.choiceb);pstmt1.setString(5, question.choicec);pstmt1.setString(6, question.choiced);pstmt1.setString(7, question.answer);pstmt1.executeUpdate();}}32.8import java.util.*;import java.sql.*;public class Exercise32_08 {private Statement stmt;。

Java语言程序设计基础篇(第10版) 梁勇 课后习题答案

Java语言程序设计基础篇(第10版) 梁勇 课后习题答案

System.out.println("Programming is fun .");
}
}
1.2 public class Test{
public static void main(String[] args){
for(int i = 0;i <= 4;i++){
System.out.println("Welcome to Java !");
public static void main(String[] args){ double S = 14 / 1.6;
double T = 45 * 60 + 30; double speed = S / T; System.out.println(speed); } } 1.11 public class Test{ public static void main(String[] args){ int BN = 312032486; //original person numbers double EveryYS,EveryYBP,EveryYDP,EveryYMP; EveryYS = 365 * 24 * 60 * 60; EveryYBP = EveryYS / 7; EveryYDP = EveryYS / 13; EveryYMP = EveryYS / 45; int FirstYP,SecondYP,ThirdYP,FourthYP,FivthYP; FirstYP = (int)(BN + EveryYBP + EveryYMP - EveryYDP); SecondYP = (int)(FirstYP + EveryYBP + EveryYMP - EveryYDP); ThirdYP = (int)(SecondYP + EveryYBP + EveryYMP - EveryYDP); FourthYP = (int)(ThirdYP + EveryYBP + EveryYMP - EveryYDP); FivthYP = (int)(FourthYP + EveryYBP + EveryYMP - EveryYDP); System.out.println(FirstYP); System.out.println(SecondYP); System.out.println(ThirdYP); System.out.println(FourthYP); System.out.println(FivthYP); } } 1.12 public class Test{ public static void main(String[] args){ double S = 24 * 1.6; double T = (1 * 60 + 40) * 60 + 35; double speed = S / T; System.out.println(speed); } } 1.13 import java.util.Scanner; public class Test{ public static void main(String[] args){ Scanner input = new Scanner(System.in); System.out.println("input a,b,c,d,e,f value please:"); double a = input.nextDouble(); double b = input.nextDouble(); double c = input.nextDouble(); double d = input.nextDouble(); double e = input.nextDouble();

java语言程序设计基础篇第十版练习答案精编

java语言程序设计基础篇第十版练习答案精编

j a v a语言程序设计基础篇第十版练习答案精编Document number:WTT-LKK-GBB-08921-EIGG-2298601import class Exercise14_01 extendsApplication {@Override Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}02import class Exercise14_02 extends Application {@Override Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}03import class Exercise14_03 extends Application {@Override One is to use the hint in the book.ArrayList<Integer> list = new ArrayList<>(); for (int i = 1; i <= 52; i++) {(i);}HBox pane = new HBox(5);;().add(new ImageView("image/card/" + (0) +".png"));().add(new ImageView("image/card/" + (1) +".png"));().add(new ImageView("image/card/" + (2) +".png"));Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}04import class Exercise14_04 extends Application {@Override dd(txt);}Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}05import class Exercise14_05 extends Application {@Override dd(txt);}Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}05import class Exercise14_05 extends Application {@Override dd(txt);}Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}06import class Exercise14_06 extends Application {@Override dd(rectangle);}}Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}07import class Exercise14_07 extends Application {@Override Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}08import class Exercise14_08 extends Application {@Override ng"), j, i);}}Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}09import class Exercise14_09 extends Application {@Override Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}class FanPane extends Pane {double radius = 50;public FanPane() {Circle circle = new Circle(60, 60, radius);;;getChildren().add(circle);Arc arc1 = new Arc(60, 60, 40, 40, 30, 35);; ddAll(arc1, arc2, arc3, arc4);}}10import class Exercise14_10 extends Application {@Override ddAll, ;Arc arc2 = new Arc(100, 140, 50, 20, 180, 180); ;;().addAll(ellipse, arc1, arc2,new Line(50, 40, 50, 140), new Line(150, 40, 150, 140));Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}11import class Exercise14_11 extends Application {@Override ddAll(circle, ellipse1, ellipse2,circle1, circle2, line1, line2, line3, arc);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}12import class Exercise14_12 extends Application {@Override ddAll(r1, text1, r2, text2, r3, text3, r4, text4);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}13import class Exercise14_13 extends Application {@Override ddAll(arc1, text1, arc2, text2, arc3, text3, arc4, text4);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}14import class Exercise14_14 extends Application {@Override ddAll(r1, r2, line1, line2, line3, line4);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}15import class Exercise14_15 extends Application {@Override ddAll(polygon, text);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}16import class Exercise14_16 extends Application {@Override ind().divide(3));().bind());().bind().divide(3));;Line line2 = new Line(0, 0, 0, 0);().bind().multiply(2).divide(3));().bind());().bind().multiply(2).divide(3));;Line line3 = new Line(0, 0, 0, 0);().bind().divide(3));().bind().divide(3));().bind());;Line line4 = new Line(0, 0, 0, 0);().bind().multiply(2).divide(3));().bind().multiply(2).divide(3));().bind());;().addAll(line1, line2, line3, line4);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}17import class Exercise14_17 extends Application {@Override ddAll(arc, line1, line2, line3, circle, line4, line5, line6, line7, line8);Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}18import class Exercise14_18 extends Application {@Override ddAll(polyline, line1, line2,line3, line4, line5, line6, text1, text2);Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}19import class Exercise14_19 extends Application {@Override ddAll(polyline1, polyline2, line1,line2,line3, line4, line5, line6, text1, text2,text3,text4, text5, text6, text7);Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}20import class Exercise14_20 extends Application {@Override dd(new Line(x1, y1, x2, y2));dd(new Line(x2, y2, (x2 + (arctan + set45) * arrlen)),((y2)) + (arctan + set45) * arrlen)));().add(new Line(x2, y2, (x2 + (arctan - set45) * arrlen)),((y2)) + (arctan - set45) * arrlen)));}/*** 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);}}21import class Exercise14_21 extends Application {@Override istance(x2, y2) + "");().addAll(circle1, circle2, line, text);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}22import class Exercise14_22 extends Application {@Override ddAll(circle1, circle2, line, text1, text2);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}23import class Exercise14_23 extends Application {@Override ddAll(r1, r2, text);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}24import class Exercise14_24 extends Application {@Override ddAll(polygon, new Circle(x5, y5, 10), text);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}25import class Exercise14_25 extends Application {@Override ddAll(circle, polygon);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}26import class Exercise14_26 extends Application {@Override ddAll(clock1, clock2);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}27import class Exercise14_27 extends Application {@OverrideNot needed for running from the command line. */public static void main(String[] args) {launch(args);}}class DetailedClockPane extends Pane {private int hour;private int minute;private int second;lear();getChildren().addAll(circle, sLine, mLine, hLine);dd(new Line(xOuter, yOuter, xInner, yInner));}dd(text);}}}28import class Exercise14_28 extends Application {@OverrideNot needed for running from the command line.*/public static void main(String[] args) {launch(args);}}class ClockPaneWithBooleanProperties extends Pane { private int hour;private int minute;private int second;private boolean hourHandVisible = true;private boolean minuteHandVisible = true; private boolean secondHandVisible = true;public boolean isHourHandVisible() {return hourHandVisible;}public void setHourHandVisible(boolean hourHandVisible) {= hourHandVisible;paintClock();}public boolean isMinuteHandVisible() {return minuteHandVisible;}public void setMinuteHandVisible(boolean minuteHandVisible) {= minuteHandVisible;paintClock();}public boolean isSecondHandVisible() {return secondHandVisible;public void setSecondHandVisible(boolean secondHandVisible) {= secondHandVisible;paintClock();}lear();getChildren().addAll(circle, t1, t2, t3, t4);if (secondHandVisible) {getChildren().add(sLine);}if (minuteHandVisible) {getChildren().add(mLine);}if (hourHandVisible) {getChildren().add(hLine);}}}import class Exercise14_29 extends Application {final static double HGAP = 20;final static double VGAP = 20;final static double RADIUS = 5;final static double LENGTH_OF_SLOTS = 40;final static double LENGTH_OF_OPENNING = 15;final static double Y_FOR_FIRST_NAIL = 50;final static double NUMBER_OF_SLOTS = 9;final static double NUMBER_OF_ROWS =NUMBER_OF_SLOTS - 2;@Override dd(c);}}dd(new Line(x, y, x, y + LENGTH_OF_SLOTS)); }dd(new Line(centerX - (NUMBER_OF_ROWS - 1) * HGAP / 2 - HGAP,y + LENGTH_OF_SLOTS, centerX -(NUMBER_OF_ROWS - 1) * HGAP / 2 + NUMBER_OF_ROWS * HGAP,y + LENGTH_OF_SLOTS));dd(new Line(centerX + HGAP / 2,Y_FOR_FIRST_NAIL + RADIUS,centerX - (NUMBER_OF_ROWS - 1) * HGAP / 2 + NUMBER_OF_ROWS * HGAP, y));().add(new Line(centerX - HGAP / 2,Y_FOR_FIRST_NAIL + RADIUS,centerX - (NUMBER_OF_ROWS - 1) * HGAP / 2 - HGAP, y));dd(new Line(centerX - HGAP / 2,Y_FOR_FIRST_NAIL + RADIUS,centerX - HGAP / 2, Y_FOR_FIRST_NAIL - LENGTH_OF_OPENNING));().add(new Line(centerX + HGAP / 2,Y_FOR_FIRST_NAIL + RADIUS,centerX + HGAP / 2, Y_FOR_FIRST_NAIL - LENGTH_OF_OPENNING));Not needed for running from the command line.*/public static void main(String[] args) { launch(args);}}。

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环境演练【目的】①安装并配置Java运行开发环境;②掌握开发Java应用程序的3个步骤:编写源文件、编译源文件和运行应用程序;③掌握开发Java Applet程序的3个步骤:编写源文件、编译源文件和运行Java Applet 程序;④学习同时编译多个Java源文件。

【内容】1.一个简单的应用程序✧实验要求:编写一个简单的Java应用程序,该程序在命令行窗口输出两行文字:“你好,很高兴学习Java”和“We are students”。

✧程序运行效果示例:程序运行效果如下图所示:✧程序模板:Hello.javapublic class Hello{public static void main (String args[ ]){【代码1】 //命令行窗口输出"你好,很高兴学习Java"A a=new A();a.fA();}}class A{void fA(){【代码2】 //命令行窗口输出"We are students"}}✧实验后的练习:1.编译器怎样提示丢失大括号的错误?2.编译器怎样提示语句丢失分号的错误?3.编译器怎样提示将System写成system这一错误?4.编译器怎样提示将String写成string这一错误?2.一个简单的Java Applet程序✧实验要求:编写一个简单的Java Applet程序,并在Java Applet中写两行文字:“这是一个Java Applet程序”和“我改变了字体”。

✧程序运行效果示例:程序运行效果如下图所示:✧程序模板:FirstApplet.javaimport java.applet.*;import java.awt.*;public class FirstApplet extends Applet{public void paint(Graphics g){g.setColor(Color.blue);【代码1】//在Java Applet中绘制一行文字:“这是一个Java Applet 程序”g.setColor(Color.red);g.setFont(new Font("宋体",Font.BOLD,36));【代码2】//在Java Applet中绘制一行文字:“我改变了字体”}}✧实验后的练习:5.程序中的主类如果不用public修饰,编译能通过吗?6.程序中的主类如果不用public修饰,程序能正确运行吗?7.程序将paint方法误写成Paint,编译能通过么?8.程序将paint方法误写成Paint,运行时能看到有关的输出信息吗?3.联合编译✧实验要求:编写4个源文件:Hello.java、A.java、B.java和C.java,每个源文件只有一个类,Hello.java是一个应用程序(含有main方法),使用了A、B和C类。

java语言程序设计方案基础篇答案

java语言程序设计方案基础篇答案

在一个正n边形中,所以边的长度都相同,且所有角的度数都相同(即这个多边形是等边等角的)。

设计一个名为RegularPolygon的类,该类包括:一个名为int型的私有数据域定义多边形的边数,默认值3。

一个名为side的double型私有数据域存储边的长度,默认值1。

一个名为x的double型私有数据域,它定义多边形中点的x坐标,默认值0。

一个名为y 的double型私有数据域,它定义多边形中点的y坐标,默认值0。

一个创建带默认值的正多边形的无参构造方法。

一个能创建带指定边数和边长度、中心在(0,0)的正多边形的构造方法。

一个能创建带指定边数和边长度、中心在(x,y)的正多边形的构造方法。

所有数据域的访问器和修改器。

一个返回多边形周长的方法getPerimeter()。

一个返回多边形面积的方法getArea().计算多边形面积的公式是:面积=(n*s*s)/(4*tan(p/n)) 画出该类的UML图。

实现这个类。

编写一个测试程序,分别使用无参构造方法、RegularPolygon(6,4)和RegularPolygon(10,4,5.6,7.8)创建三个RegularPolygon对象。

显示每个对象的周长和面积。

代码:class Regularpolygon{private int n=3。

//边长private double side=1。

//边长private double x=0。

private double y=0。

//x,y为多边形中点的x,y坐标Regularpolygon(){}Regularpolygon(int newN,int newS){n=newN。

side=newS。

x=0。

y=0。

}Regularpolygon(int newN,int newS,double newX,double newY){n=newN。

side=newS。

x=newX。

y=newY。

}public void setN(int newN){n=newN。

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

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

J a v a语言程序设计课后习题答案全集Document serial number【UU89WT-UU98YT-UU8CB-UUUT-UUT108】指出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语言程序设计(基础篇)答案

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语言程序设计(基础篇)(第10版 梁勇著)第二章练习题答案

Java语言程序设计(基础篇)(第10版 梁勇著)第二章练习题答案
第二章基本程序设计练习题答案本人在自学编程过程中发现本书答案很难找找到的要么不完整要么错误百出所以我将自己所做的练习题答案提供给有需要者供大家交流
《Java语言程序设计(基础篇)》(第10版 梁勇 著) 第二章 基本程序设计 练习题答案
本人在自学编程过程中,发现本书答案很难找,找到的要么不完整、要么错误百出,所以我将自己所做的 练习题答案,提供给有需要者,供大家交流。本章答案均为本人一字一字所敲,答案均经过验证,虽为初学者, 但代码均按照书中规范要求书写,如有错误或更好的建议,请指正交流。
// 第二章 P59 练习题2.1 (将摄氏温度转为华氏温度) import java.util.Scanner;
public class CelsiusToFahrenheit {
public static void main(String[] args) { // 华氏温度和摄氏温度的转换公式为:华氏温度 = (9/5)*摄氏温度+32 Scanner input = new Scanner(System.in);
System.out.print("Enter the time zone offset to GMT: "); long timeZoneOffset = input.nextLong(); // 此处用long还是int?
long totalMilliseconds = System.currentTimeMillis(); long totalSeconds = totalMilliseconds / 1000; long currentSecond = totalSeconds % 60; long totalMinutes = totalSeconds / 60; long currentMinute = totalMinutes % 60; long totalHours = totalMinutes / 60; long currentHour = totalHours % 24; long hour = currentHour + timeZoneOffset;

java语言程序设计基础篇复习题答案

java语言程序设计基础篇复习题答案

java语言程序设计基础篇复习题答案【篇一:《java语言程序设计基础教程》(龚永罡_陈昕)习题答案】txt>1.9 练习思考题1、a,b,c2、d3、a,b 4 a 5、b6、开发与运行java程序需要经过的三个主要步骤为____________、____校验________和___解释执行____。

7、如果一个java applet源程序文件只定义有一个类,该类的类名为myapplet,则类myapplet必须是类的子类并且存储该源程序文件的文件名为。

8、如果一个java applet程序文件中定义有3个类,则使用sun 公司的jdk编译器编译该源程序文件将产生___3___个文件名与类名相同而扩展名为__class____的字节码文件。

11、编写一个简单的java应用程序,该程序在命令行窗口输出两行文字:“你好,很高兴学习java”和“we are students”。

解答:class myfirstjava{public static void main(string args[]){system.out.println(“你好,很高兴学习java”);system.out.println(“we are students”);}}第2章 java基本的程序设计结构2.7练习思考题1、a,b,d2、C3、a4、b5、d6、d,f7、b8、d9、d10、a11、D12、a 13、B 14、c15、d16、a17、在java的基本数据类型中,char型采用unicode编码方案,每个unicode码占用字节内存空间,这样,无论是中文字符还是英文字符,都是占用字节内存空间。

18、设 x = 2 ,则表达式 ( x + + )/3 的值是。

19、若x = 5,y = 10,则x y和x = y的逻辑值分别为和。

20、设有数组定义:int myintarray[] = { 10, 20, 30, 40, 50, 60, 70 };则执行以下几个语句后的输出结果是: 120。

《Java语言程序设计(基础篇)》(第10版 梁勇 著)第二十一章练习题答案

《Java语言程序设计(基础篇)》(第10版 梁勇 著)第二十一章练习题答案

《Java语言程序设计(基础篇)》(第10版梁勇著)第二十一章练习题答案21.1import java.util.*;public class Exercise21_01 {public static void main(String[] args) {LinkedHashSet<String> set1 = new LinkedHashSet<String>(Arrays.asList( new String[]{"George", "Jim", "John", "Blake", "Kevin", "Michael"}));LinkedHashSet<String> set1Clone1 = (LinkedHashSet<String>)set1.clone(); LinkedHashSet<String> set1Clone2 = (LinkedHashSet<String>)set1.clone();LinkedHashSet<String> set2 = new LinkedHashSet<String>(Arrays.asList( new String[] {"George", "Katie", "Kevin", "Michelle", "Ryan"}));set1.addAll(set2);set1Clone1.removeAll(set2);set1Clone2.retainAll(set2);System.out.println("The union of the two sets is " + set1);System.out.println("The difference of the two sets is " + set1Clone1); System.out.println("The intersection of the two sets is " + set1Clone2); }}21.1附加import java.util.*;public class Exercise21_01Extra {public static void main(String[] args) {System.out.print("Enter a string: ");Scanner input = new Scanner(System.in);String s = input.nextLine();Character[] list1 = {'A', 'E', 'I', 'O', 'U'};Set<Character> vowels = new HashSet<>(Arrays.asList(list1));Set<Character> vowelsInString = new HashSet<>();Set<Character> consonantsInString = new HashSet<>();int numbeOfVowels = 0;int numbeOfConsonants = 0;for (int i = 0; i < s.length(); i++) {char ch = Character.toUpperCase(s.charAt(i));if (Character.isLetter(ch)) {if (vowels.contains(ch)) {if (!vowelsInString.contains(ch)) {vowelsInString.add(ch);numbeOfVowels++;}}else if (!consonantsInString.contains(ch)) {consonantsInString.add(ch);numbeOfConsonants++;}}}System.out.println("The number of vowels is " + numbeOfVowels);System.out.println("The number of consonants is " + numbeOfConsonants); }}21.2import java.util.*;import java.io.*;public class Exercise21_02 {public static void main(String[] args) {if (args.length != 1) {System.out.println("Usage: java Exercise21_02 fullfilename");System.exit(1);}String filename = args[0];// Create a tree set to hold the wordsTreeSet<String> treeSet = new TreeSet<String>();try {Scanner in = new Scanner(new File(filename));String line;while ((line = in.nextLine()) != null) {String[] tokens = line.split("[ |\n|\t|\r|.|,|)|(|-|\"]");for (int i = 0; i < tokens.length; i++)treeSet.add(tokens[i]);}}catch (Exception ex) {System.err.println(ex);}// Get an iterator for the setIterator iterator = treeSet.iterator();// Display mappingsSystem.out.println("\nDisplay words in ascending order ");while (iterator.hasNext()) {System.out.println(iterator.next());}}}21.3import java.util.*;import java.io.*;public class Exercise21_03 {public static void main(String[] args) {// Check usageif (args.length != 1) {System.out.println("Usage: java Exercise21_03 file.java");System.exit(1);}// Array of all Java keywords + true + nullString[] keywordString = {"abstract", "finally", "public", "boolean", "float", "return", "break", "for", "short", "byte","goto", "static", "case", "if", "super", "catch", "implements", "switch", "char", "import", "synchronized", "class","instanceof", "this", "const", "int", "throw", "continue","interface", "throws", "default", "long", "transient", "do","native", "try", "double", "new", "void", "else", "package","volatile", "extends", "private", "while", "final","protected", "true", "null"};Set<String> keywordSet =new HashSet<String>(Arrays.asList(keywordString));int count = 0;try {Scanner input = new Scanner(new File(args[0]));String text = "";while (input.hasNext()) {String line = input.nextLine();line = stripLineComments(line);line = stripLineStringLiterals(line);text += line + " ";}text = stripParagraghComments(text);String[] tokens = text.split("[ \\[,()\\]]");for (String token: tokens) {if (keywordSet.contains(token))count++;}System.out.println("The number of keywords in the program is " + count);}catch (Exception ex) {ex.printStackTrace();}}/* Strip line comments */private static String stripLineComments(String line) {int index = line.indexOf("//");if (index < 0)return line;elsereturn line.substring(0, index);}/* Strip string literals */private static String stripLineStringLiterals(String line) {int start = line.indexOf("\"");int end = line.indexOf("\"", start + 1);while (start > 0 && end > 0) {line = line.substring(0, start) + line.substring(end + 1);start = line.indexOf("\"");end = line.indexOf("\"");}return line;}/* Strip paragraph comments */private static String stripParagraghComments(String text) {int start = text.indexOf("/*");int end = text.indexOf("*/");while (start > 0 && end > 0) {text = text.substring(0, start) + text.substring(end + 2);start = text.indexOf("/*");end = text.indexOf("*/");}return text;}}/** This is an incorrect version. It does not count the case such as (this. Here the this keyword* is not counted. It does not exclude keywords in the comments*import java.util.*;import java.io.*;public class Exercise20_03 {public static void main(String[] args) {// Check usageif (args.length != 1) {System.out.println("Usage: java Exercise20_03 file.java");System.exit(0);}// Array of all Java keywords + true + nullString[] keywordString = {"abstract", "finally", "public","boolean", "float", "return", "break", "for", "short", "byte", "goto", "static", "case", "if", "super", "catch", "implements", "switch", "char", "import", "synchronized", "class","instanceof", "this", "const", "int", "throw", "continue","interface", "throws", "default", "long", "transient", "do","native", "try", "double", "new", "void", "else", "package","volatile", "extends", "private", "while", "final","protected", "true", "null"};Set<String> keywordSet =new HashSet<String>(Arrays.asList(keywordString));int count = 0;try {Scanner input = new Scanner(new File(args[0]));while (input.hasNext()) {String token = input.next();if (keywordSet.contains(token))count++;}System.out.println("The number of keywords in the program is " + count);}catch (Exception ex) {ex.printStackTrace();}}}*/21.4import java.util.Scanner;import java.util.HashSet;import java.util.Arrays;public class Exercise21_04 {public static void main(String[] args) throws Exception {HashSet<Character> set1 = new HashSet<Character>(Arrays.asList( new Character[]{'A', 'E', 'I', 'O', 'U'}));System.out.print("Enter a filename: ");Scanner input = new Scanner(System.in);String filename = input.nextLine();input = new Scanner(new java.io.File(filename));int countVowels = 0;int countConsonants = 0;while (input.hasNext()) {String s = input.nextLine().toUpperCase();for (int i = 0; i < s.length(); i++) {if (set1.contains(s.charAt(i)))countVowels++;else if (Character.isLetter(s.charAt(i)))countConsonants++;}}System.out.println("The number of vowels is " + countVowels + " and consonanats is " +countConsonants);}}21.5/*** Usage: Copy this class to the folder, run it with java JavaToHTMLftim * to generate* HTM file for all the .java file in this folder. The generated .htm files are* stored in the same folder*/import java.util.*;import java.io.*;public class Exercise21_05 {// Array of all Java keywords + true + false + nullstatic String[] keywordString = {"abstract", "assert", "boolean","break", "byte", "case", "catch", "char", "class", "const","continue", "default", "do", "double", "else", "enum","extends", "for", "final", "finally", "float", "goto", "if","implements", "import", "instanceof", "int", "interface","long", "native", "new", "package", "private", "protected","public", "return", "short", "static", "strictfp", "super","switch", "synchronized", "this", "throw", "throws","transient", "try", "void", "volatile", "while","true", "false", "null"};static Set<String> keywordSet =new HashSet<String>(Arrays.asList(keywordString));/** Main method */public static void main(String[] args) throws Exception {// Check usageif (args.length != 2) {System.out.println("Usage: java Exercise20_10 javaSourcefile htmlfile");System.exit(1);}Scanner input = new Scanner(new File(args[0]));PrintWriter output = new PrintWriter(new File(args[1]));JavaToHTML(input, output);}static boolean stringToken = false;static String inputFileName;public static void JavaToHTML(Scanner input, PrintWriter output) { try {output.format("%s\r\n", "<html>");output.format("%s\r\n", "<head>");output.format("%s\r\n","<title>Intro to Java Programming, 6E - " + inputFileName +"</title>");output.format("%s\r\n","<meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1252\">");output.format("%s\r\n", "<style type = \"text/css\">");output.format("%s\r\n","body {font-family: \"Courier New\", sans-serif; font-size: 100%; color: black}");output.format("%s\r\n",".keyword {color: #000080; font-weight: bold}");output.format("%s\r\n", ".comment {color: #008000}");output.format("%s\r\n", ".literal {color: #0000ff}");// Match the color in the text// output.format("%s\r\n", ".keyword {color: black; font-weight: bold}");// output.format("%s\r\n", ".comment {color: #77797C}");// output.format("%s\r\n", ".literal {color: #007346; font-weight: bold}");output.format("%s\r\n", "</style>");output.format("%s\r\n", "</head>");output.format("%s\r\n", "<body>");output.format("%s\r\n", "<pre>");String text = "";String temp;// Read all lineswhile (input.hasNext()) {temp = input.nextLine();text += temp + "\r\n";}text = text.replaceAll(">", "&gt;");text = text.replaceAll("<", "&lt;");translateToHTML(text, input, output);output.format("%s\r\n", "</pre>");output.format("%s\r\n", "</body>");output.format("%s\r\n", "</html>");}catch (Exception ex) {System.out.println(ex);}finally {try {input.close();output.close();}catch (Exception ex) {}}}/** Translate Java source code to HTML */static void translateToHTML(String text, Scanner input, PrintWriter output) throws Exception {text = text.replaceAll("// ", "LINECOMMENT");text = text.replaceAll("/\\*", "BLOCKCOMMENT");String token;while (text != null && text.length() > 0) {// * and / are in conflict with /* and //String[] parts = text.split("[%\\+\\-\\*/\r\n\t \\[\\].;(){},]", 2); token = parts[0];if (token.length() > 1 && token.startsWith("LINECOMMENT")) {output.format("%s", "<span class = \"comment\">");parts = text.split("\r\n", 2);text = parts[1];output.format("%s", parts[0].replaceAll("LINECOMMENT", "// "));output.format("%s", "</span>\r\n");continue;}else if (token.length() > 1 && token.startsWith("BLOCKCOMMENT")) {output.format("%s", "<span class = \"comment\">");parts = text.split("\\*/", 2);text = parts[1];output.format("%s", parts[0].replaceAll("BLOCKCOMMENT", "/*") +"*/");output.format("%s", "</span>");continue;}else if (token.length() > 1 && token.matches("'\\w'*")) {output.format("%s", "<span class = \"literal\">");output.format("%s", token);output.format("%s", "</span>");}else if (token.startsWith("\"") && token.endsWith("\"") &&(token.length() > 1)) {output.format("%s", "<span class = \"literal\">" + token+ "</span>");}else if (token.startsWith("'") && token.endsWith("'") &&(token.length() > 1)) {output.format("%s", "<span class = \"literal\">" + token+ "</span>");}else if (token.equals("' '")) {output.format("%s", "<span class = \"literal\">" + token+ "</span>");}else if (token.startsWith("\"") && token.endsWith("\"") &&(token.length() == 1)) {if (stringToken) {output.format("%s", token + "</span>");stringToken = false;}else {output.format("%s", "<span class = \"literal\">" + token); stringToken = true;}}else if (token.startsWith("\"")) {output.format("%s", "<span class = \"literal\">" + token); stringToken = true;}else if (token.endsWith("\"") && (!token.endsWith("\\\""))) { output.format("%s", token);output.format("%s", "</span>");stringToken = false;}else if (token.matches("\\d+")) { // Check if numericoutput.format("%s", "<span class = \"literal\">" + token +"</span>");}else if (!stringToken && keywordSet.contains(token)) {output.format("%s", "<span class = \"keyword\">" + token +"</span>");}else {output.format("%s", token);}if (token.length() < text.length()) {if (text.charAt(token.length()) == '<')output.format("%s", "&lt;");else if (text.charAt(token.length()) == '>')output.format("%s", "&gt;");elseoutput.format("%s", text.charAt(token.length()));}if (parts.length == 2) {text = parts[1];}}}}21.6import java.util.*;public class Exercise21_06 {public static void main(String[] args) {// Create a tree map to hold words and key and count as value TreeMap<Integer, Integer> treeMap = new TreeMap<>();Scanner input = new Scanner(System.in);while (true) {// Enter an integerSystem.out.print("Enter an integer: ");int number = input.nextInt();if (number == 0) break;Integer key = new Integer(number);if (treeMap.get(key) != null) {int value = ((Integer)treeMap.get(key)).intValue();value++;treeMap.put(key, new Integer(value));}else {treeMap.put(key, new Integer(1));}}Integer max = Collections.max(treeMap.values());Set<Integer> keys = treeMap.keySet();Iterator<Integer> iterator = keys.iterator();while (iterator.hasNext()) {Object key = iterator.next();Integer value = (Integer)(treeMap.get(key));if (value.equals(max)) {System.out.println("Number " + key + " occurred most");}}}}21.7import java.util.*;public class Exercise21_07 {public static void main(String[] args) {// Text in a stringString text = "Have a good day. Have a good class. " + "Have a good visit. Have fun!";// Create a hash map to hold words and key and count as value HashMap<String, Integer> hashMap = new HashMap<>();String[] tokens = text.split("[ |.|!|?]");for (String key: tokens) {if (hashMap.get(key) != null) {hashMap.put(key, hashMap.get(key).intValue() + 1);}else {if (key.trim().length() > 0)hashMap.put(key, 1);}}// Get an entry set for the tree mapSet<Map.Entry<String, Integer>> entrySet = hashMap.entrySet();ArrayList<WordOccurrence> list = new ArrayList<>();for (Map.Entry<String, Integer> entry: entrySet) {list.add(new WordOccurrence(entry.getKey(), entry.getValue())); }Collections.sort(list);for (WordOccurrence item: list) {System.out.println(item);}}}class WordOccurrence implements Comparable<WordOccurrence> {String word;int count;public WordOccurrence(String word, int count) {this.word = word;this.count = count;}@Overridepublic int compareTo(WordOccurrence o) {return count - o.count;}@Overridepublic boolean equals(Object o) {return word.equals(((WordOccurrence)o).word);}@Overridepublic String toString() {return word + ": " + count;}}21.8import java.util.*;import java.io.*;public class Exercise21_08 {public static void main(String[] args) {if (args.length != 1) {System.out.println("Usage: java Exercise21_08 fullfilename");System.exit(1);}String filename = args[0];// Create a tree map to hold words as key and count as valueTreeMap<String, Integer> treeMap = new TreeMap<String, Integer>();try {Scanner input = new Scanner(new File(filename));while (input.hasNext()) {String line = input.nextLine();String[] words = line.split("[ @!~{}\\[\\]$#^&*\n\t\r.,;?'\")(]");for (int i = 0; i < words.length; i++) {if (words[i].trim().length() > 0 &&words[i].trim().matches("[A-Z|a-z]+")) {String key = words[i].toLowerCase();if (treeMap.get(key) != null) {int count = treeMap.get(key);count++;treeMap.put(key, count);}else {treeMap.put(key, 1);}}}}}catch (Exception ex) {ex.printStackTrace();}// Get an entry set for the tree mapSet<Map.Entry<String, Integer>> entrySet = treeMap.entrySet();// Display words in alphabetical orderSystem.out.println("\nDisplay words and their count in " + " ascending order of the words");for (Map.Entry<String, Integer> entry: entrySet)System.out.println(entry.getValue() + "\t" + entry.getKey()); }}21.9import java.util.*;public class Exercise21_09 {public static void main(String[] args) {String[][] stateCapital = {{"Alabama", "Montgomery"},{"Alaska", "Juneau"},{"Arizona", "Phoenix"},{"Arkansas", "Little Rock"},{"California", "Sacramento"},{"Colorado", "Denver"},{"Connecticut", "Hartford"},{"Delaware", "Dover"},{"Florida", "Tallahassee"},{"Georgia", "Atlanta"},{"Hawaii", "Honolulu"},{"Idaho", "Boise"},{"Illinois", "Springfield"},{"Indiana", "Indianapolis"},{"Iowa", "Des Moines"},{"Kansas", "Topeka"},{"Kentucky", "Frankfort"},{"Louisiana", "Baton Rouge"},{"Maine", "Augusta"},{"Maryland", "Annapolis"},{"Massachusettes", "Boston"},{"Michigan", "Lansing"},{"Minnesota", "Saint Paul"},{"Mississippi", "Jackson"},{"Missouri", "Jefferson City"},{"Montana", "Helena"},{"Nebraska", "Lincoln"},{"Nevada", "Carson City"},{"New Hampshire", "Concord"},{"New Jersey", "Trenton"},{"New York", "Albany"},{"New Mexico", "Santa Fe"},{"North Carolina", "Raleigh"},{"North Dakota", "Bismark"},{"Ohio", "Columbus"},{"Oklahoma", "Oklahoma City"},{"Oregon", "Salem"},{"Pennslyvania", "Harrisburg"},{"Rhode Island", "Providence"},{"South Carolina", "Columbia"},{"South Dakota", "Pierre"},{"Tennessee", "Nashville"},{"Texas", "Austin"},{"Utah", "Salt Lake City"},{"Vermont", "Montpelier"},{"Virginia", "Richmond"},{"Washington", "Olympia"},{"West Virginia", "Charleston"},{"Wisconsin", "Madison"},{"Wyoming", "Cheyenne"}};Map<String, String> map = new HashMap<String, String>();for (int i = 0; i < stateCapital.length; i++)map.put(stateCapital[i][0].toLowerCase(), stateCapital[i][1]);Scanner input = new Scanner(System.in);System.out.print("Enter a state: ");String state = input.nextLine().toLowerCase().trim();if (map.containsKey(state))System.out.println("The capital is " +map.get(state));elseSystem.out.println("No such state ");}}21.10import java.util.*;import java.io.*;public class Exercise21_10 {public static void main(String[] args) {// Prompt the user to enter a Java source fileScanner input = new Scanner(System.in);System.out.print("Enter a file name: ");String filename = input.nextLine();// Array of all Java keywords + true + nullString[] keywordString = { "abstract", "finally", "public", "boolean", "float", "return", "break", "for", "short", "byte", "goto", "static","case", "if", "super", "catch", "implements", "switch", "char","import", "synchronized", "class", "instanceof", "this", "const","int", "throw", "continue", "interface", "throws", "default", "long","transient", "do", "native", "try", "double", "new", "void", "else","package", "volatile", "extends", "private", "while", "final","protected", "true", "null" };Set<String> keywordSet = newHashSet<String>(Arrays.asList(keywordString));int count = 0;try {input = new Scanner(new File(filename));String text = "";while (input.hasNext()) {String line = input.nextLine();line = stripLineComments(line);line = stripLineStringLiterals(line);text += line + " ";}text = stripParagraghComments(text);TreeMap<String, Integer> map = new TreeMap<String, Integer>();String[] tokens = text.split("[ \\[,()\\]]");for (String token : tokens) {if (keywordSet.contains(token))if (map.get(token) == null) {map.put(token, 1);} else {int value = map.get(token);value++;map.put(token, value);}}// Get all entries into a setSet<Map.Entry<String, Integer>> entrySet = map.entrySet();// Get key and value from each entryfor (Map.Entry<String, Integer> entry: entrySet)System.out.println(entry.getValue() + "\t" + entry.getKey()); } catch (Exception ex) {ex.printStackTrace();}}/* Strip line comments */private static String stripLineComments(String line) {int index = line.indexOf("//");if (index < 0)return line;elsereturn line.substring(0, index);}/* Strip string literals */private static String stripLineStringLiterals(String line) {int start = line.indexOf("\"");int end = line.indexOf("\"", start + 1);while (start > 0 && end > 0) {line = line.substring(0, start) + line.substring(end + 1);start = line.indexOf("\"");end = line.indexOf("\"");}return line;}/* Strip paragraph comments */private static String stripParagraghComments(String text) {int start = text.indexOf("/*");int end = text.indexOf("*/");while (start > 0 && end > 0) {text = text.substring(0, start) + text.substring(end + 2);start = text.indexOf("/*");。

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

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

java语言程序设计课后习题答案Java语言程序设计课后习题答案Java语言是一种广泛应用于软件开发领域的编程语言,它具有简洁、可移植、面向对象等特点,因此在计算机科学与技术领域中得到了广泛的应用和推广。

学习Java语言程序设计是每个计算机科学与技术专业学生的必修课之一。

在学习过程中,老师通常会布置一些课后习题,以帮助学生巩固所学的知识。

本文将为大家提供一些Java语言程序设计课后习题的答案,希望对大家的学习有所帮助。

1. 编写一个Java程序,实现求阶乘的功能。

```javaimport java.util.Scanner;public class Factorial {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.print("请输入一个正整数:");int n = scanner.nextInt();int result = 1;for (int i = 1; i <= n; i++) {result *= i;}System.out.println(n + "的阶乘为:" + result);}```2. 编写一个Java程序,实现判断一个数是否为素数的功能。

```javaimport java.util.Scanner;public class PrimeNumber {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.print("请输入一个正整数:");int n = scanner.nextInt();boolean isPrime = true;for (int i = 2; i <= Math.sqrt(n); i++) {if (n % i == 0) {isPrime = false;break;}}if (isPrime) {System.out.println(n + "是素数");} else {System.out.println(n + "不是素数");}}```3. 编写一个Java程序,实现将一个字符串反转的功能。

自考04747《Java语言程序设计(一)》课后习题答案全集

自考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语言程序设计基础教程》习题解答

《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基础习题及答案

java基础习题及答案

程序设计—基础篇习题1.作图.2. 输出101--500之间的所有奇数,奇数之和.3. 输出100--200间不能被3整除的数.4. 输入初值,输出100个不能被3整除的数.5. 求S=1+(1+2)+(1+2+3)+...+(1+2+3+...+n)的值.6. 设S=1*2*3*...*n,求S不大于400000时的最大n.7. 设S=11*22*33*...*n n,求S不大于400000时的最大n.8. 找出1~1000间的全部”同构数”.如果一个数出现在其平方数右端,则称此数为同构数,如1在12=1的右端,5在52=25的右端,25在252=625的右端等.9. 百鸡问题。

“鸡翁一,值钱五,鸡母一,值钱三,鸡雏三,值钱一,百钱买百鸡,问鸡翁、鸡母、鸡雏各几何?”10.利用一维数组,统计一个班学生0-9,10-19,..90-99及100各分数段的人数.11.插入法排序.排序方法:设有10个数存放在数组A中,分别用A[1],A[2],..,A[10]表示.先将A[1]与A[2]比较,若A[2]<A[1],则交值这两个元素的值,A[1],A[2]顺序排列.再将A[3]与A[1],A[2]比较,按照顺序确定A[3]应放的位置,A[1],A[2],A[1]顺序排列.依次将后面的数一个一个拿来插入排好序的数列中,直到所有的数按顺序排好.12.2个按升序(从小到大)排列的数列A[1],A[2],....,A[N]和B[1],B[2],...,B[M]中各元素按其大小关系存放到数组c.同时必须注意对数组A或B残余元素的的追加处理。

13.运动员成绩排名.设有一表格记录了10人参加的男子100M决赛成绩,运动员号码和成绩自行确定,设计一程序,将给定的成绩排名输出。

14.知某班学生M(M<100)人,其N(N<4)门课程.度按平均成绩输出学生平均成绩名次表(要求每个学生的信息包括:名次,学号(用整型数),平均成绩等)。

《Java语言程序设计(基础篇)》(第10版梁勇著)第三章练习题答案

《Java语言程序设计(基础篇)》(第10版梁勇著)第三章练习题答案

《Java语言程序设计(基础篇)》(第10版梁勇著)第三章练习题答案《Java语言程序设计(基础篇)》(第10版梁勇著)第三章练习题答案3.1public class Exercise03_01 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter a, b, c: ");double a = input.nextDouble();double b = input.nextDouble();double c = input.nextDouble();double discriminant = b * b - 4 * a * c;if (discriminant < 0) {System.out.println("The equation has no real roots");}else if (discriminant == 0) {double r1 = -b / (2 * a);System.out.println("The equation has one root " + r1);}else { // (discriminant > 0)double r1 = (-b + Math.pow(discriminant, 0.5)) / (2 * a);double r2 = (-b - Math.pow(discriminant, 0.5)) / (2 * a);System.out.println("The equation has two roots " + r1 + " and " + r2);}}}3.1附加public class Exercise03_01Extra {public static void main(String args[]) {Scanner input = new Scanner(System.in);System.out.print("Enter a numerator: ");int numerator = input.nextInt();System.out.print("Enter a denominator: ");int denominator = input.nextInt();if (numerator < denominator) {System.out.println(numerator + " / " + denominator + " is a proper fraction");}else if (numerator % denominator == 0) {System.out.print(numerator + " / " + denominator + " is an improper fraction ");System.out.println("and it can be reduced to " + numerator / denominator);}else {System.out.print(numerator + " / " + denominator + " is an improper fraction ");System.out.println("and its mixed fraction is " + numerator / denominator + " + " +numerator % denominator + " / " + denominator);}}}3.2public class Exercise03_02 {public static void main(String[] args) {Scanner input = new Scanner(System.in);int number1 = (int)(System.currentTimeMillis() % 10);int number2 = (int)(System.currentTimeMillis() * 7 % 10);int number3 = (int)(System.currentTimeMillis() * 3 % 10);System.out.print("What is " + number1 + " + " + number2 + " + " +number3 + "? ");int answer = input.nextInt();System.out.println(number1 + " + " + number2 + " + " + number3 +" = " + answer + " is " +(number1 + number2 + number3 == answer));}}3.2附加public class Exercise03_02Extra {public static void main(String args[]) {Scanner input = new Scanner(System.in);System.out.print("Enter the coordinates for two points: ");double x1 = input.nextDouble();double y1 = input.nextDouble();double x2 = input.nextDouble();double y2 = input.nextDouble();double m = (y2 - y1) / (x2 - x1);double b = y1 - m * x1;System.out.print("The line equation for two points (" + x1 + ", " + y1 + ") and (" + x2 + ", " + y2 + ") is " + "y = ");if (m == -1)System.out.print("-x");else if (m == 1)System.out.print("x");elseSystem.out.print(m + "x");if (b > 0)System.out.println(" + " + b);else if (b < 0)System.out.println(" - " + (-1 * b));else// b is 0System.out.println();}}3.3public class Exercise03_03 {public static void main(String[] args) {Scanner input = new Scanner(System.in); System.out.print("Enter a, b, c, d, e, f: ");double a = input.nextDouble();double b = input.nextDouble();double c = input.nextDouble();double d = input.nextDouble();double e = input.nextDouble();double f = input.nextDouble();double detA = a * d - b * c;if (detA == 0) {System.out.println("The equation has no solution"); }else {double x = (e * d - b * f) / detA;double y = (a * f- e * c) / detA;System.out.println("x is " + x + " and y is " + y);}}}3.3附加public class Exercise03_03Extra {public static void main(String[] args) {final double RADIUS = 5;double angle = Math.random() * 2 * Math.PI;double x = RADIUS * Math.random() * Math.cos(angle);double y = RADIUS * Math.sin(angle);double distance = Math.pow(x * x + y * y, 0.5);System.out.println("The point is (" + x + ", " + y + ") and its distance to the center is " + distance);}}3.4public class Exercise03_04 {public static void main(String[] args) {int number = (int)(Math.random() * 12) + 1;// or int number = (int)(System.currentTimeMillis() % 12 + 1);// or int number = (int)(Math.random() * 12) + 1;if (number == 1)System.out.println("Month is Januaray");else if (number == 2)System.out.println("Month is Feburary");else if (number == 3)System.out.println("Month is March");else if (number == 4)System.out.println("Month is April");else if (number == 5)System.out.println("Month is May");else if (number == 6)System.out.println("Month is June");else if (number == 7)System.out.println("Month is July");else if (number == 8)System.out.println("Month is August");else if (number == 9)System.out.println("Month is September");else if (number == 10)System.out.println("Month is October");else if (number == 11)System.out.println("Month is November");else// if (number == 12)System.out.println("Month is December");}}3.5public class Exercise03_05 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Prompt the user to enter an integer for todaySystem.out.print("Enter today抯 day: ");int today = input.nextInt();System.out.print("Enter the number of days elapsed since today: ");int elapsedDays = input.nextInt();String nameForToday;if (today == 0)nameForToday = "Sunday";else if (today == 1)nameForToday = "Monday";else if (today == 2)nameForToday = "Tuesday";else if (today == 3)nameForToday = "Wednesday";else if (today == 4)nameForToday = "Thursday";else if (today == 5)nameForToday = "Friday";else// if (today == 6)nameForToday = "Saturday";int futureDay = (today + elapsedDays) % 7; String nameForFutureDay;if (futureDay == 0)nameForFutureDay = "Sunday";else if (futureDay == 1) nameForFutureDay = "Monday";else if (futureDay == 2) nameForFutureDay = "Tuesday";else if (futureDay == 3) nameForFutureDay = "Wednesday";else if (futureDay == 4) nameForFutureDay = "Thursday";else if (futureDay == 5) nameForFutureDay = "Friday";else// if (futureDay == 6) nameForFutureDay = "Saturday";System.out.println("Today is " + nameForToday+ " and the future day is " + nameForFutureDay); } }3.6public class Exercise03_06 {public static void main(String[] args) {Scanner input = new Scanner(System.in);// Prompt the user to enter weight in pounds System.out.print("Enter weight in pounds: "); double weight = input.nextDouble();// Prompt the user to enter heightSystem.out.print("Enter feet: ");double feet = input.nextDouble();System.out.print("Enter inches: ");double inches = input.nextDouble();double height = feet * 12 + inches;// Compute BMIdouble bmi = weight * 0.45359237 / ((height * 0.0254) * (height * 0.0254));// Display resultSystem.out.println("BMI is " + bmi);if (bmi < 18.5)System.out.println("Underweight");else if (bmi < 25)System.out.println("Normal");else if (bmi < 30)System.out.println("Overweight");elseSystem.out.println("Obese");}}3.7/** Break down an amount into smaller units* Display the non-zero denominations only, and display singular* words for single units like 1 dollars, 1 penny, and display plural * words for more than one unit like 2 dollars, 3 pennies.*/public class Exercise03_07 {// Main methodpublic static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Receive the amount entered from the keyboardSystem.out.print("Enter an amount in double, for example 11.56: ");double amount = input.nextDouble();int remainingAmount = (int)(amount * 100);// Find the number of one dollarsint numberOfOneDollars = remainingAmount / 100;remainingAmount = remainingAmount % 100;// Find the number of quarters in the remaining amountint numberOfQuarters = remainingAmount / 25;remainingAmount = remainingAmount % 25;// Find the number of dimes in the remaining amountint numberOfDimes = remainingAmount / 10;remainingAmount = remainingAmount % 10;// Find the number of nickels in the remaining amountint numberOfNickels = remainingAmount / 5;remainingAmount = remainingAmount % 5;// Find the number of pennies in the remaining amountint numberOfPennies = remainingAmount;// Display resultsif (amount < 0) {System.out.println("Your amount is negative");System.exit(1);}else if (amount < 0) {System.out.println("Your amount is zero");System.exit(2);}System.out.println("Your amount " + amount + " consists of ");if (numberOfOneDollars > 1)System.out.println(numberOfOneDollars + "\ dollars");else if (numberOfOneDollars == 1)System.out.println(numberOfOneDollars + "\ dollar");if (numberOfQuarters > 1)System.out.println(numberOfQuarters + "\ quarters");else if (numberOfQuarters == 1)System.out.println(numberOfQuarters + "\ quarter");if (numberOfDimes > 1)System.out.println(numberOfDimes + "\ dimes");else if (numberOfDimes == 1)System.out.println(numberOfDimes + "\ dime");if (numberOfNickels > 1)System.out.println(numberOfNickels + "\ nickels");else if (numberOfNickels == 1)System.out.println(numberOfNickels + "\ nickel");if (numberOfPennies > 1)System.out.println(numberOfPennies + "\ pennies");else if (numberOfPennies == 1)System.out.println(numberOfPennies + "\ penny");}}3.8public class Exercise03_08 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in); // Enter three numbersSystem.out.print("Enter three integers: ");int number1 = input.nextInt();int number2 = input.nextInt();int number3 = input.nextInt();if (number1 > number2) {int temp = number1;number1 = number2;number2 = temp;}if (number2 > number3) {int temp = number2;number2 = number3;number3 = temp;}if (number1 > number2) {int temp = number1;number1 = number2;number2 = temp;}System.out.println("The sorted numbers are "+ number1 + " " + number2 + " " + number3);}}public class Exercise03_09 {public static void main(String[] args) {Scanner input = new Scanner(System.in);// Prompt the user to enter an integerSystem.out.print("Enter the first 9 digits of an ISBN as integer: ");int number = input.nextInt();// Calculate checksum (You may write a loop to simplify it in Ch4int checksum =((number / 100000000 % 10) * 1 +(number / 10000000 % 10) * 2 +(number / 1000000 % 10) * 3 +(number / 100000 % 10) * 4 +(number / 10000 % 10) * 5 +(number / 1000 % 10) * 6 +(number / 100 % 10) * 7 +(number / 10 % 10) * 8 +(number % 10) * 9) % 11;System.out.print("The ISBN-10 number is ");// Display leading zeros, improve the solution using loops in the next chapterif (number / 100000000 == 0) {System.out.print("0");if (number / 10000000 == 0) {System.out.print("0");if (number / 1000000 == 0) {System.out.print("0");if (number / 100000 == 0) {System.out.print("0");if (number / 10000 == 0) { System.out.print("0");if (number / 1000 == 0) { System.out.print("0");if (number / 100 == 0) {System.out.print("0");if (number / 10 == 0) {System.out.print("0");if (number == 0) {System.out.print("0");}}}}}}}}}System.out.print(number);if (checksum == 10)System.out.print("X");elseSystem.out.print(checksum);}}3.10public class Exercise03_10 {public static void main(String[] args) {// 1. Generate two random single-digit integersint number1 = (int)(Math.random() * 10);int number2 = (int)(Math.random() * 10);// 2. Prompt the student to answer 搘hat is number1 + number2?? System.out.print("What is " + number1 + " + " + number2 + "? "); Scanner input = new Scanner(System.in);int answer = input.nextInt();// 4. Grade the answer and display the resultString replyString;if (number1 + number2 == answer)replyString = "You are correct!";elsereplyString = "Your answer is wrong.\" + number1 + " + "+ number2 + " should be " + (number1 + number2);System.out.println(replyString);}}3.11public class Exercise03_11 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Prompt the user to enter inputSystem.out.print("Enter a month in the year (e.g., 1 for Jan): ");int month = input.nextInt();System.out.print("Enter a year: ");int year = input.nextInt();int numberOfDaysInMonth = 0;switch (month) {case 1:System.out.print("January " + year);numberOfDaysInMonth = 31;break;case 2:System.out.print("February " + year);if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) { numberOfDaysInMonth = 29;}else {numberOfDaysInMonth = 28;}break;case 3:System.out.print("March " + year);numberOfDaysInMonth = 31;break;case 4:System.out.print("April " + year);numberOfDaysInMonth = 30;break;case 5:System.out.print("May " + year);numberOfDaysInMonth = 31;break;case 6:System.out.print("June " + year);numberOfDaysInMonth = 30;break;case 7:System.out.print("July " + year);numberOfDaysInMonth = 31;break;case 8:System.out.print("August " + year);numberOfDaysInMonth = 31;break;case 9:System.out.print("September " + year);numberOfDaysInMonth = 30;break;case 10:System.out.print("October " + year);numberOfDaysInMonth = 31;break;case 11:System.out.print("November " + year);numberOfDaysInMonth = 30;break;case 12:System.out.print("December " + year);numberOfDaysInMonth = 31;break;}System.out.print(" has " + numberOfDaysInMonth + " days"); }}3.12public class Exercise03_12 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter a three-digit integer: ");int number = input.nextInt();if (number / 100 == number % 10)System.out.println(number + " is a palindrome");elseSystem.out.println(number + " is not a palindrome");}}3.13public class Exercise03_13 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Prompt the user to enter filing statusSystem.out.print("(0-single filer, 1-married jointly or qualifying widow(er),"+ "\2-married separately, 3-head of household)\" + "Enter the filing status: ");int status = input.nextInt();// Prompt the user to enter taxable incomeSystem.out.print("Enter the taxable income: ");double income = input.nextDouble();// Compute taxdouble tax = 0;if (status == 0) { // Compute tax for single filersif (income <= 8350) {tax = income * 0.10;} else if (income <= 33950) {tax = 8350 * 0.10 + (income - 8350) * 0.15;} else if (income <= 82250) {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (income - 33950)* 0.25; } else if (income <= 171550) {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (82250 - 33950) * 0.25 + (income - 82250) * 0.28;} else if (income <= 372950) {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (82250 - 33950) * 0.25 + (171550 - 82250) * 0.28 + (income - 171550) * 0.33;} else {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (82250 - 33950) * 0.25 + (171550 - 82250) * 0.28 + (372950 - 171550) * 0.33 + (income - 372950) * 0.35;}} else if (status == 1) { // Compute tax for married file jointly if (income <= 16700) {tax = income * 0.10;} else if (income <= 67900) {tax = 16700 * 0.10 + (income - 16700) * 0.15;} else if (income <= 137050) {tax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (income - 67900) * 0.25; } else if (income <= 208850) {tax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (137050 - 67900) * 0.25 + (income - 137050) * 0.28;} else if (income <= 372950) {tax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (137050 - 67900) * 0.25 + (208850 - 137050) * 0.28 + (income - 208850) * 0.33;} else {tax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (137050 - 67900) * 0.25 + (171950 - 137050) * 0.28 + (372950 - 208850) * 0.33+ (income - 372950) * 0.35;}} else if (status == 2) { // Compute tax for married separately if (income <= 8350) {tax = income * 0.10;} else if (income <= 33950) {tax = 8350 * 0.10 + (income - 8350) * 0.15;} else if (income <= 68525) {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (income - 33950) * 0.25; } else if (income <= 104425) {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (68525 - 33950) * 0.25 + (income - 68525) * 0.28;} else if (income <= 186475) {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (68525 - 33950) * 0.25 + (104425 - 68525) * 0.28 + (income - 104425) * 0.33;} else {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (68525 - 33950) * 0.25 + (104425 - 68525) * 0.28 + (186475 - 104425) * 0.33 + (income - 186475) * 0.35;}} else if (status == 3) { // Compute tax for head of household if (income <= 11950) {tax = income * 0.10;} else if (income <= 45500) {tax = 11950 * 0.10 + (income - 11950) * 0.15;} else if (income <= 117450) {tax = 11950 * 0.10 + (45500 - 11950) * 0.15 + (income - 45500) * 0.25; } else if (income <= 190200) {tax = 11950 * 0.10 + (45500 - 11950) * 0.15 + (117450 - 45500) * 0.25 + (income - 117450) * 0.28;} else if (income <= 372950) {tax = 11950 * 0.10 + (45500 - 11950) * 0.15 + (117450 - 45500) * 0.25 + (190200 - 117450) * 0.28 + (income - 190200) * 0.33;} else {tax = 11950 * 0.10 + (45500 - 11950) * 0.15 + (117450 - 45500) * 0.25 + (190200 - 117450) * 0.28 + (372950 - 190200) * 0.33+ (income - 372950) * 0.35;}} else {System.out.println("Error: Wrong filing status");System.exit(1);}// Display the resultSystem.out.println("Tax is " + (int) (tax * 100) / 100.0);}}3.14public class Exercise03_14 {public static void main(String[] args) {// Obtain the random number 0 or 1int number = (int)(Math.random() * 2);// Prompt the user to enter a guessjava.util.Scanner input = new java.util.Scanner(System.in);System.out.print("Guess head or tail? " +"Enter 0 for head and 1 for tail: ");int guess = input.nextInt();// Check the guessif (guess == number)System.out.println("Correct guess");else if (number == 0)System.out.println("Sorry, it is a head");elseSystem.out.println("Sorry, it is a tail");}}3.15public class Exercise03_15 {public static void main(String[] args) {// Generate a lotteryint lottery = (int)(Math.random() * 1000);// Prompt the user to enter a guessjava.util.Scanner input = new java.util.Scanner(System.in); System.out.print("Enter your lottery pick (three digits): ");int guess = input.nextInt();// Get digitsint l1 = lottery / 100;int l2 = (lottery % 100) / 10; // l2 = (lottery / 10) % 10int l3 = lottery % 10;int g1 = guess / 100;int g2 = (guess % 100) / 10;int g3 = guess % 10;System.out.println("Lottery is " + lottery);// Check the guessif (guess == lottery)System.out.println("Exact match: you win $10,000");else if (g1 == l1 && g3 == l2 && g2 == l3 ||g2 == l1 && g1 == l2 && g3 == l3 ||g2 == l1 && g3 == l2 && g1 == l3 ||g3 == l1 && g1 == l2 && g2 == l3 ||g3 == l1 && g2 == l2 && g1 == l3)System.out.println("Match all digits: you win $3,000"); else if (g1 == l1 || g1 == l2 || g1 == l3 ||g2 == l1 || g2 == l2 || g2 == l3 ||g3 == l1 || g3 == l2 || g3 == l3)System.out.println("Match one digit: you win $1,000"); elseSystem.out.println("Sorry, no match");}}3.16public class Exercise03_16 {public static void main(String[] args) {double x = Math.random() * 100 - 50;double y = Math.random() * 200 - 100;System.out.println(x + ", " + y);}}3.17public class Exercise03_17 {public static void main(String[] args) {// Generate scissor, rock, paperint computerNumber = (int)(Math.random() * 3);// Prompt the user to enter scissor, rock, or paper java.util.Scanner input = new java.util.Scanner(System.in); System.out.print("scissor (0), rock (1), paper (2): ");int userNumber = input.nextInt();// Check the guessswitch (computerNumber) {case 0:if (userNumber == 0)System.out.print("The computer is scissor. You are scissor too. It is a draw");else if (userNumber == 1)System.out.print("The computer is scissor. You are rock. You won");else if (userNumber == 2)System.out.print("The computer is scissor. You are paper. You lost");break;case 1:if (userNumber == 0)System.out.print("The computer is rock. You are scissor. You lost");else if (userNumber == 1)System.out.print("The computer is rock. You are rock too. It is a draw");else if (userNumber == 2)System.out.print("The computer is rock. You are paper. You won");break;case 2:if (userNumber == 0)System.out.print("The computer is paper. You are scissor. You won");else if (userNumber == 1)System.out.print("The computer is paper. You are rock. You lost");else if (userNumber == 2)System.out.print("The computer is paper. You are paper too.It is a draw");break;}}}3.18public class Exercise03_18 {public static void main(String args[]) {Scanner input = new Scanner(System.in);System.out.print("Enter package weight: ");double w = input.nextDouble();if (w <= 1) {System.out.println("The shipping cost is $3.5");}else if (w <= 3) {System.out.println("The shipping cost is $5.5");}else if (w <= 10) {System.out.println("The shipping cost is $8.5");}else if (w <= 20) {System.out.println("The shipping cost is $10.5");}else {System.out.println("The package cannot be shipped");}}}3.19public class Exercise03_19 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in); // Enter three edgesSystem.out.print("Enter three edges (length in double): ");double edge1 = input.nextDouble();double edge2 = input.nextDouble();double edge3 = input.nextDouble();。

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

《Java语言程序设计(基础篇)》(第10版梁勇著)第三十五章练习题答案35.1import javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import bel;import javafx.scene.control.TextField;import javafx.stage.Stage;import java.sql.*;import javafx.application.Platform;import javafx.collections.FXCollections;import javafx.geometry.HPos;import javafx.geometry.Pos;import boBox;import javafx.scene.control.PasswordField;import javafx.scene.control.TextArea;import yout.BorderPane;import yout.GridPane;import yout.HBox;public class Exercise35_01 extends Application {private DBConnectionPane dBConnectionPane= new DBConnectionPane();private Label lblConnectionStatus= new Label("No connection now");private TextArea taDisplay = new TextArea();@Override // Override the start method in the Application class public void start(Stage primaryStage) {Button btBatchUpdate = new Button("Batch Update");Button btNonBatchUpdate = new Button("Non-Batch Update");HBox hBoxButtons = new HBox(10);hBoxButtons.getChildren().addAll(btBatchUpdate,btNonBatchUpdate);hBoxButtons.setAlignment(Pos.CENTER);BorderPane borderPaneConnect = new BorderPane();Button btConnectDB = new Button("Connect to Database");borderPaneConnect.setCenter(lblConnectionStatus);borderPaneConnect.setRight(btConnectDB);BorderPane pane = new BorderPane();pane.setTop(borderPaneConnect);pane.setBottom(hBoxButtons);pane.setCenter(taDisplay);// Create a scene and place it in the stageScene scene = new Scene(pane, 320, 350);primaryStage.setTitle("Exercise35_01"); // Set the stage titleprimaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stagebtConnectDB.setOnAction(e -> openDialog());btBatchUpdate.setOnAction(e -> {if (dBConnectionPane.getConnection() == null) {taDisplay.setText("Please connect to the database first");return;}new Thread(() -> batchUpdate()).start();});btNonBatchUpdate.setOnAction(e -> {if (dBConnectionPane.getConnection() == null) {taDisplay.setText("Please connect to the database first");return;}new Thread(() -> nonBatchUpdate()).start();});}private void openDialog() {BorderPane pane = new BorderPane();pane.setCenter(dBConnectionPane);Button btCloseDialog = new Button("Close Dialog");pane.setBottom(btCloseDialog);BorderPane.setAlignment(btCloseDialog, Pos.CENTER);Stage stage = new Stage();stage.setScene(new Scene(pane, 420, 180)); // Place the scene in the stage stage.setTitle("Connect to DB");stage.show(); // Display the stagebtCloseDialog.setOnAction(e -> {stage.hide();if (dBConnectionPane.getConnection() != null)lblConnectionStatus.setText("DB connected");});}private void nonBatchUpdate() {try {// Create the tableStatement statement =dBConnectionPane.getConnection().createStatement();statement.executeUpdate("drop table Temp");statement.executeUpdate("CREATE TABLE TEMP(NUM1 double, NUM2 double, NUM3 double)");long startTime = System.currentTimeMillis();for (int i = 1; i <= 5000; i++) {statement.executeUpdate("INSERT INTO TEMP VALUES(" +Math.random() * 1000 + ", " + Math.random() * 1000 + ", " + Math.random() + ")");}long endTime = System.currentTimeMillis();Platform.runLater(() -> {taDisplay.appendText("Non-batch update completed\n");taDisplay.appendText("The elapsed time is " +(endTime - startTime) + "\n");lblConnectionStatus.setText("Non-batch update succeeded");});}catch (Exception ex) {ex.printStackTrace();}}private void batchUpdate() {if (dBConnectionPane.getConnection() != null) {try {// Create the tableStatement statement =dBConnectionPane.getConnection().createStatement();statement.executeUpdate("drop table Temp");statement.executeUpdate("CREATE TABLE TEMP(NUM1 double, NUM2 double, NUM3 double)");long startTime = System.currentTimeMillis();for (int i = 1; i <= 5000; i++) {statement.addBatch("INSERT INTO TEMP VALUES(" +Math.random()*1000 + ", " + Math.random()*1000 + ", " + Math.random() + ")");}statement.executeBatch();long endTime = System.currentTimeMillis();Platform.runLater(() -> {taDisplay.appendText("Batch update completed\n");taDisplay.appendText("The elapsed time is " +(endTime - startTime) + "\n");lblConnectionStatus.setText("Batch update succeeded");});}catch (Exception ex) {ex.printStackTrace();}}}/*** 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 DBConnectionPane extends BorderPane {private Connection connection;private Label lblConnectionStatus = new Label("No connection");private Button btConnect = new Button("Connect to DB");private ComboBox<String> cboDriver = new ComboBox<>(FXCollections.observableArrayList("com.mysql.jdbc.Driver", "sun.jdbc.odbc.JdbcOdbcDriver","oracle.jdbc.driver.OracleDriver"));private ComboBox<String> cboURL = new ComboBox<>(FXCollections.observableArrayList("jdbc:mysql://localhost/javabook","jdbc:odbc:exampleMDBDataSource","jdbc:oracle:thin:@:1521:ora9i"));private TextField tfUsername = new TextField();private PasswordField pfPassword = new PasswordField();/** Creates new form DBConnectionPanel */public DBConnectionPane() {cboDriver.setEditable(true);cboURL.setEditable(true);GridPane gridPane = new GridPane();gridPane.add(new Label("JDBC Drive"), 0, 0);gridPane.add(new Label("Database URL"), 0, 1);gridPane.add(new Label("Username"), 0, 2);gridPane.add(new Label("Password"), 0, 3);gridPane.add(cboDriver, 1, 0);cboDriver.setPrefWidth(350);cboDriver.getSelectionModel().selectFirst();gridPane.add(cboURL, 1, 1);cboURL.getSelectionModel().selectFirst();gridPane.add(tfUsername, 1, 2);gridPane.add(pfPassword, 1, 3);gridPane.add(btConnect, 1, 4);GridPane.setHalignment(btConnect, HPos.RIGHT);this.setTop(lblConnectionStatus);this.setCenter(gridPane);btConnect.setOnAction(e -> connectDB());}private void connectDB() {// Get database information from the user inputString driver = cboDriver.getValue();String url = cboURL.getValue();String username = tfUsername.getText().trim();String password = new String(pfPassword.getText());// Connection to the databasetry {Class.forName(driver);connection = DriverManager.getConnection(url, username, password);lblConnectionStatus.setText("Connected to " + url); }catch (ng.Exception ex) {ex.printStackTrace();}}/** Return connection */public Connection getConnection() {return connection;}}}35.2import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.Button;import bel;import javafx.scene.control.TextField;import yout.BorderPane;import yout.HBox;import yout.VBox;import javafx.stage.Stage;public class Exercise35_02 extends Application {private Button btFirst = new Button("First");private Button btNext = new Button("Next");private Button btPrior = new Button("Prior");private Button btLast = new Button("Last");private Button btInsert = new Button("Insert");private Button btDelete = new Button("Delete");private Button btUpdate = new Button("Update");private TextField tfLastName = new TextField();private TextField tfFirstName = new TextField();private TextField tfMi = new TextField();private TextField tfStreet = new TextField();private TextField tfCity = new TextField();private TextField tfState = new TextField();private TextField tfZip = new TextField();private TextField tfTelephone = new TextField();private TextField tfEmail = new TextField();private Label lblStatus = new Label();// Result setprivate ResultSet resultSet;// Current row numberprivate int currentRowNumber;@Override // Override the start method in the Application class public void start(Stage primaryStage) {VBox vBox = new VBox(5);HBox hBox2 = new HBox(5);hBox2.getChildren().addAll(new Label("Last Name"), tfLastName, new Label("First Name"), tfFirstName, new Label("MI"), tfMi); tfLastName.setPrefColumnCount(8);tfFirstName.setPrefColumnCount(8);tfMi.setPrefColumnCount(1);HBox hBox3 = new HBox(5);hBox3.getChildren().addAll(new Label("Street"), tfStreet);HBox hBox4 = new HBox(5);hBox4.getChildren().addAll(new Label("City"), tfCity, new Label("State"), tfState, new Label("ZIP"), tfZip);tfState.setPrefColumnCount(2);tfZip.setPrefColumnCount(5);HBox hBox5 = new HBox(5);hBox5.getChildren().addAll(new Label("Telephone"), tfTelephone);HBox hBox1 = new HBox(5);hBox1.getChildren().addAll(new Label("Email"), tfEmail);vBox.getChildren().addAll(hBox2, hBox3, hBox4, hBox5, hBox1);HBox hBox = new HBox(5);hBox.getChildren().addAll(btFirst, btNext, btPrior, btLast,btInsert, btDelete, btUpdate);hBox.setAlignment(Pos.CENTER);BorderPane pane = new BorderPane();pane.setTop(hBox);pane.setCenter(vBox);pane.setBottom(lblStatus);// Create a scene and place it in the stageScene scene = new Scene(pane, 450, 200);primaryStage.setTitle("Exercise35_02"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stageinitializeDB();btFirst.setOnAction(e -> first());btNext.setOnAction(e -> next());btPrior.setOnAction(e -> previous());btLast.setOnAction(e -> last());btInsert.setOnAction(e -> insert());btUpdate.setOnAction(e -> updateRecord());btDelete.setOnAction(e -> clear());}private void first() {try {if (resultSet.first())showRecord();elselblStatus.setText("There is no row in the result set"); }catch (Exception ex) {lblStatus.setText(ex.toString());}}private void next() {try {if (resultSet.isLast())lblStatus.setText("This is already the last row");else {resultSet.next();showRecord();}}catch (Exception ex) {lblStatus.setText(ex.toString());}}private void previous() {try {if (resultSet.isFirst())lblStatus.setText("This is already the first row");else {resultSet.previous();showRecord();}}catch (Exception ex) {lblStatus.setText(ex.toString());}}private void last() {try {if (resultSet.isLast())lblStatus.setText("This is already the last row");else {st();showRecord();}}catch (Exception ex) {lblStatus.setText(ex.toString());}}/**Initialize the database connection, create statement, and result set */ private void initializeDB() {try {// Load the driverClass.forName("com.mysql.jdbc.Driver");System.out.println("Driver loaded");// Connect to the local InterBase databaseConnection connection = DriverManager.getConnection// ("dbc:odbc:exampleMDBDataSource", "", "" );("jdbc:mysql://localhost/javabook", "scott", "tiger");System.out.println("Database connected");// Create a statementStatement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);// Get result setresultSet = statement.executeQuery("select * from Address");// Show the first record in the result setresultSet.first();showRecord();}catch (Exception ex) {lblStatus.setText(ex.toString());}}/**Load the record into text fields*/private void loadToTextField(ResultSet rs) throws SQLException { if (rs.next()) {tfLastName.setText(rs.getString(2));tfFirstName.setText(rs.getString(3));tfMi.setText(rs.getString(4));tfStreet.setText(rs.getString(5));tfCity.setText(rs.getString(6));tfState.setText(rs.getString(7));tfTelephone.setText(rs.getString(8));lblStatus.setText("Record found");}elselblStatus.setText("Record not found");}/**Delete text fields*/private void clear() {tfEmail.setText(null);tfLastName.setText(null);tfFirstName.setText(null);tfMi.setText(null);tfStreet.setText(null);tfCity.setText(null);tfState.setText(null);tfTelephone.setText(null);}private void showRecord() throws Exception {tfFirstName.setText(resultSet.getString("firstName"));tfLastName.setText(resultSet.getString("lastName"));tfMi.setText(resultSet.getString("mi"));tfStreet.setText(resultSet.getString("Street"));tfCity.setText(resultSet.getString("City"));tfState.setText(resultSet.getString("State"));tfTelephone.setText(resultSet.getString("Telephone"));tfZip.setText(resultSet.getString("zip"));tfEmail.setText(resultSet.getString("email"));currentRowNumber = resultSet.getRow();lblStatus.setText("Current row number: " + currentRowNumber); }/**Insert a new record to the database*/private void insert() {try {// Update the fieldsupdateRecord();// Insert the rowresultSet.insertRow();// Move the cursor back to the position before the insertion resultSet.moveToCurrentRow();lblStatus.setText("Inserstion succeeded");}catch (SQLException ex) {ex.printStackTrace();}}/**Update fields in the record*/protected void updateRecord() {try {// Gather data from the UI and update the database fieldsresultSet.updateString("firstName",tfFirstName.getText().trim());resultSet.updateString("MI", tfMi.getText().trim());resultSet.updateString("lastName", tfLastName.getText().trim()); resultSet.updateString("Street", tfStreet.getText().trim());resultSet.updateString("City", tfCity.getText().trim());resultSet.updateString("zip", tfZip.getText().trim());resultSet.updateString("Telephone", tfTelephone.getText().trim()); resultSet.updateString("email", tfEmail.getText().trim());lblStatus.setText("Update succeeded");}catch (SQLException ex) {ex.printStackTrace();}}private void delete() {try {resultSet.deleteRow();lblStatus.setText("Deletion succeeded");}catch (Exception ex) {lblStatus.setText(ex.toString());}}/*** The main method is only needed for the EmailE with limited* avaFX support. Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}35.3import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import javafx.application.Application;import javafx.beans.property.SimpleStringProperty;import javafx.beans.value.ObservableValue;import javafx.collections.FXCollections;import javafx.collections.ObservableList;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.Button;import bel;import javafx.scene.control.TextField;import javafx.stage.Stage;import javafx.scene.control.ScrollPane;import javafx.scene.control.TableColumn;import javafx.scene.control.TableColumn.CellDataFeatures;import javafx.scene.control.TableView;import yout.BorderPane;import yout.HBox;import javafx.util.Callback;public class Exercise35_03 extends Application {private TextField tfTableName = new TextField();private TableView tableView = new TableView();private Button btShowContents = new Button("Show Contents"); private Label lblStatus = new Label();// Statement for executing queriesprivate Statement stmt;@Override // Override the start method in the Application class public void start(Stage primaryStage) {HBox hBox = new HBox(5);hBox.getChildren().addAll(new Label("Table Name"), tfTableName, btShowContents);hBox.setAlignment(Pos.CENTER);BorderPane pane = new BorderPane();pane.setCenter(tableView);pane.setTop(hBox);pane.setBottom(lblStatus);// Create a scene and place it in the stageScene scene = new Scene(pane, 420, 180);primaryStage.setTitle("Exercise35_03"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stageinitializeDB();btShowContents.setOnAction(e -> showContents());}private void initializeDB() {try {// Load the JDBC driverClass.forName("com.mysql.jdbc.Driver");System.out.println("Driver loaded");// Establish a connectionConnection connection =DriverManager.getConnection("jdbc:mysql://localhost/javabook", "scott", "tiger");// ("jdbc:oracle:thin:@:1521:ora9i",// "scott", "tiger");System.out.println("Database connected");// Create a statementstmt = connection.createStatement();} catch (Exception ex) {ex.printStackTrace();}}private void showContents() {String tableName = tfTableName.getText();try {String queryString = "select * from " + tableName;ResultSet resultSet = stmt.executeQuery(queryString);populateTableView(resultSet, tableView);} catch (SQLException ex) {ex.printStackTrace();}}private void populateTableView(ResultSet rs, TableView tableView) { ObservableList<ObservableList> data =FXCollections.observableArrayList();try {/*** ********************************* TABLE COLUMN ADDED DYNAMICALLY * *********************************/for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {//We are using non property style for making dynamic tablefinal int j = i;TableColumn col = new TableColumn(rs.getMetaData().getColumnName(i + 1));//col.setCellValueFactory(TextFieldTableCell.forTableColumn());col.setCellValueFactory(new Callback<CellDataFeatures<ObservableList, String>, ObservableValue<String>>() {public ObservableValue<String>call(CellDataFeatures<ObservableList, String> param) {if (param == null || param.getValue() == null ||param.getValue().get(j) == null) {return null;}return newSimpleStringProperty(param.getValue().get(j).toString());}});tableView.getColumns().addAll(col);System.out.println("Column [" + i + "] ");}/*** ******************************* Data added to ObservableList * *******************************/while (rs.next()) {//Iterate RowObservableList<String> row = FXCollections.observableArrayList();for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {//Iterate Columnrow.add(rs.getString(i));}System.out.println("Row [1] added " + row);data.add(row);}//FINALLY ADDED TO TableViewtableView.setItems(data);} catch (Exception e) {e.printStackTrace();System.out.println("Error on Building Data");}}/*** 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);}}35.4import java.sql.Connection;import java.sql.DatabaseMetaData;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import javafx.application.Application;import javafx.beans.property.SimpleStringProperty;import javafx.beans.value.ObservableValue;import javafx.collections.FXCollections;import javafx.collections.ObservableList;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.Button;import boBox;import bel;import javafx.stage.Stage;import javafx.scene.control.ScrollPane;import javafx.scene.control.TableColumn;import javafx.scene.control.TableColumn.CellDataFeatures;import javafx.scene.control.TableView;import yout.BorderPane;import yout.HBox;import javafx.util.Callback;public class Exercise35_04 extends Application {private ComboBox<String> cboTableName = new ComboBox<>(); private TableView tableView = new TableView();private Button btShowContents = new Button("Show Contents"); private Label lblStatus = new Label();// Statement for executing queriesprivate Statement stmt;@Override // Override the start method in the Application class public void start(Stage primaryStage) {HBox hBox = new HBox(5);hBox.getChildren().addAll(new Label("Table Name"),cboTableName, btShowContents);hBox.setAlignment(Pos.CENTER);BorderPane pane = new BorderPane();pane.setCenter(tableView);pane.setTop(hBox);pane.setBottom(lblStatus);// Create a scene and place it in the stageScene scene = new Scene(pane, 420, 180);primaryStage.setTitle("Exercise35_04"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stageinitializeDB();btShowContents.setOnAction(e -> showContents());}private void initializeDB() {try {// Load the JDBC driverClass.forName("com.mysql.jdbc.Driver");System.out.println("Driver loaded");// Establish a connectionConnection connection = DriverManager.getConnection("jdbc:mysql://localhost/javabook", "scott", "tiger");// ("jdbc:oracle:thin:@:1521:ora9i",// "scott", "tiger");System.out.println("Database connected");// Create a statementstmt = connection.createStatement();DatabaseMetaData dbMetaData = connection.getMetaData();ResultSet rsTables = dbMetaData.getTables(null, null, null,new String[] {"TABLE"}); System.out.print("User tables: ");while (rsTables.next()) {cboTableName.getItems().add(rsTables.getString("TABLE_NAME"));}cboTableName.getSelectionModel().selectFirst();}catch (Exception ex) {ex.printStackTrace();}}private void showContents() {String tableName = cboTableName.getValue();try {String queryString = "select * from " + tableName;ResultSet resultSet = stmt.executeQuery(queryString);populateTableView(resultSet, tableView);} catch (SQLException ex) {ex.printStackTrace();}}private void populateTableView(ResultSet rs, TableView tableView) {ObservableList<ObservableList> data =FXCollections.observableArrayList();try {/*** ********************************* TABLE COLUMN ADDED DYNAMICALLY * ******************************** */for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {//We are using non property style for making dynamic tablefinal int j = i;TableColumn col = new TableColumn(rs.getMetaData().getColumnName(i + 1));//col.setCellValueFactory(TextFieldTableCell.forTableColumn());col.setCellValueFactory(new Callback<CellDataFeatures<ObservableList, String>, ObservableValue<String>>() {public ObservableValue<String>call(CellDataFeatures<ObservableList, String> param) {if (param == null || param.getValue() == null ||param.getValue().get(j) == null) {return null;}return newSimpleStringProperty(param.getValue().get(j).toString());}});tableView.getColumns().addAll(col);System.out.println("Column [" + i + "] ");}/*** ******************************* Data added to ObservableList * *******************************/while (rs.next()) {//Iterate RowObservableList<String> row = FXCollections.observableArrayList();for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {//Iterate Columnrow.add(rs.getString(i));}System.out.println("Row [1] added " + row);data.add(row);}//FINALLY ADDED TO TableViewtableView.setItems(data);} catch (Exception e) {e.printStackTrace();System.out.println("Error on Building Data");}}/*** 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);}}35.5import java.sql.*;import javafx.application.Application;import javafx.beans.property.SimpleStringProperty;import javafx.beans.value.ObservableValue;import javafx.collections.FXCollections;import javafx.collections.ObservableList;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.Button;import boBox;import bel;import javafx.scene.control.PasswordField;import javafx.scene.control.ScrollPane;import javafx.scene.control.TableColumn;import javafx.scene.control.TableColumn.CellDataFeatures;import javafx.scene.control.TableView;import javafx.scene.control.TextArea;import javafx.scene.control.TextField;import yout.BorderPane;import yout.GridPane;import yout.HBox;import yout.VBox;import javafx.stage.Stage;import javafx.util.Callback;public class Exercise35_05 extends Application {// Connection to the databaseprivate Connection connection;// Statement to execute SQL commandsprivate Statement statement;// Text area to enter SQL commandsprivate TextArea tasqlCommand = new TextArea();// Text area to display results from SQL commandsprivate TextArea taSQLResult = new TextArea();// Table view to display results from SQL commandsprivate TableView tableView = new TableView();// DBC info for a database connectionprivate TextField tfUsername = new TextField();private PasswordField pfPassword = new PasswordField();private ComboBox<String> cboURL = new ComboBox<>();private ComboBox<String> cboDriver = new ComboBox<>();private Button btExecuteSQL = new Button("Execute SQL Command"); private Button btClearSQLCommand = new Button("Clear");private Button btConnectDB = new Button("Connect to Database"); private Button btClearSQLResult = new Button("Clear Result"); private Label lblConnectionStatus= new Label("No connection now");private BorderPane borderPaneExecutionResult = new BorderPane();@Override // Override the start method in the Application class public void start(Stage primaryStage) {cboURL.getItems().addAll(FXCollections.observableArrayList( "jdbc:mysql://localhost/javabook","jdbc:mysql:///javabook","jdbc:odbc:exampleMDBDataSource","jdbc:oracle:thin:@:1521:orcl"));cboURL.getSelectionModel().selectFirst();cboDriver.getItems().addAll(FXCollections.observableArrayList( "com.mysql.jdbc.Driver", "sun.jdbc.odbc.dbcOdbcDriver","oracle.jdbc.driver.OracleDriver"));cboDriver.getSelectionModel().selectFirst();// Create UI for connecting to the database。

相关文档
最新文档