本博客是个人作业的记录,也会记录标准答案供我自己进行对比,想找答案的可以直接忽略我的个人作业直接看标准答案
(一)编写一个Java Application程序,要求用户从键盘输入两个整型数据,求它们的商。
- 可以使用Scanner,nextInt()
- 要求处理NumberFormatException,ArithmeticException等异常
- 也可以使用BufferedReader和InputStreamReader, readLine()和parseInt()
标准答案:
方法一:
import java.util.*;
public class InputInteger1 {
public static void main(String args[]) {
double a, b, c;
Scanner reader = new Scanner(System.in);
try {
System.out.println("从键盘输入一个整型数");
a = reader.nextInt(); // reader调用方法为a赋值。
System.out.println("从键盘输入一个整型数");
b = reader.nextInt(); // reader调用方法为a赋值。
c = a / b;
System.out.printf("\nc=%f", c); // 添加输出结果c的代码。
} catch (NumberFormatException e) {
System.out.println("捕捉到一个数字格式异常");
} catch (ArithmeticException e) {
System.out.println("捕捉到一个算术异常");
} catch (IOException e) {
System.out.println(e);
} finally {
reader.close();
}
}
}
方法二:
import java.io.*;
public class InputInteger2 {
public static void main(String args[]) {
double a, b, c;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String s;
try {
System.out.println("从键盘输入一个整型数");
s = in.readLine();
a = Integer.parseInt(s);
System.out.println("从键盘输入另外一个整型数");
s = in.readLine();
b = Integer.parseInt(s);
c = a / b;
System.out.printf("\nc=%f", c); // 添加输出结果c的代码。
in.close();
} catch (NumberFormatException e) {
System.out.println("捕捉到一个数字格式4异常");
} catch (ArithmeticException e) {
System.out.println("捕捉到一个算术异常");
} catch (IOException e) {
System.out.println(e);
}
}
}
个人作业:
import java.util.*;
public class Division {
public static void main(String []args) {
Scanner scanner=new Scanner(System.in);
System.out.println("请输入两个整数:");
int a=scanner.nextInt();
int b=scanner.nextInt();
try {
System.out.println(a+"/"+b+"的结果为:"+a/b);
}catch(NumberFormatException e) {
System.out.println("数据格式异常");
}
catch(ArithmeticException e) {
System.out.println("算术运算异常");
}
catch(Exception e){
System.out.println("出现异常");
}
}
}
个人作业运行结果:
本题需要学会:
(1)Scanner的基本语句:
Scanner scanner=new Scanner(System.in);
int a=scanner.nextInt();
(2)BufferedReader的基本语句:
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
String s=reader.readLine();
(还得import java.io.* 和必须处理IOException)
(3)InputStreamReader的基本语句:
InputStreamReader reader=new InputStreamReader(System.in);
int a=reader.read();
(4)parseInt()用于把string转换为int:
String s="";
int a=Integer.parseInt(s);
(5)异常处理基本语句:
try {
检测语句
}catch(异常类型 e) {
处理语句
}
(二)将若干基本数据类型数据写入到一个文件,然后再按顺序读出。按模板要求,将【代码1】~【代码23】替换为Java程序代码。
个人作业:
import java.io.*;
public class NumberExample
{
public static void main(String args[])
{
int a1=12,a2=1180;
long b=808080;
float x1=3.14F,x2=12.456F;
double d=1234.9876;
boolean boo1=true,boo2=false;
char c='我';
File f= new File("D:\\作业\\java作业","NumberExample.txt"); //创建文件
try
{
FileOutputStream fos= new FileOutputStream(f); //创建指向f文件的输出流
DataOutputStream out_data=new DataOutputStream(fos);//创建指向fos的数据输出流
out_data.writeInt(a1);//out_data将数据a1写入到文件
out_data.writeInt(a2); //out_data将数据a2写入到文件
out_data.writeLong(b); //out_data将数据b写入到文件
out_data.writeFloat(x1); //out_data将数据x1写入到文件
out_data.writeFloat(x2); //out_data将数据x2写入到文件
out_data.writeDouble(d);//out_data将数据d写入到文件
out_data.writeBoolean(boo1); //out_data将数据boo1写入到文件
out_data.writeBoolean(boo2); //out_data将数据boo2写入到文件
out_data.writeChar(c); //out_data将数据c写入到文件
out_data.close();
}
catch(IOException e){}
try
{
FileInputStream fis= new FileInputStream(f);//创建指向f文件输入流
DataInputStream in_data= new DataInputStream(fis); //创建指向fis的数据输入流
System.out.println(in_data.readInt());//in_data读取int整数
System.out.println(in_data.readInt());//in_data读取int整数
System.out.println(in_data.readLong());//in_data读取long整数
System.out.println(in_data.readFloat());//in_data读取float整数
System.out.println(in_data.readFloat());//in_data读取float整数
System.out.println(in_data.readDouble());//in_data读取double整数
System.out.println(in_data.readBoolean());//in_data读取boolean整数
System.out.println(in_data.readBoolean());//in_data读取boolean整数
System.out.println(in_data.readChar());//in_data读取char整数
in_data.close();
}
catch(IOException e){}
}
}
运行结果:
本题需要学会:
(1)File的基本语句:
File f= new File("文件的路径");
同时可以在括号内加一个参数,如"r"表示文件仅为可读,"w"表示文件仅为可写,"rw"表示文件可以读写,true表示非覆盖写入
(2)各种输入输出流的用法:(得import java.io.* )
FileOutputStream fos= new FileOutputStream(f); //创建指向f文件的输出流
DataOutputStream out_data=new DataOutputStream(fos);//创建指向fos的数据输出流
FileInputStream fis= new FileInputStream(f);//创建指向f文件输入流
DataInputStream in_data= new DataInputStream(fis); //创建指向fis的数据输入流
创建这些流就可以调用流带有的函数进行一些读写操作,非常方便
一定要记得close()
(三)按模板要求,将【代码1】~【代码5】替换为Java程序代码。
个人作业:
import java.io.*;
public class RandomExample{
public static void main(String args[]){
File f=new File("D:\\"+"hello.txt");
try
{
RandomAccessFile random=new RandomAccessFile(f,"rw");//创建指向文件f的random对象
random.seek(0);//将random的读取位置定位在文件内容的开始处
long m=random.length();
while(m>=0)
{
m=m-1;
random.seek(m);//将random的读取位置定位在距文件开头m个字节
int c=random.readByte();//读取一个字节赋值给整型变量c
if(c<=255&&c>=0)
{
System.out.print((char)c);
}
else
{
m=m-1;
random.seek(m);//将random的读取位置定位在距文件开头m个字节
byte cc[]=new byte[2];
random.readFully(cc);
System.out.print(new String(cc));
}
}
random.close();
}
catch(IOException ee){}
}
}
本题需要学会:
(1)RandomAccessFile的用法:
RandomAccessFile random=new RandomAccessFile(f,"rw");//创建指向文件f的random对象
random.seek(0);//将random的读取位置定位在文件内容的开始处
random.seek(m);//将random的读取位置定位在距文件开头m个字节
int c=random.readByte();//读取一个字节赋值给整型变量c
(四)将一个Calendar对象写入文件,然后顺序读出该对象,并验证读出的对象是原始对象的克隆。按模板要求,将【代码1】~【代码9】替换为Java程序代码。
个人作业:
import java.util.*;
import java.io.*;
public class ObjectExample {
public static void main(String args[]) {
Calendar calendar1 = Calendar.getInstance(); // 创建一个日历对象
Calendar calendar2 = Calendar.getInstance(); // 创建一个日历对象
calendar1.set(1949, 9, 1); // 将日历时间设置为1949年10月1日,注意9表示十月
calendar2.set(2005, 9, 1);
try {
File f = new File("a.txt"); // 创建一个名字为"a.txt"的文件
FileOutputStream fileOut = new FileOutputStream(f); // 创建指向文件f的文件输出流
ObjectOutputStream objectOut = new ObjectOutputStream(fileOut); // 创建指向文件fileOut的对象输出流
objectOut.writeObject(calendar1); // objectOut写对象calendar1到文件
objectOut.writeObject(calendar2); // objectOut写对象calendar2到文件
FileInputStream fileIn = new FileInputStream(f); // 创建指向文件f的文件输入流
ObjectInputStream objectIn = new ObjectInputStream(fileIn); // 创建指向文件fileIn 的对象输入流
Calendar cloneCalendar1 = (Calendar) objectIn.readObject(); // objectIn读出对象
Calendar cloneCalendar2 = (Calendar) objectIn.readObject(); // objectIn读出对象
cloneCalendar1.setTime(new Date());
cloneCalendar2.set(9999, 9, 1);
int 年 = calendar1.get(Calendar.YEAR), 月 = calendar1.get(Calendar.MONTH) + 1,
日 = calendar1.get(Calendar.DAY_OF_MONTH);
System.out.printf("\ncalendar1的日期:%d-%d-%d", 年, 月, 日);
年 = calendar2.get(Calendar.YEAR);
月 = calendar2.get(Calendar.MONTH) + 1;
日 = calendar2.get(Calendar.DAY_OF_MONTH);
System.out.printf("\ncalendar2的日期:%d-%d-%d", 年, 月, 日);
年 = cloneCalendar1.get(Calendar.YEAR);
月 = cloneCalendar1.get(Calendar.MONTH) + 1;
日 = cloneCalendar1.get(Calendar.DAY_OF_MONTH);
System.out.printf("\ncloneCalendar1的日期:%d-%d-%d", 年, 月, 日);
年 = cloneCalendar2.get(Calendar.YEAR);
月 = cloneCalendar2.get(Calendar.MONTH) + 1;
日 = cloneCalendar2.get(Calendar.DAY_OF_MONTH);
System.out.printf("\ncloneCalendar2的日期:%d-%d-%d", 年, 月, 日);
} catch (Exception event) {
System.out.println(event);
}
}
}
运行结果:
本题需要学会:
(1)Calendar的用法:(import java.util.*;)
Calendar calendar = Calendar.getInstance(); // 创建一个日历对象
calendar.set(1949, 9, 1); // 将日历时间设置为1949年10月1日,注意月份从0开始算
int a=calendar.get(Calendar.YEAR);//得到年份(其他的可类似处理)
(2)ObjectOutputStream和ObjectInputStream的用法:
无论是字节输出流,还是字符输出流都不能直接写出对象
ObjectOutputStream可以将一个对象写出,ObjectInputStream可以读取一个对象到程序中,即序列化和反序列化
ObjectOutputStream objectOut = new ObjectOutputStream(fileOut); // 创建指向文件fileOut的对象输出流
objectOut.writeObject(calendar); // objectOut写对象calendar到文件
ObjectInputStream objectIn = new ObjectInputStream(fileIn); // 创建指向文件fileIn 的对象输入流
Calendar cloneCalendar = (Calendar) objectIn.readObject(); // objectIn读出对象
(五)按照要求编写程序
1. 撰写类MyLog,实现接口Loggable,完成在本地文件“MyLog.log”文件中的日志读写。
要求:
- 记录的日志内容包括:当前时间、日志类型、日志内容。
- 可以累加写入日志文件。如:
提示:
- 使用BufferedReader和BufferedWriter实现对日志文件的读写。
- 枚举的值:type.toString()
标准答案:
个人作业:
import java.io.*;
import java.util.*;
import java.text.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
interface Loggable {
/**
* 日志信息的三种类型 信息、警告、错误
*/
enum TYPE {
INFORMATION, WARNING, ERROR
};
/**
* 添加一条日志
*
* @param type 日志类型
* @param logContent 日志的内容
*/
void addLog(Loggable.TYPE type, String logContent);
/**
*
* @return 读出日志文件中的所有内容
*/
String readLog();
}
public class MyLog implements Loggable{
public void addLog(Loggable.TYPE type, String logContent) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("D:\\作业\\java作业\\MyLog.log",true));
Calendar calendar= Calendar.getInstance();
SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
writer.write("******************************\n");
writer.write(dateFormat.format(calendar.getTime())+'\n');
writer.write(type.toString()+'\n');
writer.write(logContent+'\n');
writer.write("******************************\n");
writer.close();
}catch(IOException e) {}
}
public String readLog() {
String s="";
try {
BufferedReader reader=new BufferedReader(new FileReader("D:\\作业\\java作业\\MyLog.log"));
while((s=reader.readLine())!=null) {
System.out.println(s);
}
reader.close();
}catch(IOException e) {}
return null;
}
public static void main (String[] args) {
MyLog log=new MyLog();
Scanner scanner=new Scanner(System.in);
System.out.println("请输入日志内容:");
String logContent=scanner.nextLine();
System.out.println("请输入日志类型(0:INFORMATION,1:WARNING,2:ERROR):");
int n=scanner.nextInt();
TYPE type=TYPE.INFORMATION;
switch(n){
case 0:
type=TYPE.INFORMATION;
break;
case 1:
type=TYPE.WARNING;
break;
case 2:
type=TYPE.ERROR;
break;
}
log.addLog(type, logContent);
log.readLog();
}
}
个人作业运行结果:
MyLog.log内:
本题需要注意:
(1)实现接口就是用一个类implements这个接口然后在类中实现接口中所有的方法
(2)BufferedWriter和BufferedReader
BufferedWriter writer = new BufferedWriter(new FileWriter("文件路径",true));
writer.write("写的一些东西");
writer.close();
BufferedReader reader=new BufferedReader(new FileReader("文件路径"));
String s=reader.readLine();
reader.close();
还得import java.io.* 和必须处理IOException
主函数就可以在后面写一个throws IOException(意思就是不用写try catch语句包裹住了)
注意readLine()每次读文件的一行,连续使用会持续读取下一行,因此可以用循环来读取文件的所有内容
(3)SimpleDateFormat日期格式的设置:
Calendar calendar= Calendar.getInstance();
SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFormat.format(calendar.getTime());
(4)枚举类型的使用:
enum TYPE {
INFORMATION, WARNING, ERROR
};TYPE type=TYPE.INFORMATION;
switch(n){
case 0:
type=TYPE.INFORMATION;
break;
case 1:
type=TYPE.WARNING;
break;
case 2:
type=TYPE.ERROR;
break;
}
枚举类型要调用自己的东西初始化,不是随便自己输入一个字符串就可以
若要自行选择枚举类型,可以搭配switch case语句使用
2. 分别使用FileOutputStream和BufferedOutputStream向二进制文件(如:Numbers.dat)中写入10万个随机数(double),比较用时的多少。将结果以及异常信息记录在日志文件中(使用上面的MyLog类记录日志)。
运行效果如下:
日志文件内容:
如果将本例写入文件属性设置为“只读”,运行程序后,日志新增记录:
提示:计算用时的方法:
- long startTime = System.currentTimeMillis();
- long endTime = System.currentTimeMillis();
- long cost = endTime - startTime;
标准答案:
个人作业:
package MYLOG;
import java.io.*;
import java.util.*;
import MYLOG.Loggable.TYPE;
public class NumberOutput {
public static void main (String[] args) {
File file=new File("D:\\作业\\java作业\\Numbers.dat","r");//这里随题目要求改
MyLog log=new MyLog();
Random random = new Random();
try{
//FileOutputStream out1=new FileOutputStream(file);
DataOutputStream out1 =new DataOutputStream(new FileOutputStream(file));
long startTime = System.currentTimeMillis();
for(int i=0;i<100000;i++) {
out1.writeDouble(random.nextDouble());
}
long endTime = System.currentTimeMillis();
long cost = endTime - startTime;
log.addLog(TYPE.INFORMATION, ("Done,cost "+cost+" without buffer"));
}
catch (FileNotFoundException e)
{
log.addLog(TYPE.ERROR, ("文件拒绝访问"));
}
catch (IOException e)
{
System.out.println("读取过程存在异常");
}
try{
//BufferedOutputStream out2=new BufferedOutputStream(new FileOutputStream(file));
DataOutputStream out2 =new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
long startTime = System.currentTimeMillis();
for(int i=0;i<100000;i++) {
out2.writeDouble(random.nextDouble());
}
long endTime = System.currentTimeMillis();
long cost = endTime - startTime;
log.addLog(TYPE.INFORMATION, ("Done,cost "+cost+" with buffer"));
}
catch (FileNotFoundException e)
{
log.addLog(TYPE.ERROR, ("文件拒绝访问"));
}
catch (IOException e)
{
System.out.println("读取过程存在异常");
}
}
}
文件可读或不可读运行后MyLog.log文件内容为:
本题需要注意:
(1)Random产生随机数:
Random random = new Random();
int n1 = random.nextDouble();
int n2 = random.nextInt();
nextDouble()返回一个大于或等于0.0且小于1.0的随机浮点数
(当然也可以用Math.random()随机产生大于等于0.0且小于1.0的伪随机double 值)
nextInt()返回一个-231到230的随机整数,nextInt(n)返回一个0到n的随机整数
可以用*多少再+多少的形式来调整范围
想产生多少个随机数就写个多少次的循环
(2)向文件中写入double类型的数据
由于题目要求使用FileOutputStream和BufferedOutputStream来向文件中写入数据进行对比,但是FileOutputStream和BufferedOutputStream没有写入double类型数据的函数,而DataOutputStream中有写入double类型数据的函数,因此就需要进行一些“套娃”
DataOutputStream out1 =new DataOutputStream(new FileOutputStream(file));
DataOutputStream out2 =new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
(3)计算用时的方法(虽然是题目给的但也挺有意思的)
long startTime = System.currentTimeMillis();
long endTime = System.currentTimeMillis();
long cost = endTime - startTime;
(4)出现异常的情况就用catch来捕获就好,反正输入也需要处理IOException
3.编写查询程序,输入要查询的数字的索引,在2.中的文件中查询这个数显示到屏幕上。
运行示例:
标准答案:
个人作业:
package MYLOG;
import java.io.*;
import java.util.*;
import MYLOG.Loggable.TYPE;
public class FindNumber {
public static void main (String[] args) {
File file=new File("D:\\作业\\java作业\\Numbers.dat");
try {
Scanner scanner=new Scanner(System.in);
//DataInputStream in=new DataInputStream(new FileInputStream(file));
System.out.println("Input the index:");
int index=scanner.nextInt();
RandomAccessFile random=new RandomAccessFile(file,"r");
random.seek(index*8);
/*
* double n=0.0; while(index!=-1) { n=in.readDouble(); index--; }
* System.out.println("The number is:"+n);
*/
System.out.println("The number is:"+random.readDouble());
random.close();
}catch (FileNotFoundException e){}
catch(IOException e) {}
}
}
运行结果:
本题需要注意:
(1)根据数字索引
这里我想到了两种方法,一种即是注释掉的利用DataInputStream里的readDouble()函数一个个地读过去,但要注意是从第0个数开始读;另一种是利用RandomAccessFile里的seek()函数来定位读取文件的位置
本次记录就到这~~虽然感觉内容挺多的,但学到和巩固到的也很多!