写代码习惯不好,也不熟练,如有错误,请指出
1、自定义一个年龄异常类AgeException和一个学号异常类SnoException。定义一个学生类,学生类有三个私有成员变量姓名(Name)、学号(Sno)、年龄(age),为三个私有成员变量配置各自的getter、setter方法。其中,学号的长度不等于13时抛出学号异常,若年龄不在15-100之间抛出异常。为学生类编写无参构造方法。在测试类Test的主方法中测试上面的方法,并处理可能可能发生的异常。
package com.test1;
public class AgeException extends Exception {
String message;
public AgeException(String s) {
message = s;
}
public String getMessage() {
return message;
}
}
package com.test1;
public class SnoException extends Exception {
String message;
public SnoException(String s) {
message=s;
}
public String getMessage() {
return message;
}
}
package com.test1;
public class Student {
private String name;
private String sno;
private int age;
public String getName() {
return name;
}
public void setName (String name) {
this.name=name;
}
public String getSno() {
return sno;
}
public void setSno(String sno)throws SnoException{
if(sno.length()==13) {
}else {
throw new SnoException("学号长度异常 应为13位");
}
}
public int getAge () {
return age;
}
public void setAge(int age)throws AgeException{
if(age>100||age<15) {
throw new AgeException("年龄异常");
}
this.age=age;
}
public Student() {}
}
package com.test1;
public class Test {
public static void main(String[] args) {
Student s1 =new Student();
s1.setName("张三");
try {
s1.setSno("12345678911234");
s1.setAge(13);
}catch (AgeException e) {
//TODO 自动生成的catch块
e.printStackTrace();
}catch(SnoException e) {
e.printStackTrace();
}
}
}
在FileTest_1类中,创建主方法,主方法实现以下功能:判断D盘的mywork文件夹是否存在,若存在,判断1.txt文件是否存在,若存在显示文件属性并重命名为2.txt,若不存在创建2.txt文件;若mywork文件夹不存在则创建文件夹和2.txt文件。
package com.test1;
import java.io.*;
public class FileTest_1 {
public static void main(String[] args)throws IOException {
File f1=new File("D:\\mywork");
File f2=new File(f1,"1.txt");
File f3=new File(f1,"2.txt");
if(f1.exists()) {
if(f2.exists()) {
System.out.println(f2.getName());
f2.renameTo(f3);
}else f3.createNewFile();
}else {
f1.mkdir();
f3.createNewFile();
}
}
}
将“123456789”,写入D盘的“3.txt”中,使用字节输出流。
package com.test1;
import java.io.*;
public class FileTxt1 {
public static void main(String[] args)throws IOException{
File f1=new File("D:\\3.txt");
if(f1.exists()!=true)f1.createNewFile();
FileOutputStream fou=new FileOutputStream("D:\\3.txt");
String b="123456789";
byte a[]=b.getBytes();
fou.write(a,0,a.length);
fou.close();
}
}