第二次java作业(3-5)和实验(3-14)参考答案 - 图文

更新时间:2023-11-19 05:07:01 阅读量: 教育文库 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

作业

第三章 Java面向对象

1、为某研究所编写一个通用程序,用来计算每一种交通工具运行1000公里所需的时间,已知每种交通工具的参数都是3个整数A、B、C的表达式。现有两种工具:Car007 和Plane,其中Car007 的速度运算公式为:A*B/C,Plane 的速度运算公式为:A+B+C。需要编写三类:ComputeTime.java, Plane.java, Car007.java和接口Common.java,要求在未来如果增加第3种交通工具的时候,不必修改以前的任何程序,只需要编写新的交通工具的程序。其运行过程如下,从命令行输入ComputeTime的四个参数,第一个是交通工具的类型,第二、三、四个参数分别时整数A、B、C,举例如下:

计算Plane的时间:\ 计算Car007的时间:\

如果第3种交通工具为Ship, 则只需要编写Ship.java,运行时输入:\22 33 44\

提示:充分利用接口的概念,接口对象充当参数。

实例化一个对象的另外一种办法:Class.forName(str).newInstance();例如需要实例化一个Plane对象的话,则只要调用Class.forName(\便可。 访到classpath 路径下即可,请从下往上编译 目录结构 CalTime

--------|--------

| | | |

vehicle ComputTime.java |

--------- | | | |

all Palne.java /Car.java | |

Common.java

1. ComputTime.java 请确保输入正确,其中没有捕捉NumberFromatException import CalTime.vehicle.all.Common; import java.lang.*;

public class ComputeTime {

public static void main(String args[]) { System.out.println(\交通工具: \ System.out.println(\参数A: \

System.out.println(\参数B: \System.out.println(\参数C: \double A=Double.parseDouble(args[1]); double B=Double.parseDouble(args[2]); double C=Double.parseDouble(args[3]); double v,t; try {

Common d=(Common) Class.forName(\+args[0]).newInstance(); // CalTime.vehicle是对应的包名 v=d.runTimer(A,B,C); t=1000/v;

System.out.println(\平均速度: \ System.out.println(\运行时间:\小时\}

catch(Exception e) { System.out.println(\}

} }

2.Plane.java

package CalTime.vehicle;

import CalTime.vehicle.all.Common;

public class Plane implements Common {

public double runTimer(double a, double b, double c) {

return (a+ b + c); } }

3. Car.java

package CalTime.vehicle;

import CalTime.vehicle.all.Common;

public class Car implements Common { public double runTimer(double a, double b, double c)

{

return ( a*b/c ); } }

4.Common.java

package CalTime.vehicle.all;

public interface Common

{ }

double runTimer(double a, double b, double c);

2、编写一个学生类 Student ,要求: (1) 学生类 Student 属性有: id : long型,代表学号 name : String类对象,代表姓名 age : int型,代表年龄 sex : boolen型,代表性别(其中:true表示男,false表示女) phone : String类对象,代表联系电话 (2) 学生类 Student的方法有: Student(long i , String n , int a , boolean s , long p) : 有参构造函数,形参表中的参数分别初始化学号、姓名、年龄、性别和联系电话。 int getAge() ( ) : 获取年龄作为方法的返回值。 boolean getSex( ) ( ) : 获取性别作为方法的返回值。 long getPhone ( ) : 获取联系电话作为方法的返回值。 public String toString( ) : 以 姓名:联系电话 的形式作为方法的返回值。

public class test_S3_2 { public static void main(String[]args) { Student student = new Student(01,\李明\ System.out.println(student.getAge()); System.out.println(student.getPhone()); System.out.println(student.toString()); } }

class Student { public long id; public String name; public int age; public boolean sex; public String phone; public Student(long i,String n,int a,boolean s,String p) { this.id = i; this.name = n; this.age = a; this.sex = s; this.phone = p; } public int getAge() { return this.age; } public boolean getSex() { return this.sex;

}

}

public String getPhone() { return this.phone; }

public String toString() { return this.name+ \ }

3、利用接口编写三角形、矩形的面积和周长的程序。 import java.awt.image.renderable.RenderableImageOp; public class S3_3 { public static void main(String[] args) { Rectangle rectangle = new Rectangle(10, 8);

System.out.println(\矩形面积:\

System.out.println(\矩形周长:\Triangle triangle = new Triangle(3, 4, 5);

System.out.println(\三角形面积:\ System.out.println(\三角形周长:\ } }

class Rectangle implements Cal { double longth; double width; public Rectangle(double longth, double width) { this.longth = longth; this.width = width; } public double calArea() { return this.longth * this.width; } @Override public double calPerimeter() { return (this.longth + this.width) * 2; } }

class Triangle implements Cal { double a; double b; double c; public Triangle(double a, double b, double c) { this.a = a; this.b = b; this.c = c; } public double calArea() { double p = (a+b+c)/2; return Math.sqrt(p*(p-a)*(p-b)*(p-c)); } public double calPerimeter() { return (a+b+c); } }

4、编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。但是要保证汉字不被截半个,如\我ABC\,应该截为\我AB\,输入\我ABC汉DEF\,6,应该输出为\我ABC\而不是\我ABC+汉的半个\。 public class Test3 {

public static void main(String[] args) {

String srcStr1 = \我ABC\

String srcStr2 = \我ABC汉DEF\ splitString(srcStr1, 4); splitString(srcStr2, 6); }

public static void splitString(String src, int len) {

int byteNum = 0; if (null == src) {

System.out.println(\ return; }

byteNum = src.length();

byte bt[] = src.getBytes(); // 将String转换成byte字节数组

if (len > byteNum) {

len = byteNum; }

// 判断是否出现了截半,截半的话字节对于的ASC码是小于0的值 if (bt[len] < 0)

{

String subStrx = new String(bt, 0, --len); System.out.println(\ }

else {

String subStrx = new String(bt, 0, len); System.out.println(\ } } }

第四章 Java异常处理 1、 写程序运行结果: public class A {

static int some() { try {

System.out.println(\ return 1; }

finally {

System.out.println(\ } }

public static void main(String arg[]) { System.out.println(some()); } } try finally 1

2、先从键盘输入一个十六进制数,再将其转化为十进制数,然后输出。若输入的不是一个有效的十六进制数,则抛出异常。 import java.util.InputMismatchException; import java.util.Scanner;

public class S4_2

{

public static void main(String[] args) { System.out.println(\请输入一个十六进制的数:\ Scanner cin = new Scanner(System.in); try{ while(cin.hasNext()) { int val = cin.nextInt(16);

System.out.print(\转化为十进制为:\ System.out.println(val); System.out.println(\请输入一个十六进制的数:\ } }catch(InputMismatchException e){ e.printStackTrace(); } } }

3、先编写一个方法,它将格式为“yyyy/mm/dd”形式的日期字符串转化为日期对象。若日期字符串不符合以上规定,则抛出异常。再在main方法中对正常和异常输入的日期字符串分别进行验证,并输出转换后的日期对象。 import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner; public class S4_3 { public static void main(String[] args) throws ParseException { System.out.println(\/9/1 :\ Scanner scanner = new Scanner(System.in); String temp = scanner.nextLine(); try { System.out.println(getDate(temp)); } catch (ParseException e) { e.printStackTrace(); throw e; } } public static Date getDate(String date) throws ParseException{ DateFormat format = new SimpleDateFormat(\

}

}

try { return new Date(format.parse(date).getTime()); } catch (ParseException e) { e.printStackTrace(); throw e; }

第五章 Java常见类

1、设有一个由10个英文单词构成的字符串数组,要求: (1) 统计以字母“w”开头的单词数;

(2) 统计单词中含“or”字符串的单词数; (3) 统计长度为3的单词数。

public class S5_1 { public static void main(String[] args) { String string[] = {\ int countW = 0; int countOr = 0; int countLentghEqual3 = 0; for (int i = 0; i < string.length; i++) { if (string[i].substring(0, 1).equals(\ { countW++; } if (string[i].indexOf(\ { countOr++; } if (string[i].length() == 3) { countLentghEqual3++; } } System.out.println(\以字母w开头的单词数:\ System.out.println(\单词中含'or'字符串的单词数:\ System.out.println(\长度为3的单词数:\ } }

2、利用随机函数产生20个10~90之间的不重复整数, 将这些数拼接在一个字符串中, 用逗号隔开(每产生一个新数, 要保证在该串中不存在)。然后将字符串中的整数分离存放到一个数组中,将数组的内容按由小到大的顺序输出。

import javax.naming.ldap.SortControl; public class S5_2 { public static void main(String[] args) { StringBuffer stringBuffer = new StringBuffer(); String string; int a[] = new int[20]; stringBuffer = generateInt(); string = stringBuffer.toString(); System.out.println(string); a = intoArray(string); a = sort(a); for (int i = 0; i < 20; i++) { System.out.print(a[i]+\ } } static StringBuffer generateInt() { int integer; StringBuffer string = new StringBuffer(); String tempString; for (int i = 0; i < 20; i++) { integer = (int)(Math.random()*90); if (integer < 10) { i--; } else if (string.indexOf(Integer.toString(integer)) != -1) { i--; } else { tempString = Integer.toString(integer); string.append(tempString+\ }

}

} return string; }

static int[] intoArray(String string) { int a[] = new int[20]; String tempString; for (int i = 0; i < a.length; i++) { tempString = string.substring(3*i, 3*i+2); a[i] = Integer.parseInt(tempString); } return a; }

static int[] sort(int a[]) { int tempInt; for (int i = 0; i < a.length-1; i++) { for (int j = i+1; j < a.length; j++) { if (a[i] > a[j]) { tempInt = a[i]; a[i] = a[j]; a[j] = tempInt; } } } return a; }

3、先任意输入不超过10个人的姓名和电话到电话簿,然后从电话簿中查询指定人的电话。

import java.util.Scanner; public class S5_3 { public static void main(String[] args) { String person[][] = new String[3][2]; String searchName; String phone; Scanner myInput = new Scanner(System.in); person = input(person);

实验05:输入/输出处理

实验目的: 掌握输入输出程序的处理。 实验数据记录及分析(或程序及运行结果) 1. 编写程序,从键盘上输入一个整数作为圆的半径,分别计算并输出圆周长、圆面积。 public class S05_1{ public static void main(String[] args) { double pi=Math.PI; System.out.println(\请输入你要求的圆的半径:\ Scanner scanner = new Scanner( System.in ); String a=scanner.next(); int b=Integer.parseInt(a); System.out.println(\圆的周长为:\ System.out.println(\圆的面积为:\ } } 2. 编写程序,从键盘上输入三个实数,比较大小,分别输出最大值和最小值。 public class S05_2 { public static void main(String[] args) { int[] a = new int[3]; a = input_3(); a = rankUp(a); System.out.println(\最大值是\+a[2]); System.out.println(\最小值是\+a[0]); } static int[] input_3() { int[] a = new int[3]; String string; for (int i = 0; i < 3; i++) { System.out.println(\输入一个整数\); Scanner scanner = new Scanner(System.in); string = scanner.next(); a[i] = Integer.parseInt(string); } return a; } static int[] rankUp(int[] a) { int temp; for (int i = 0; i < a.length-1; i++) { for (int j = i+1; j < a.length; j++) { if (a[i] > a[j]) { temp = a[i]; a[i] = a[j]; a[j] = temp; } } } return a; } } 3. 运行下面的程序,写出运行结果,解释每种格式的含义。 import java.util.Calendar; public class CommandParameter { public static void main(String[] args) { long n = 461012; System.out.printf(\ System.out.printf(\System.out.printf(\ System.out.printf(\ System.out.printf(\ double pi = Math.PI; System.out.printf(\System.out.printf(\ System.out.printf(\System.out.printf(\ Calendar c = Calendar.getInstance(); System.out.printf(\System.out.printf(\System.out.printf(\ } } { System.out.println(\number x is not between 1 and 10000.\); } } } 2. 分析下面程序,写出运行结果 class TestApp{ public static void main(String[] args){ for(int i=0;i<10;i++){ if(i==3) break; System.out.print(i); } } } 012 3. 分析switch的作用,写出下面程序运行的结果 class SwitchDemo{ public static void main(String args[]) { int c=38; switch (c<10?1:c<25?2:c<35?3:4) { case 1: System.out.println(\℃ 有点冷。要多穿衣服。\case 2: System.out.println(\℃ 正合适。出去玩吧。\case 3: System.out.println(\℃ 有点热。\default: System.out.println(\℃ 太热了!开空调。\} } 1) 当c=38时,运行结果是什么?38℃ 太热了!开空调。 2) 当c=8时,运行结果是什么?8℃有点冷。要多穿衣服。 8℃ 正合适。出去玩吧。8℃ 有点热。8℃ 太热了!开空调。 3) 当c=48时,运行结果是什么?48℃ 太热了!开空调。 4) 在每个case的输出语句后,添加break语句后,充分执行上述几种情况,分析有何变化,分析写出每次运行结果。 当c=38时,运行结果是38℃ 太热了!开空调。 当c=8时,运行结果是8℃有点冷。要多穿衣服。 当c=48时,运行结果是48℃ 太热了!开空调。 4. 通过键盘输入任一个整数,判断其是否是素数,并输出判断结果。 public class S06_4 { public static void main(String[] args) { } System.out.println(\请输入一个整数\); Scanner scanner = new Scanner(System.in); int a = scanner.nextInt(); isPrime(a); } static void isPrime(int a) { boolean isPrime = true; for (int i = 2; i < a/2; i++) { if (a % i == 0) { isPrime = false; } } if (isPrime) { System.out.println(a+\是一个素数\); } else { System.out.println(a+\不是一个素数\); } } 5. 通过键盘输入任意两个整数,按照从小到大的顺序输出这两个数。 public class S06_5 { public static void main(String[] args) { int[] a = new int[2]; a = input_2(); if (a[0] > a[1]) { System.out.println(a[1]+\+a[0]); } else { System.out.println(a[0]+\+a[1]);

={\,\,\,\,\,\,\,\,\,\,\,\,\}; private static String[] cards = new String[52]; public Deck() { int n = 0; for (int i = 0; i < suits.length; i++) { for (int j = 0; j < ranks.length; j++) { Deck.cards[n] = suits[i] + ranks[j]; n++; } } } public void show() { for (int i = 0; i < this.cards.length; i++) { if (i % 13 == 0) { System.out.println(); } System.out.print(this.cards[i]+' '); } } System.out.println(); } public String show(int idx) { return this.cards[idx-1]; } public static void main(String[] args) { Deck deck = new Deck(); deck.show(); System.out.println(deck.show(13)); } 2. 定义一个Teacher类,该类提供教师的工号、姓名、职称信息,再定义一个课程类,描述了课程的编号、课程名称、理论课时和实验课时、学分以及每门课程都要指定一个教师,通过课程能够获得任课教师对象。 public class Teacher { private String workID; private String name; private String title; public String getWorkID() { return workID; } public void setWorkID(String workID) { this.workID = workID; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } } public class Course { private String number; private String name; private int theroyClass; private int ExperimentClass; private int credit; public Teacher teacher = new Teacher(); public Course(String number, String name, int theroyClass, int ExperimentClass, int credit, String teacherID, String teacherName, String teacherTitle) { this.number = number; this.name = name; this.theroyClass = theroyClass; this.ExperimentClass = ExperimentClass; this.credit = credit; this.teacher.setName(teacherName); this.teacher.setWorkID(teacherID); this.teacher.setTitle(teacherTitle); } public static void main(String[] args) { Course course = new Course(\, \, 32, 16, 3, \, \, \); System.out.println(course.teacher.getName()); System.out.println(course.teacher.getWorkID()); System.out.println(course.teacher.getTitle()); } } 3. 小镇的图书馆需要一个新的电子租借系统。该小镇有两个图书馆,每个图书馆提供很多书让客户去租赁。客户可以打印出所有的图书清单,包括现存的,已经借出的和归还的。现在我们需要提供两个类,Book类和Library类,有这俩个类提供图书数据库的功能。请补充缺少的方法去完成类的功能。 步骤: 1) 补充完成Book类的定义。这个类需要定义获取图书标题的方法,查看图书的作者,查看是否可用的方法,是否借出方法。图书的状态用“available”和“borrowed”表示。现在的结构框架内缺少这些方法的执行内容,请用合适的功能代码补充方法体的内容。用main方法测试方法,当你运行程序时应该输出的内容: 图书名称:Java程序设计教程 图书作者:丁一 出租状态:出租中 可用状态:不可用 public class Book { String title; //图书名称 String author; //作者 boolean borrowed; //图书状态,初始状态为可用 //使用给定的图书名称,创建一个新的Book对象 ,并置该对象的初始状态为可用 public Book(String bookTitle,String author){ // Implement this method } // 借书,标记该书为借出状态 public void borrowed() { // Implement this method } //还书,标记该书为可用状态 public void returned() { // Implement this method } // Returns true if the book is rented, false otherwise public boolean isBorrowed() { // Implement this method } // Returns true if the book is available, false otherwise public Boolean isAvailable(){ // Implement this method } //返回图书的名称 public String getTitle() { // Implement this method } public static void main(String[] arguments){ Book example = new Book(\程序设计教程\System.out.println(\图书名称:\System.out.println(\图书作者:\System.out.println(\出租状态:\System.out.println(\可用状态:\} } public class Book { String title; //图书名称 String author; //作者 boolean borrowed = false; //图书状态,初始状态为可用 //使用给定的图书名称,创建一个新的Book对象 ,并置该对象的初始状态为可用 public Book(String bookTitle,String author){ // Implement this method this.title = bookTitle; this.author = author; } // 借书,标记该书为借出状态 public void borrowed() { // Implement this method this.borrowed = true; } //还书,标记该书为可用状态 public void returned() { // Implement this method this.borrowed = false; } // Returns true if the book is rented, false otherwise public String isBorrowed() { // Implement this method if (borrowed) { return \出租中\; } else { return \未出租\; } } // Returns true if the book is available, false otherwise public String isAvailable(){ // Implement this method if (borrowed) { return \不可用\; } else { return \可用\; } } //返回图书的名称 public String getTitle(){ // Implement this method return title; } public String getAuthor() { return author;

} } static int[] input_2() { int[] a = new int[2]; for (int i = 0; i < a.length; i++) { } } System.out.println(\请输入一个整数:\); Scanner scanner = new Scanner(System.in); a[i] = scanner.nextInt(); } return a; 6. 写出下面的代码段执行后,j的值是多少? int i=1, j=0 switch(i) { case 2: j+=6; case 4: j+=1; default: j +=2; case 0: j +=4; } 6 7. 写出下列程序片段中while循环体重复执行的次数 int a = 1, b = 1; while ( a <= 1000 ){ a = 2 * a; b = b + 1; } System.out.println( b ); 10 8. 编写一个程序,输出1到200之间所有能被3整除的整数,要求输出时每行输出5个整数。 public class S06_8 { public static void main(String[] args) { int n=0; for (int x = 1; x <= 200; x++) { if(x%3==0) { System.out.print(x+\); n++; } if(n%5==0) { System.out.println(); } } } 9. 编写一个程序,输出一个99乘法表,输出格式如下。 1×1=1 1×2=2 2×2=4 1×3=3 2×3=6 3×3=9 1×4=4 2×4=8 3×4=12 4×4=16 1×5=5 2×5=10 3×5=15 4×5=20 5×5=25 1×6=6 2×6=12 3×6=18 4×6=24 5×6=30 6×6=36 1×7=7 2×7=14 3×7=21 4×7=28 5×7=35 6×7=42 7×7=49 1×8=8 2×8=16 3×8=24 4×8=32 5×8=40 6×8=48 7×8=56 8×8=64 1×9=9 2×9=18 3×9=27 4×9=36 5×9=45 6×9=54 7×9=63 8×9=72 9×9=81 public class S06_9 { public static void main(String[] args) { for (int i = 1; i <= 9; i++) { for (int j = 1; j <= i; j++) { System.out.print(i+\+i+\+i*j+\); } System.out.println(); } } } 10. 下面输出素数的程序原意输出为下面的结果,但现在不是,请调试下面程序,使之能够按要求输出: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 public class Prime { public static void main(String[] args) { boolean isPrime=true;//用来标识每次计算的数是否是素数,如果不是则为false; for (int x = 2; x <= 100; x++) { int m = (x / 2)-1; for (int i = 2; i <= m; i++) { if (x % i == 0) isPrime=false;// break; } if(isPrime){ System.out.print(x+\); } if(n==5){ System.out.println(); } } } } 评语: 日期: 年 月 日 实验07:流程控制(二)

实验目的: 1. 进一步巩固对分支、循环结构的掌握,并简单了解有关方法的使用 实验数据记录及分析(或程序及运行结果) 1. 分析程序 class TestApp{ public static void main(String[] args){ System.out.println(multiply(2,3,4,5)); } public int multiply(int … nums){//变长参数 int result = 1; for(int x :nums) result *= x; return result; } } 能否正常运行?原因是什么? 不能,for循环不符合Java语言规则 2. 编写程序,接受命令行传入的的一个参数,能够统计其中大写字母、小写字母、数字、空格及其他字符的个数,并且分别输出统计数据,如果碰到了”\\n”则终止统计。 提示: 1) 声明并出初始化一个字符串变量:如String s=”hello\\nMike”; 2) s.charAt(0)表示取该字符串的第1个字符h; s.charAt(1) 取第2个字符e,其他依次类推; 3) s.length()返回该字符串的字符个数,如”hello”的字符个数是5。 public class S07_2 { public static void main(String[] args) { String string; int upN=0, lowN=0,numberN=0,blankN=0,elseN=0; System.out.println(\请输入一个字符串,以\\n结尾:\); string = input(); System.out.println(string); for (int i = 0; i < string.length(); i++) { if (string.charAt(i) == '\\n') { break; } if (string.charAt(i)>='A' && string.charAt(i)<='Z') { upN++; }

} else if (string.charAt(i)>='a' && string.charAt(i)<= 'z') { lowN++; } else if (string.charAt(i)>='0' && string.charAt(i)<='9') { numberN++; } else if (string.charAt(i) == ' ') { blankN++; } else { elseN++; } System.out.println(\其中大写字母个数为\+upN+\+\小写字母个数为\+lowN+\+\数字个数为\+numberN+\+\空格个数为\+blankN+\+\及其他字符的个数\+elseN); } static String input() { String string; Scanner scanner = new Scanner(System.in); string = scanner.nextLine(); return string; } } 3. 利用java.util.Random类,编写一个程序,每次执行时生成一个1~6之间(含1和6)的整数。Random类的用法如下面代码段所示。 Ramdom rand = new Random( ); //第一步要创建一个随机数生成对象 int x = rand.nextInt(5)+1; //第二步rand.nextInt(5)生成一个0到5之间的数字,然后简单加1,调整到1到6之间,以满足需要 public class S07_3 { public static void main(String[] args) { Random random = new Random(); int a = random.nextInt(5)+1; } System.out.println(\随机生成的整数为:\+a); } 4. 利用java.util.Random类,编写一个程序,每次执行时生成一个1~6之间(含1和6)的整数。Random类的用法如下面代码段所示。 Ramdom rand = new Random( ); //第一步要创建一个随机数生成对象 int x = rand.nextInt(5)+1; //第二步rand.nextInt(5)生成一个0到5之间的数字,然后简单加1,调整到1到6之间,以满足需要。 写一个程序,使用上述随机数生成方法模拟掷筛子(Dice)。一个人每次掷3个筛子,根据下面的规则来显示获胜的奖金情况。 ? 如果3个筛子都是6,赢20元; ? 如果3个筛子都相同,赢10元; ? 如果3个筛子中有任何两个都相同,赢5元。 public class S07_4 { public static void main(String[] args) { int[] a; a = throwDice(); grade(a); } static int[] throwDice() { int[] a = new int[3]; for (int i = 0; i < 3; i++) { Random random = new Random(); a[i] = random.nextInt(5)+1; } return a; } static void grade(int[] a) { if (a[0] == 6 && a[1] == 6 && a[2] == 6) { System.out.println(\); } else if (a[0]==a[1] && a[0] == a[2] && a[0] != 6) { } System.out.println(\); } else if (a[0]==a[1] || a[0] == a[2] || a[1] == a[2]) { System.out.println(\); } } 5. 分析程序 public static double power( double x, int n ){ if ( n == 0 ) return 1.0; else if ( n % 2 == 0 ) return power( x * x, n / 2 ); else return power( x * x, n / 2 ) * x; } 1) 程序的功能是:功能为x的n次方; 2) 当x=4,n=2时,调用power方法返回值是什么?写出每次的调用过程 返回16;step1:x=4,n=2; step2:x=16,n=1;即为:16*1.0=16.0 6. 分析下面的两段程序 public static int P( int n ){ return Q( n >= 0 ? n : - n ); } private static int Q( int m ){ final int BASE = 10; return ( m < BASE ? 1 : 1 + Q( m / BASE ) ); } 例如:当n=5时,调用方法p返回值是多少?写出执行过程。 Step1:n=5, p (5) = Q (5 ) ; Q (5 ) = 1 1) 当n=9时,调用方法p返回值是多少?写出执行过程。 Step1:n=9, p (9) = Q (9 ) ; Q (9 ) = 1 2) 当n=10时,调用方法p返回值是多少?写出执行过程。 Step1:n=10, p (10) = Q (10 ) ; Q (10 ) = 2 3) 当n=123时,调用方法p返回值是多少?写出执行过程。 Step1:n=123, p (123) = Q (123 ) ; Q (123 ) = 13 4) 总结P方法的功能是什么? 将整数转化为正整数,然后返回与十相除取整加一 5) 修改方法P,完成同样功能,达到不调用其它函数包括递归调用自己。 public static int P( int n ) { final int BASE = 10; n >= 0 ? n : - n ; return n/10 + 1; } 实验08:数组

实验目的: 1. 知道怎么样声明、创建和初始化各种类型的数组 2. 理解二维数组的概念,能够声明、创建和初始化各种类型的二维数组 3. 掌握对一维或二维数组元素的访问方法 4. 掌握不规则二维数组的声明、创建和初始化以及访问的方法了解Arrays类及System类中关于数组操作的方法的使用 实验内容 1. 编写程序,掌握数组的声明和访问数组元素,了解数组对象length的作用 2. 编写程序,掌握二维数组的定义和应用 3. 编写程序,掌握二维不规则数组的定义和使用 4. 编写程序,熟悉命令行参数 实验数据记录及分析(或程序及运行结果) 1. 根据教科书程序5-5,写出外循环每次循环后数组的元素变化。 循环开始前的数组元素依次是: 第一次循环后的数组元素依次是: 第二次循环后的数组元素依次是: 循环后的数组元素依次是: 2. 分析下面程序,写出运行结果 public class ArrayTest { public static void main(String[] args) { int i, j; int a[] = { 2, 1, 4, 8, 9, 5, 3 }; for (i = 0; i < a.length - 1; i++) { int k = i; for (j = i; j < a.length; j++){ if (a[j] < a[k]){ k = j; } } int temp = a[i]; a[i] = a[k]; a[k] = temp; } for (i = 0; i < a.length; i++) System.out.print(a[i] + \ \ System.out.println(); } } 循环开始前的数组元素依次是:2 1 4 8 9 5 3 第一次循环后:i = 0 j =6 k= 1 数组元素依次是1 2 4 8 9 5 3 第二次循环后:i =1 j =6 k=1 数组元素依次是1 2 4 8 9 5 3 第三次循环后:i =2 j =6 k=6 数组元素依次是1 2 3 4 8 9 5 第四次循环后:i = 3 j =6 k=3 数组元素依次是1 2 3 4 8 9 5 第五次循环后:i = 4 j =6 k=6 数组元素依次是1 2 3 4 5 8 9 第六次循环后:i =5 j =6 k=5 数组元素依次是1 2 3 4 5 8 9 第七次循环后:i = 6 j =6 k=6 数组元素依次是1 2 3 4 5 8 9 最后运行结果:1 2 3 4 5 8 9 3. 按照要求运行下面的程序,回答问题。 public class CommandParameter { public static void main(String[] args) { for(int i=0;i

4. 有如下数组 int myArray[] = { 1, 2, 3, 4, 5, 6 }; int yourArray[] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }; 请利用System.arraycopy方法编写一个程序,复制myArray数组的所有内容到yourArray数组,放在yourArray数组下标0开始的位置,并输出yourArray数组的每个元素。 public class S08_1 { public static void main(String[] args) { int myArray[] = { 1, 2, 3, 4, 5, 6 }; int yourArray[] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }; System.arraycopy(myArray, 0, yourArray, 0, myArray.length); for (int i = 0; i < yourArray.length; i++) { System.out.println(\+\+i+\+yourArray[i]); } } } yourArray[0]=1 yourArray[1]=2 yourArray[2]=3 yourArray[3]=4 yourArray[4]=5 yourArray[5]=6 yourArray[6]=4 yourArray[7]=3 yourArray[8]=2 yourArray[9]=1 11. 有整型数组,按顺序包含元素:10,7,9,2,4,5,1,3,6,8,请编写程序利用Arrays.sort方法对数组进行排序,并输出该数组的每个元素。 public class S08_11 { public static void main(String[] args) { int a[] = {10,7,9,2,4,5,1,3,6,8}; } System.out.println(\排序前:\); output(a); Arrays.sort(a); System.out.println(\排序后:\); output(a); } static void output(int[] a) { for (int i = 0; i < a.length; i++) { System.out.println(\ +i+ \+a[i]); } } 排序前: a[0]=10 a[1]=7 a[2]=9 a[3]=2 a[4]=4 a[5]=5 a[6]=1 a[7]=3 a[8]=6 a[9]=8 排序后: a[0]=1 a[1]=2 a[2]=3 a[3]=4 a[4]=5 a[5]=6 a[6]=7 a[7]=8 a[8]=9 a[9]=10 12. 补充完整下面的程序,使得程序能够计算出指定字符数组中连续字符块的个数: A countRuns( A ) 0 a 1 a a a a a 1 a a a b b c c c c 3 a a b b a b b 4 a b c d e f g 7 public class CountRuns { public static void main(String[] args) { char[] ch={};//重复用上面的字符数组来初始化,验证你的算法是否正确 int count=0; //请在此处补充程序 for(int i=0;i

实验目的: 1. 掌握类的定义,熟悉属性、构造函数、方法的作用,掌握用类作为类型声明变量和方法返回值; 2. 理解类和对象的区别,掌握构造函数的使用,熟悉通过对象名引用实例的方法和属性; 实验数据记录及分析(或程序及运行结果) 1. 写一个名为Rectangle的类表示矩形。其属性包括宽width、高height和颜色color,width和height都是double型的,而color则是String类型的。要求该类具有: (1) 使用构造函数完成各属性的初始赋值 (2) 使用getter和setter的形式完成属性的访问及修改 (3) 提供计算面积的getArea()方法 public class Rectangle { private double width; private double height; private String color; public Rectangle(double width, double height, String color) { this.width = width; this.height = height; this.color = color; } public double getWidth() { return width; } public void setWidth(double width) { this.width = width; } public double getHeight() { return height; } public void setHeight(double height) { this.height = height; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public double getArea() { return width * height; } public static void main(String[] args) { Rectangle rectangle = new Rectangle(10, 5.4, \); System.out.println(\+rectangle.getArea()); rectangle.setHeight(7.1); } System.out.println(\+rectangle.getArea()); } 2. 一副牌Deck有52张扑克Card组成(不含王牌),每张牌有自己的牌型suit(用char类型)和点数rank(用String类型),补充完整下面的类的定义。 public class Card { private char suit; private String rank; public Card( String rank, char suit) { this.suit = suit; this.rank = rank; } public String toString() { return suit+rank; } public static void main(String[] args) { } Card c=new Card(\,'红'); System.out.println(c.toString()); } 3. 银行的账户记录Account有账户的唯一性标识(11个长度的字符和数字的组合),用户的姓名,开户日期(Date),账户密码(六位的数字,可以用0开头),当前的余额。银行规定新开一个账户时,银行方面提供一个标识符、账户初始密码123456,客户提供姓名,开户时客户可以直接存入一笔初始账户金额,不提供时初始余额为0。定义该类,并要求该类提供如下方法:存款、取款、变更密码、可以分别查询账户的标识、姓名、开户日期、当前余额等信息。 public class Account { private String ID; private String name; private String date; private String pwd = \; private double currentValue = 0; public String getID() { return ID; } public String getName() { return name; } public void setName(String name) {

this.name = name; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public double getCurrentValue() { return currentValue; } public void setCurrentValue(double currentValue) { this.currentValue = currentValue; } public Account(String ID,String name) { this.ID = ID; this.name = name; } public void draw(double drawValue) { this.currentValue -= drawValue; } public void deposite(double depositeValue) { } this.currentValue += depositeValue; } public static void main(String[] args) { Account account1 = new Account(\,\); account1.setDate(\); System.out.println(account1.getID()); System.out.println(account1.getName()); System.out.println(account1.getDate()); System.out.println(account1.getCurrentValue()); } 4. 一个Fan有自己的品牌和型号,其调速旋钮speed可以调整Fan的速度(档级在0、1、2、3范围内),通电开关可以改变电扇状态(通电表示工作就绪或者工作,断电表示停止工作)请仔细分析并提供Fan类的定义。并编写程序对其进行测试。具体要求如下: (1) 表示该类对象的状态可以用品牌(brand,可以用字符串型表示,因为品牌通常都是多个字符组成的)、工作状态(status,用来反映一个电风扇是否处于通电就绪ready、正在转动working或者静止stop)、当前的速度(speed,可以用数值型表示); (2) 用构造函数可以创建一个电风扇对象,指定其品牌就可以了,一个电风扇的初始状态可以是静止,而且初始速度为0,分析为什么不适宜直接通过构造函数的形式参数来指定初始状态和速度; (3) 给该类提供如下的方法,重点考虑每个动作导致的状态变化,形成代码逻辑; ? 提供一个方法来表示电风扇的开与关,模拟一个开关动作 ? 通过加速和减速两个方法来调整速度,当速度超出极限(0或3),向控制台输出一条告警信息作为提示,并且不执行该调速动作。 ? 提供一个方法能够返回电风扇当前的状态和速度 (4) 添加一个main方法,按顺序完成以下工作,考虑状态与速度变化和开关动作之间的关系: ? 创建一个电风扇对象,用f表示; ? 加速一次电风扇; ? 向控制台输出f的状态和速度; ? 启动电风扇(调用对象的开关方法); ? 向控制台输出f的状态和速度; ? 连续加速4次(考虑发生什么情况); ? 向控制台输出f的状态和速度; ? 连续减速4次(考虑发生什么情况); ? 向控制台输出f的状态和速度; ? 关掉电风扇(调用对象的开关方法); ? 连续加速2次 ? 向控制台输出f的状态和速度; public class Fan { private String brand; public int status = 0; public int speed = 0; public String getBrand() { } public void setBrand(String brand) { } public int getStatus() { } public void setStatus(int status) { } public int getSpeed() { } public void setSpeed(int speed) { } public Fan(String brand) { } public void turn(boolean on) { } public void upSpeed() if (on) { } else { } status = 0; status = 1; this.brand = brand; this.speed = speed; return speed; this.status = status; return status; this.brand = brand; return brand; { } public void downSpeed() { } public void fanCondition() { System.out.println(this.getSpeed()); switch (status) { case 0: System.out.println(\静止stop\); break; this.speed--; if (this.status == 1 || this.status == 2) { } if (this.speed == 0) { } else if (this.speed >= 1 && this.speed <= 3) { } else { } System.out.println(\); this.speed++; this.status = 2; this.status = 1; this.speed++; if (this.status == 1 || this.status == 2) { } if (this.speed == 0) { } else if (this.speed >= 1 && this.speed <= 3) { } else { } System.out.println(\); this.speed--; this.status = 2; this.status = 1; case 1: } } } System.out.println(\通电就绪ready\); break; System.out.println(\正在转动working\); break; break; case 2: default: public static void main(String[] args) { } Fan fan = new Fan(\); fan.fanCondition(); fan.turn(true); fan.fanCondition(); fan.upSpeed(); fan.upSpeed(); fan.upSpeed(); fan.upSpeed(); fan.fanCondition(); fan.downSpeed(); fan.downSpeed(); fan.downSpeed(); fan.downSpeed(); fan.fanCondition(); fan.turn(false); fan.upSpeed(); fan.upSpeed(); fan.fanCondition(); 5. 解释下面的程序运行结果输出为什么是null public class My { String s; public void My(){ s = \ } public void go() { System.out.println(s); } public static void main(String args[]) { My m = new My(); m.go(); }

} m.s 为Constructor 6. 给出下面的类,找出后面的5个声明中,哪些是重载后的构造函数 public class ConstOver { public ConstOver (int x, int y, int z) { } } A. ConstOver ( ) { } B. Protected int ConstOver ( ) { } C. Private ConstOver (int z, int y, byte x) { } D. Public Object ConstOver (int x, int y, int z) { } E. Public void ConstOver (byte x, byte y, byte z) { } C 7. 给出下面的类,找出后面的5个声明中,哪些是重载后的setVar函数 public class MethodOver { public void setVar (int a, int b, float c) { } } A. Private void setVar (int a, float c, int b) { } B. Protected void setVar (int a, int b, float c) { } C. Public int setVar (int a, float c, int b) {return a;} D. Public int setVar (int a, int b, float c) {return a;} E. Protected float setVar (int a, int b, float c) {return c;} A、C、 实验11:面向对象编程基础(二)方法中的参数传递

实验目的: 1. 理解方法中的形参和实参传递在传递基本类型和引用类型时的差异 实验要求和过程 1. 程序运行后的输出是什么? class TestReference{ public static void main(String[] args){ int x=2; TestReference tr = new TestReference(); System.out.print(x); tr.change(x); System.out.print(x); } public void change(int num){ num = num + 1; } } 22 2. 写出程序运行结果 public class Foo { public static void main (String [] args) { StringBuffer a = new StringBuffer (“A”); StringBuffer b = new StringBuffer (“B”); operate(a,b);//调用了Foo类的一个类方法 System.out.printIn(a + “,” +b); } static void operate (StringBuffer x, StringBuffer y) { x.append(y); y = x; } } AB,B 3. 输入下面的类,结合实验十(2)中的Card类,完成下面的要求 public class JLab1201 { static final char suits[] ={'H','S','D','C'}; static final String ranks[] ={\ static Card[] cards=new Card[52]; /** * 初始化扑克牌数组 */ public static void init(){ for(int i=0;i

实验目的: 1. 理解访问控制修饰符的作用; 2. 掌握package的作用 实验要求和过程 1. 下列程序有错误,调试、写出错误原因并改正。 public class VariableScope { public static void main(String args[]) { int i=10; { int k=10; System.out.println(\ System.out.println(\ } System.out.println(\ System.out.println(\//k未定义 } } main方法外定义一个全局变量static int k = 11; 2. 在项目中创建两个包p1,将实验十(3)中的Account类移至p1下,保证Account类的账户余额属性balance的访问范围修饰为public,并在p1下创建一个测试类Test,如下: public class Test { } public static void main(String[] args){ } Account c=new Account(\,\丁怡\); System.out.println(\当前账户余额是:\); 执行下面的实验步骤,观察并分析程序中出现的现象。 1) 依次将balance前的访问范围修饰符变为protected、private和缺省,观察上面的Test程序会出现何种现象,如有错误,解释原因。 缺省、public和protected可以访问,但用private修饰之后不能直接访问。用private修饰之后,属性变为私有,不能直接访问。 2) 创建和p1并列的包p2,并将Account类从p1移至p2下,观察上面的Test程序会出现何种现象,如有错误,如何解决。 只有用public修饰的时候才能够直接访问,其他修饰符都不能直接访问。 3) 将p2下的Account类class前的public去掉,观察上面的Test类会出现何种现象,如有错误,可否解决。 无法访问Account类,如要访问Account类要改成public 4) 恢复Account类为public后,依次将balance前的访问范围修饰符变为protected、private和缺省,观察上面的Test程序会出现何种现象,如有错误,解释原因。 均不能访问balance,不在一个包中,只有public修饰的才能访问。 5) 比较并写出上述1和4中的异同。 1中是两个类在同一个包中,4中两个类不在同一个包中。 评语: 教师签字: 日期: 年 月 日 实验13:面向对象编程基础(四) 类的关系

实验目的: 1. 理解类之间的关联关系 2. 理解类之间的整体与部分关系 3. 理解类之间的组合/聚合关系 实验要求和过程 1. 定义一个类Deck,表示一副牌,每副牌包含52张牌(不含王牌,用数组实现) 1) Deck和Card之间属于什么关系。 Deck属于类,Card属于对象。Card属于Deck。 2) 定义一个构造方法,实现一副牌的初始化,即按照“黑、红、梅、方”的花色顺序,点数从A-K,生成52张扑克牌。 3) 提供一个方法show,按照每行13张,逐一显示全部的扑克牌。如 黑A黑2……黑K 红A红2……红K 梅A梅2……梅K 方A方2……方K 4) 提供一个show(int idx)方法,返回idx-1位置处的扑克牌对象。 public class Deck { static final char suits[] ={'黑','红','梅','方'}; static final String ranks[]

本文来源:https://www.bwwdw.com/article/s0xv.html

Top