Java语言程序设计(郑莉)第六章课后习题答案
- 格式:docx
- 大小:332.30 KB
- 文档页数:20
Java语言程序设计第六章课后习题答案1.将本章例6-1至6-18中出现的文件的构造方法均改为使用File类对象作为参数实现。
个人理解:File类只能对整文件性质进行处理,而没法通过自己直接使用file.Read()或者是file.write()类似方法对文件内容进行写或者读取。
注意:是直接;下面只提供一个例2变化,其他的你自己做,10几道啊,出这题的人真他妈有病。
import java.io.*;public class test6_2{public static void main(String[] args) throws IOException { String fileName = "D:\\Hello.txt";File writer=new File(fileName);writer.createNewFile();BufferedWriter input = new BufferedWriter(newFileWriter(writer));input.write("Hello !\n");input.write("this is my first text file,\n");input.write("你还好吗?\n");input.close();}}运行结果:(电脑系统问题,没法换行,所以一般使用BuffereWriter中newLine()实现换行)2.模仿文本文件复制的例题,编写对二进制文件进行复制的程序.// CopyMaker类import java.io.*;class CopyMaker {String sourceName, destName;BufferedInputStream source;BufferedOutputStream dest;int line;//打开源文件和目标文件,无异常返回trueprivate boolean openFiles() {try {source = new BufferedInputStream(newFileInputStream( sourceName ));}catch ( IOException iox ) {System.out.println("Problem opening " + sourceName );return false;}try {dest = new BufferedOutputStream(newFileOutputStream( destName ));}catch ( IOException iox ){System.out.println("Problem opening " + destName );return false;}return true;}//复制文件private boolean copyFiles() {try {line = source.read();while ( line != -1 ) {dest.write(line);line = source.read();}}catch ( IOException iox ) {System.out.println("Problem reading or writing" );return false;}return true;}//关闭源文件和目标文件private boolean closeFiles() {boolean retVal=true;try { source.close(); }catch ( IOException iox ) {System.out.println("Problem closing " + sourceName );retVal = false;}try { dest.close(); }catch ( IOException iox ) {System.out.println("Problem closing " + destName );retVal = false;}return retVal;}//执行复制public boolean copy(String src, String dst ) {sourceName = src ;destName = dst ;return openFiles() && copyFiles() && closeFiles();}}//test6_2public class test6_2{public static void main ( String[] args ) {String s1="lin.txt",s2="newlin.txt";if(new CopyMaker().copy(s1, s2))S ystem.out.print("复制成功");elseS ystem.out.print("复制失败");}}运行前的两个文本:lin.txt和newlin.txt(为空)运行后:3.创建一存储若干随机整数的文本文件,文件名、整数的个数及范围均由键盘输入。
《J a v a程序设计》课后练习答案第一章Java概述一、选择题1.( A )是在Dos命令提示符下编译Java程序的命令,( B )是运行Java程序的命令。
A.javacB.javaC.javadocD.javaw2.( D )不是Java程序中有效的注释符号。
A.//B.C.D.3.(A.B.C.D.4.JavaA.B.C.D.5.JavaA.1、JavaJava(JVM)Java以下图展示了Java程序从编译到最后运行的完整过程。
2、简述Java语言的特点Java具有以下特点:1)、简单性Java语言的语法规则和C语言非常相似,只有很少一部分不同于C语言,并且Java还舍弃了C语言中复杂的数据类型(如:指针和结构体),因此很容易入门和掌握。
2)、可靠性和安全性Java从源代码到最终运行经历了一次编译和一次解释,每次都有进行检查,比其它只进行一次编译检查的编程语言具有更高的可靠性和安全性。
3)、面向对象Java是一种完全面向的编程语言,因此它具有面向对象编程语言都拥有的封装、继承和多态三大特点。
4)、平台无关和解释执行Java语言的一个非常重要的特点就是平台无关性。
它是指用Java编写的应用程序编译后不用修改就可在不同的操作系统平台上运行。
Java之所以能平台无关,主要是依靠Java虚拟机(JVM)来实现的。
Java编译器将Java源代码文件编译后生成字节码文件(一种与操作系统无关的二进制文件)5)、6)、Java来。
1、/****/}}第二章Java语法基础一、选择题1.下面哪个单词是Java语言的关键字( B )?A. DoubleB. thisC. stringD. bool2.下面属于Java关键字的是( D )。
A. NULLB. IFC. DoD. goto3.在启动Java应用程序时可以通过main( )方法一次性地传递多个参数。
如果传递的参数有多个,可以用空格将这些参数分割;如果某一个参数本身包含空格,可以使用( B )把整个参数引起来。
习题23.使用“= =”对相同内容的字符串进行比较,看会产生什么样的结果。
答:首先创建一个字符串变量有两种方式:String str = new String("abc");String str = "abc";使用“= =”会因为创建的形式不同而产生不同的结果:String str1 = "abc";String str2 = "abc";System.out.println(str1= =str2); //trueString str1 = new String("abc"); String str2 = "abc";System.out.println(str1= =str2); //falseString str1 = new String("abc"); String str2 = new String("abc"); System.out.println(str1= =str2); //false因此自符串如果是对内容进行比较,使用equals方法比较可靠。
String str1 = "abc";String str2 = "abc";System.out.println(str1= =str2); //trueString str1 = new String("abc"); String str2 = "abc";System.out.println(str1.equals(str2)); //trueString str1 = new String("abc"); String str2 = new String("abc"); System.out.println(str1.equals(str2)); //true5.编写一个程序,把变量n的初始值设置为1678,然后利用除法运算和取余运算把变量的每位数字都提出来并打印,输出结果为:n=1678。
第6章习题解答1.简述Java中设计图形用户界面程序的主要步骤。
对于设计图形用户界面程序而言,一般分为两个步骤:第一步,设计相应的用户界面,并根据需要对相关的组件进行布局;第二步,添加相关的事件处理,如鼠标、菜单、按钮和键盘等事件。
2.试说明容器与组件之间的关系。
组件(component)是图形用户界面中的各种部件(如标签、按钮、文本框等等),所有的组件类都继承自JComponent类。
容器(container)是用来放置其他组件的一种特殊部件,在java中容器用Container类描述。
3.阅读下面程序,说明其运行结果和功能。
//filename:MyFrame.javaimport java.awt.*;import java.awt.event.*;import javax.swing.*;public class MyFrame{public static void main(String agrs[]){JFrame f=new JFrame("简单窗体示例");f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);JLabel l=new JLabel("习题1");f.getContentPane().add(l,BorderLayout.CENTER);f.pack();f.setVisible(true);}}程序的运行结果如下:4.阅读下面程序,说明其运行结果和功能。
//filename:TestButton.javaimport java.awt.*;import javax.swing.*;public class TestButton extends JFrame{JButton b1,b2;TestButton(String s){super(s);b1=new JButton("按钮1");b2=new JButton("按钮2");setLayout(new FlowLayout());add(b1);add(b2);setSize(300,100);setVisible(true);}public static void main(String args[]){ TestButton test;test=new TestButton("测试按钮"); }}程序的运行结果如下:5.阅读下面程序,说明其运行结果和功能。
《Java语言程序设计:基础篇》课后复习题答案-第六章Chapter6Single-dimensional Arrays1.See the section"Declaring and Creating Arrays."2.You access an array using its index.3.No memory is allocated when an array is declared.The memory is allocated whencreating the array.x is60The size of numbers is304.Indicate true or false for the following statements:1.Every element in an array has the same type.Answer:True2.The array size is fixed after it is declared.Answer:False3.The array size is fixed after it is created.Answer:True4.The element in the array must be of primitive data type.Answer:False5.Which of the following statements are valid array declarations?int i=new int(30);Answer:Invaliddouble d[]=new double[30];Answer:Validchar[]r=new char(1..30);Answer:Invalidint i[]=(3,4,3,2);Answer:Invalidfloat f[]={2.3, 4.5, 5.6};Answer:Validchar[]c=new char();Answer:Invalid6.The array index type is int and its lowest index is0.a[2]7.(a)double[]list=new double[10];(b)list[list.length–1]=5.5;(c)System.out.println(list[0]+list[1]);(d)double sum=0;for(int i=0;i<list.length;i++)< p="">sum+=list[i];(e)double min=list[0];for(int i=1;i<list.length;i++)< p="">if(min>list[i])min=list[i];(f)System.out.println(list[(int)(Math.random()*list.length));(g)double[]={3.5, 5.5, 4.52, 5.6};8.A runtime exception occurs.9.Line3:the array declaration is wrong.It should be double[].The array needs tobe created before its been used.e.g.new double[10]Line5:The semicolon(;)at the end of the for loop heading should be removed.Line5:r.length()should be r.length.Line6:random should be random()Line6:r(i)should be r[i].10.System.arraycopy(source,0,t,0,source.length);11.The second assignment statement myList=new int[20]creates a new array andassigns its reference to myList.myList new int[10]Array myList new int[10]Arraynew int[20]Array12.False.When an array is passed to a method,the reference value of the array ispassed.No new array is created.Both argument and parameter point to the samearray.13.numbers is 0and numbers[0]is314.(A) ExecutingcreateArray in Line 6Space required for the main methodchar[] chars: refHeap Array of 100 charactersSpace required for the createArray methodchar[] chars: ref(B) After exitingcreateArray in Line 6Space required for themain methodchar[] chars: refHeapArray of 100charactersStack Stack (C) ExecutingdisplayArray in Line 10Space required for the main methodchar[] chars: refHeap Array of 100 charactersSpace required for the displayArray method char[] chars: ref(D) After exitingdisplayArray in Line10Space required for themain methodchar[] chars: refHeapArray of 100charactersStack Stack(E) Executing countLetters in Line 13 Space required for the main methodint[] counts: refchar[] chars: refHeap Array of 100 charactersSpace required for the countLetters method int[] counts: refchar[] chars: ref (F) After exitingcountLetters in Line 13Space required for themain methodint[] counts: refchar[] chars: refHeapArray of 100charactersStack StackArray of 26 integers Array of 26 integers(G) Executing displayCounts in Line 18Space required for the main methodint[] counts: refchar[] chars: refHeap Array of 100 charactersSpace required for the displayCounts methodint[] counts: ref (H) After exitingdisplayCounts in Line 18Space required for themain methodint[] counts: refchar[] chars: refHeapArray of 100charactersStack StackArray of 26 integers Array of 26 integers15.Only one variable-length parameter may be specified ina method and this parameter must be the last parameter.The method return type cannot be a variable-length parameter.16.The last oneprintMax(new int[]{1,2,3});is incorrect,because the array must of the double[] type.17.Omitted18.Omitted19.Omitted20Simply change(currentMaxlist[j])21Simply change list[k]>currentElement on Line9tolist[k]<currentelement< p="">22.You can sort an array of any primitive types except boolean.The sort method is void,so it does not return a new array.23.To apply java.util.Arrays.binarySearch(array,key),the array must be sorted in increasing order.24.Line1:list is{2,4,7,10}Line2:list is{7,7,7,7}Line3:list is{7,8,8,7}Line4:list is{7,8,8,7}</currentelement<></list.length;i++)<></list.length;i++)<>。
Java语言程序设计课后习题答案全集Java语言程序设计是一门广泛应用于软件开发领域的编程语言,随着其应用范围的不断扩大,对于掌握Java编程技巧的需求也逐渐增加。
为了帮助读者更好地掌握Java编程,本文将提供Java语言程序设计课后习题的全集答案,供读者参考。
一、基础知识题1. 代码中的注释是什么作用?如何使用注释.答:注释在代码中是用来解释或者说明代码的功能或用途的语句,编译器在编译代码时会自动忽略注释。
在Java中,有三种注释的方式:- 单行注释:使用"// " 可以在代码的一行中加入注释。
- 多行注释:使用"/* */" 可以在多行中添加注释。
- 文档注释:使用"/** */" 可以添加方法或类的文档注释。
2. 什么是Java的数据类型?请列举常见的数据类型。
答:Java的数据类型用来指定变量的类型,常见的数据类型有:- 基本数据类型:包括整型(byte、short、int、long)、浮点型(float、double)、字符型(char)、布尔型(boolean)。
- 引用数据类型:包括类(class)、接口(interface)、数组(array)等。
二、代码编写题1. 编写Java程序,输入两个整数,求和并输出结果。
答:```javaimport java.util.Scanner;public class SumCalculator {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.print("请输入第一个整数:");int num1 = scanner.nextInt();System.out.print("请输入第二个整数:");int num2 = scanner.nextInt();int sum = num1 + num2;System.out.println("两个整数的和为:" + sum);}}```三、综合应用题1. 编写Java程序,实现学生信息管理系统,要求包括以下功能:- 添加学生信息(姓名、年龄、性别、学号等);- 修改学生信息;- 删除学生信息;- 查询学生信息。
《Java程序设计》课后习题参考答案Java程序设计课后习题参考答案1. 介绍在 Java 程序设计课程中,课后习题是帮助学生巩固知识、加深理解和提高编程能力的重要环节。
本文将为大家提供《Java程序设计》课后习题的参考答案,以帮助学生更好地学习和掌握 Java 编程。
2. 基本概念Java 程序设计课后习题涵盖了从基础到高级的各种知识点,包括但不限于变量、数据类型、条件语句、循环语句、数组、类、对象、继承、多态等内容。
通过解答这些习题,学生可以加深对这些概念的理解,并且通过实际操作来巩固他们的编程能力。
3. 习题解答策略当解答课后习题时,以下几个策略可以帮助你更好地理解和解决问题:3.1 仔细阅读题目要求。
确保自己充分理解题目所要求的功能和目标。
3.2 分析问题。
在着手解答问题之前,先理清思路,分析问题的要点和关键部分。
3.3 设计算法。
根据问题的要求,设计一个合适的算法来解决问题。
3.4 编写代码。
用 Java 编程语言将你设计的算法转化为代码实现。
3.5 测试和调试。
对编写的代码进行测试和调试,确保程序能够正常运行,并且得到正确的结果。
4. 习题参考答案示例下面我们将列举几个常见的习题参考答案示例,以帮助大家更好地理解和学习 Java 程序设计:4.1 变量与数据类型:习题要求定义一个整型变量并赋值为10,然后输出该变量的值。
```public class VariableExample {public static void main(String[] args) {int num = 10;System.out.println("变量的值为:" + num);}}```4.2 条件语句:习题要求判断一个数是否是偶数,如果是,则输出“偶数”,否则输出“奇数”。
```public class EvenOddExample {public static void main(String[] args) {int num = 5;if (num % 2 == 0) {System.out.println("偶数");} else {System.out.println("奇数");}}}```4.3 循环语句:习题要求输出1到10之间的所有偶数。
第六章6.1 设计一个面板,该面板中有四个运动项目选择框和一个文本区。
当某个选择项目被选中时,在文本区中显示该选择项目。
程序运行结果:源文件:Work6_1.javaimport javax.swing.*;import java.awt.*;import ;/*** 6.1设计一个面板,该面板中有四个运动项目选择框和一个文本区。
<BR>*当某个选择项目被选中时,在文本区中显示该选择项目。
<BR>*@author黎明你好*/public class Work6_1 extends JFrame{private static final long serialVersionUID = 1L;private MyPanel6_1 panel;// 此面板public Work6_1(){super("第六章,第一题");panel = new MyPanel6_1();this.add(panel);this.setBounds(100, 100, 400, 150);this.setVisible(true);this.validate();this.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});}public static void main(String args[]){new Work6_1();}}面板类源文件:MyPanel6_1.java/***需要设计的面板类*/class MyPanel6_1 extends JPanel implements ItemListener{private static final long serialVersionUID = 1L;private JCheckBox box1, box2, box3, box4;private JTextArea textArea;public MyPanel6_1(){textArea = new JTextArea(5, 10);box1 = new JCheckBox("足球");box2 = new JCheckBox("排球");box3 = new JCheckBox("篮球");box4 = new JCheckBox("台球");box1.addItemListener(this);box2.addItemListener(this);box3.addItemListener(this);box4.addItemListener(this);this.add(box1);this.add(box2);this.add(box3);this.add(box4);this.add(textArea);this.setBackground(Color.cyan);}public void itemStateChanged(ItemEvent e){JCheckBox box = (JCheckBox) e.getSource();if (box == box1 && box.isSelected())textArea.append(box1.getText() + "\n");else if (box == box2 && box.isSelected())textArea.append(box2.getText() + "\n");else if (box == box3 && box.isSelected())textArea.append(box3.getText() + "\n");else if (box == box4 && box.isSelected())textArea.append(box4.getText() + "\n");}}6.2 设计一个面板,该面板中有四个运动项目单选框和一个文本框。
Chapter 6 Arrays1. See the section "Declaring and Creating Arrays."2. You access an array using its index.3. No memory is allocated when an array is declared. The memory is allocated whencreating the array.x is 60The size of numbers is 304. Indicate true or false for the following statements:1. Every element in an array has the same type.Answer: True2. The array size is fixed after it is declared.Answer: False3. The array size is fixed after it is created.Answer: True4. The element in the array must be of primitive data type.Answer: False5. Which of the following statements are valid array declarations?int i = new int(30);Answer: Invaliddouble d[] = new double[30];Answer: Validchar[] r = new char(1..30);Answer: Invalidint i[] = (3, 4, 3, 2);Answer: Invalidfloat f[] = {2.3, 4.5, 5.6};Answer: Validchar[] c = new char();Answer: Invalid6. The array index type is int and its lowest index is 0.7. a[2]8. A runtime exception occurs.9. Line 3: the array declaration is wrong. It should be double[]. The array needs tobe created before its been used. e.g. new double[10]Line 5: The semicolon (;) at the end of the for loop heading should be removed.Line 5: r.length() should be r.length.Line 6: random should be random()Line 6: r(i) should be r[i].System.arraycopy(source, 0, t, 0, source.length);10.11. The second assignment statement myList = new int[20] creates a new array andassigns its reference to myList.12. False. When an array is passed to a method, the reference value of the array ispassed. No new array is created. Both argument and parameter point to the samearray.13.numbers is 0 and numbers[0] is 314.15. Only one variable-length parameter may be specified ina method and this parameter must be the last parameter. The method return type cannot be a variable-length parameter.16.The last oneprintMax(new int[]{1, 2, 3});is incorrect, because the array must of the double[] type.17. Omitted18. Omitted19. Omitted20 Simply change (currentMax < list[j]) on Line 10 to(currentMax > list[j])21 Simply change list[k] > currentElement on Line 9 tolist[k] < currentElement22. To apply java.util.Arrays.binarySearch(array, key), the array must be sorted inincreasing order.23.You can sort an array of any primitive types except boolean. The sort method is void,so it does not return a new array.24. Line 1: list is {2, 4, 7, 10}Line 2: list is {7, 7, 7, 7}Line 3: list is {7, 8, 8, 7}Line 4: list is {7, 8, 8, 7}25 int[][] m = new int[4][5];26 Yes. They are ragged array.27 array[0][1] is 2.28.int[][] r = new int[2];int[] x = new int[];int[][] y = new int[3][];Answer: Valid。
Java语言程序设计第六章课后习题答案1.将本章例6-1至6-18中出现的文件的构造方法均改为使用File类对象作为参数实现。
个人理解:File类只能对整文件性质进行处理,而没法通过自己直接使用file.Read()或者是file.write()类似方法对文件内容进行写或者读取。
注意:是直接;下面只提供一个例2变化,其他的你自己做,10几道啊,出这题的人真他妈有病。
import java.io.*;public class test6_2{public static void main(String[] args) throws IOException { String fileName = "D:\\Hello.txt";File writer=new File(fileName);writer.createNewFile();BufferedWriter input = new BufferedWriter(newFileWriter(writer));input.write("Hello !\n");input.write("this is my first text file,\n");input.write("你还好吗?\n");input.close();}}运行结果:(电脑系统问题,没法换行,所以一般使用BuffereWriter中newLine()实现换行)2.模仿文本文件复制的例题,编写对二进制文件进行复制的程序.// CopyMaker类import java.io.*;class CopyMaker {String sourceName, destName;BufferedInputStream source;BufferedOutputStream dest;int line;//打开源文件和目标文件,无异常返回trueprivate boolean openFiles() {try {source = new BufferedInputStream(newFileInputStream( sourceName ));}catch ( IOException iox ) {System.out.println("Problem opening " + sourceName );return false;}try {dest = new BufferedOutputStream(newFileOutputStream( destName ));}catch ( IOException iox ){System.out.println("Problem opening " + destName );return false;}return true;}//复制文件private boolean copyFiles() {try {line = source.read();while ( line != -1 ) {dest.write(line);line = source.read();}}catch ( IOException iox ) {System.out.println("Problem reading or writing" );return false;}return true;}//关闭源文件和目标文件private boolean closeFiles() {boolean retVal=true;try { source.close(); }catch ( IOException iox ) {System.out.println("Problem closing " + sourceName );retVal = false;}try { dest.close(); }catch ( IOException iox ) {System.out.println("Problem closing " + destName );retVal = false;}return retVal;}//执行复制public boolean copy(String src, String dst ) {sourceName = src ;destName = dst ;return openFiles() && copyFiles() && closeFiles();}}//test6_2public class test6_2{public static void main ( String[] args ) {String s1="lin.txt",s2="newlin.txt";if(new CopyMaker().copy(s1, s2))S ystem.out.print("复制成功");elseS ystem.out.print("复制失败");}}运行前的两个文本:lin.txt和newlin.txt(为空)运行后:3.创建一存储若干随机整数的文本文件,文件名、整数的个数及范围均由键盘输入。
// memory存储类import java.io.*;import java.util.Random;public class memory {private String name;private int count;private int Max;private int Min;public memory(String n,int c,int min,int max){=n;this.count=c;this.Min=min;this.Max=max;}public void startmemory(){try{FileWriter out=new FileWriter(name);int limit=Max-Min;Random random = new Random();for (int i=1;i<=count;i++){int number=Min+random.nextInt(limit);System.out.print(number);System.out.print(" ");out.write(number+" ");}out.close();}catch(IOException iox){System.out.println("方法startmemory()有问题");}}}//test6_3import java.io.*;import java.util.Scanner;public class test6_3 {public static void main(String[] args) throws IOException{ //BufferedReaderString fileName;int count,min,max;Scanner in = new Scanner(System.in);System.out.println("输入要存储的文件名");fileName=in.next();System.out.println("输入随机数个数");count=in.nextInt();System.out.println("输入随机数最小值");min=in.nextInt();System.out.println("输入随机数最大值");max=in.nextInt();memory M=new memory(fileName,count,min,max);M.startmemory();}}}运行结果:naruto文件存储二进制数:4.分别使用FileWriter和BufferedWriter往文件中写入10万个随机数,比较用时的多少。
//FileWriter方法import java.io.*;public class fileWriter {public static void main(String[] args) throws IOException{ long time = System.currentTimeMillis();//当前时间FileWriter filewriter=new FileWriter("filewriter.txt");int number;for(int i=1;i<=;i++){number=(int)(Math.random()*10000);filewriter.write(number+" ");}filewriter.close();time=System.currentTimeMillis()-time;//时间差System.out.println("用时为:"+time+"微秒.");}}运行结果://BufferedWriter方法import java.io.*;public class bufferedWriter {public static void main(String[] args) throws IOException{ long time = System.currentTimeMillis();//当前时间BufferedWriter filewriter=new BufferedWriter(newFileWriter("filewriter.txt"));int number;for(int i=1;i<=;i++){number=(int)(Math.random()*10000);filewriter.write(number+" ");}filewriter.close();time=System.currentTimeMillis()-time;//时间差System.out.println("用时为:"+time+"微秒.");}}运行结果:有用时可知:BufferedWriter比FileWriter写入的速度快, 当需要写入大量内容,前者效率高。