1.实验目的
(1)掌握异常类的用法
(2)掌握Java中String类常用方法、StringBuilder类的用法;
(3)掌握Date类、Calender类、DateFormat类的用法;
(4)掌握Java中正则表达式的基本用法。
2.实验要求
在Eclipse下创建Practice2项目,对未有包名要求的题目统一按照实验题名建包,然后将本题源代码放在同一包下。对有包名要求的题目按照要求建包。作业提交时将Practice2项目下src文件包中的所有源码文件提交至码云oop_two项目代码仓库中。
3.实验题目
Exer1: 创建KeyWord类,设置两个String型成员变量input,keyword,并设计keywordSearch()实现keyword字符串在input字符串中出现信息的统计。要求如下
- 统计结果返回类型为String,格式要求 出现总次数:索引位置(依次列出,如果出现多处,中间用空格分隔)。
- KeywordSearch()方法在处理返回结果时的中间变量分别用String和StringBuffer型实现,思考这两种处理方式的区别?
测试数据:
执行的测试 | 期望的结果 |
keywordSearch(“this is a test”, “is”) | 2: 2 5 |
keywordSearch(“able was I ere I sawelba”, “a”) | 4: 0 6 18 23 |
keywordSearch(“this is a test”, “tasta”) | 0: |
KeyWord.java
package Exer1;public class KeyWord {String input;String keyword;public void keywordSearch(String input,String keyword) {this.input = input;this.keyword = keyword;int i = 0,j=0;int sum = 0;int len = input.length();int len1 = keyword.length();int a[] = new int[10];int js =0;// System.out.println(keyword);while (j <= len) {i = input.indexOf(keyword);if(i!=-1) {sum +=1;input = input.substring(i+len1);if(sum==1) {a[js] = i;// System.out.print("a["+js+"]"+"=" +i +" ");j=i;}else {j +=( i+len1);a[js] = j;//System.out.print("a["+js+"]"+"=" +j+" ");}js+=1;}else if(i == -1){break;}}System.out.print(sum+":");if(sum !=0) {for(i=0;i< sum; i++){System.out.print(a[i] + " ");}}else if(sum == 0) {System.out.println("");}}
}
Exer1.java
package Exer1;public class Exer1 {public static void main(String[] args) {// TODO Auto-generated method stubKeyWord keyword = new KeyWord();keyword.keywordSearch("this is a test", "is");System.out.println("\n");keyword.keywordSearch("able was I ere I sawelba", "a");System.out.println("\n");keyword.keywordSearch("this is a test", "tasta");System.out.println("\n");}}
编译运行
2:2 5 4:0 6 18 23 0:
Exer2: 编写程序剔除一个字符串中的全部[.]和数字之外的字符,然后计算所有字符串数字的和。测试数据“hello13.45你,好8789与(0.57sum”。
package Exer2;import java.util.*;class tichu{public static double giveSum(String s) {Scanner scanner = new Scanner(s);scanner.useDelimiter("[.]|[^0123456789.]");double sum = 0;while(scanner.hasNext()) {try {double m = scanner.nextDouble();sum = sum+m;}catch(InputMismatchException e) {String t = scanner.next();}}return sum;}// scanner.close();}
public class Exer2 {public static void main(String[] args) {// TODO Auto-generated method stubString s = "hello13.45你,好8789与(0.57sum" ;double sum = tichu.giveSum(s);System.out.println("总和为:"+sum);}}
编译运行
总和为:8904.0
Exer3: 有四个类,主类Store在包jp.p4中,Mobile、Mp3Player、Product在包jp.p4.data中,Mobile、Mp3Player是Product的子类,Product和Store代码如下:
Store.java源代码:
package cn.edu.nwsuaf.jp.p4;
import java.util.Arrays;
import javax.swing.JOptionPane;
import cn.edu.nwsuaf.jp.p4.data.Mobile;
import cn.edu.nwsuaf.jp.p4.data.Mp3Player;
import cn.edu.nwsuaf.jp.p4.data.Product;
public class Store {
//** Defines the entry point of the application. */
public static void main(String[] args) {
// Creates two mobile phone objects.
Mobile mobile1 = new Mobile("China Mobile", "E365",1780);
Mobile mobile2 = new Mobile("China Mobile", "M330",1450);
Mp3Player player1 = new Mp3Player("Meizo X3", 256, 399);
Mp3Player player2 = new Mp3Player("Meizo E5", 512, 580);
Mp3Player player3 = new Mp3Player("Xlive XM MP3 Play",256, 930);
Product[] products={mobile1,mobile2,player1,player2, player3};
Arrays.sort(products);
String text = "";
for(int index = 0; index <products.length; ++index)
text += products[index].toString()+"\n";
// Displays the two mobile phones in a dialog box.
JOptionPane.showMessageDialog(null,"The products
are:\n\n"+text+"\nThere are "+Product.getCount()
+" products.");
}
}
Product.java源代码:
package cn.edu.nwsuaf.jp.p4.data;
public abstract class Product implements Comparable<Product> {
/** Holds the name of the product. */
protected String name;
/** Holds the price of the product. */
protected float price;
/** Holds the number of products. */
protected static int count;
/** Create a new product object. */
protected Product(String name, float price) {
this.name = name;
this.price = price;
++count;
}
/** Gets the name of the product. */
public String getName() {
return name;
}
/** Gets the price of the product. */
public float getPrice() {
return price;
}
/** Gets the number of products. */
public static int getCount() {
return count;
}
/** Compares this product with the given product. */
public int compareTo(Product product) {
return new Float(product.getPrice()).compareTo(price);
}
}
[基本要求] 设计类Mobile和类MP3Player,使它们和类Product、Store组成一个完整的程序,并且在Product类中添加销售日期属性及销售额属性,在sell方法中对其初始化,比较Date类与Calender类的用法,最后使用SimpleDateFormat类对销售日期进行格式化;用类DecimalFormat的相关方法格式化属性sales,熟悉DecimalFormat的用法。运行结果如图3-1所示。60 80 50 30 20
图3-1
Product.java
package jp.p4.data;import java.util.*;
import java.text.*;public abstract class Product implements Comparable<Product> {protected String name;protected Date date;public float sales;protected float price;protected static int count;/** Create a new product object. */protected Product(String name, float price) {this.name = name;this.price = price; ++count; }public String getName() {return name;}public float getPrice() {return price;}public static int getCount() { //实例方法可以操作类变量return count;}public int compareTo(Product product) {return new Float(product.getPrice()).compareTo(price);}public void sell(int count1) {sales = price *count1;}}
Store.java
package jp.p4;import java.util.Arrays;
import jp.p4.data.*;
import javax.swing.JOptionPane;
public class Store {public static void main(String[] args) {Mobile mobile1 = new Mobile("China Mobile", "E365",1780);mobile1.sell(60);Mobile mobile2 = new Mobile("China Mobile", "M330",1450);mobile2.sell(80);Mp3Player player1 = new Mp3Player("Meizo X3", 256, 399);player1.sell(20);Mp3Player player2 = new Mp3Player("Meizo E5", 512, 580);player2.sell(30);Mp3Player player3 = new Mp3Player("Xlive XM MP3 Play",256, 930);player3.sell(50);Product[] products={mobile1,mobile2,player1,player2, player3};Arrays.sort(products);String text = "";for(int index = 0; index <products.length; ++index)text += products[index].toString()+"\n";// Displays the two mobile phones in a dialog box.JOptionPane.showMessageDialog(null,"The products are:\n\n"+text+"\nThere are "+ Product.getCount()+" products.");}}
Mobile.java
package jp.p4.data;import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;public class Mobile extends Product{protected String xinghao;public Mobile(String name,String xinghao,int price){super(name, price);this.xinghao = xinghao;}public String toString() {date = new Date();SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");DecimalFormat decimalformat = new DecimalFormat(",000¤");String s= String.format("%.1f", price);return xinghao+":"+s+" RMB,date and time of sales:"+simpleDateFormat1.format(date)+",sales:"+decimalformat.format(sales);}
}
Mp3Player.java
package jp.p4.data;import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;public class Mp3Player extends Product {protected int xinghao;public Mp3Player(String name,int xinghao,int price){super(name, price);this.xinghao = xinghao;}public String toString() {date = new Date();SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");DecimalFormat decimalformat = new DecimalFormat(",000¤");String s= String.format("%.1f", price);return name+":"+ s +" RMB,date and time of sales:"+simpleDateFormat1.format(date)+",sales:"+decimalformat.format(sales);}
}
编译运行
Exer 4: 以下代码在执行时将出现异常,请用try-catch异常处理机制对其进行改写。
public class ExceptionDemo{
public static void main(String[] args){
String s=null;
int i,sum=0,a=5,b=0;
int c[]={1,2,3,4,5};
int len=s.length();
for(i=0;i<=5;i++){
sum=sum+c[i];
}
System.out.println(“a/b=”+a/b);
}
}
package Exer4;public class ExpectionDemo {public static void main(String[] args) {// TODO Auto-generated method stubtry{ String s=null;int len=s.length();}catch(java.lang.NullPointerException e) {System.out.println("发生异常:"+e.getMessage());}try {int a=5,b=0;System.out.println("a/b="+a/b);}catch (java.lang.ArrayIndexOutOfBoundsException e) {System.out.println("发生异常:"+e.getMessage());}catch(java.lang.ArithmeticException e) {System.out.println("发生异常:"+e.getMessage());}try {int i,sum=0;int c[]={1,2,3,4,5};for(i=0;i<=5;i++){sum=sum+c[i];}}catch (java.lang.ArrayIndexOutOfBoundsException e) {System.out.println("发生异常:"+e.getMessage());}}}
编译运行
发生异常:null
发生异常:/ by zero
发生异常:5
Exer 5: 编写一个程序,输入一个班某门课程成绩,统计及格人数、不及格人数,平均分。设计一个异常类,当输入的成绩小0分或大于100分时,抛出异常,程序将捕捉这个异常,并作出相应处理。
package Exer5;public class ErrorException extends Exception{private static final long serialVersionUID = 1L;/*这个警告一般来讲不影响程序的运行,它的意思是:序列化类XXX 没有声明serialVersionUID,也就是让你在类中设置serialVersionUID的属性。解决办法:手动设置:在类中加上一行,serialVersionUID的值自己设置,我这里写的是1L。*/String message;public ErrorException(int n){message ="输入的成绩为:"+n+",小于0分或大于100分,不符合系统要求。"; }public String warnMess() {return message;}
}
package Exer5;import java.util.Random;public class s {public int m;public int grade[];s(int m) {Random r = new Random();this.m = m;grade = new int[m];//注意中括号不要写错int i;for(i=0;i<m;i++) {grade[i]= r.nextInt(101); //生成一个[0,101)之间的随机数//grade[i]= r.nextInt(101)-20; //生成一个[-20,81)之间的随机数//grade[i]= r.nextInt(101)+20; //生成一个[20,121)之间的随机数//System.out.println(grade[i]+"\n");}}public void Array() throws ErrorException {int i=0;for(i=0;i<m;i++) { if(grade[i]>100||grade[i]<0) {throw new ErrorException(grade[i]);}}int sum=0,jg=0,bjg=0;int pjf=0;for ( i=0;i<m;i++){if(60 <= grade[i] && grade[i]<= 100) {jg+=1;}else if(0 <= grade[i] && grade[i]< 60) {bjg+=1;}sum += grade[i];}pjf = sum/m;System.out.printf("该班级的及格人数为"+jg+",不及格人数为"+bjg+",平均分为"+pjf);}}
package Exer5;public class Exer5 {public static void main(String[] args) {s s1 = new s(30);try {s1.Array();}catch(ErrorException e) {System.out.println(e.warnMess());}}}
编译运行
该班级的及格人数为11,不及格人数为19,平均分为48
Exer 6: 创建异常类的练习。需要使用3个Java程序来实现:
Bank.java
InsufficientFundsException.java
ExceptionDemo.java
(1) 创建银行类Bank,包括如下的方法:
Bank(double balance)
deposite(double dAmount)
withdrawal(double dAmount)
show_balance()
(2) 创建异常类:InsufficientFundsException。若取钱数大于余额则作为异常处理。创建此异常类的思路是:(1)产生异常的条件是余额少于取额, 因此是否抛出异常要判断条件(注意throw的使用)。(2)取钱是withdrawal()方法中定义的动作,因此在该方法中产生异常。(3)处理异常安排在调用withdrawal()的时候,因此withdrawal()方法要声明异常,由上级方法调用(注意throws的使用)。创建此异常类的具体要求:异常类中需添加 exceMessage()方法,用于调用Bank类的show_balance()方法,显示“您的取款金额为XXX,但是账户余额仅为XXX,操作不合法!”。
(3) 创建主类: ExceptionDemo,用于测试新创建的两个类。 注意try-catch语句的使用, 并且在错误处理的catch块中,使用InsufficientFundsException异常类的excepMesagge()方法以及Exception类(父类)的toString()方法。最后添加finally块,输出“操作退出!”。
package Exer6;public class ExceptionDemo {public static void main(String[] args) {// TODO Auto-generated method stubBank bank = new Bank(3000);try {bank.withdrawal(1000);bank.deposite(200);bank.withdrawal(4000);}catch(InsufficientFundsException e) {e.exceMessage();}finally {System.out.println("操作退出!");}}}
package Exer6;public class InsufficientFundsException extends Exception {private static final long serialVersionUID = 1L;String message;double balance;double dAmount;public InsufficientFundsException(double dAmount,double balance) {this.dAmount = dAmount;this.balance = balance;}public void exceMessage(){Bank b1 = new Bank(balance);b1.show_balance(dAmount);}
}
package Exer6;public class Bank {double balance;Bank(double balance){this.balance = balance;}void deposite(double dAmount){ //存款balance += dAmount;System.out.println("账户存入"+dAmount+"元");}void withdrawal(double dAmount) throws InsufficientFundsException { //取款if(dAmount >balance) {throw new InsufficientFundsException(dAmount,balance);}balance -= dAmount;System.out.println("账户取出"+dAmount+"元");}public void show_balance(double dAmount){System.out.println("您的取款金额为:"+dAmount+",但是账户余额仅为"+balance+",操作不合法") ;}
}
编译运行
账户取出1000.0元
账户存入200.0元
您的取款金额为:4000.0,但是账户余额仅为2200.0,操作不合法
操作退出!