package com.itheima;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.TreeSet;
public class Test1 {
/**
* 第一题: 有五个学生,每个学生有3门课(语文、数学、英语)的成绩,
* 写一个程序接收从键盘输入学生的信息,输入格式为:name,30,30,30(姓名,三门课成绩),
* 然后把输入的学生信息按总分从高到低的顺序写入到一个名称"stu.txt"文件中。
* 要求:stu.txt文件的格式要比较直观,打开这个文件,就可以很清楚的看到学生的信息。
* @author 乔栋
*/
public static void main(String[] args) {
//将键盘录入的数据写到集合中
TreeSet<Student> al = method_input();
//将此集合写到stu.txt文件中
method_write(al);
}
/** 将从键盘输入的数据,存储到TreeSet中
* 因为TreeSet有排序的功能
*/
public static TreeSet<Student> method_input(){
//键盘输入,加入缓冲,提高读写效率
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
TreeSet<Student> al = new TreeSet<Student>();
String temp = null;
Student s = null;
try {
while((temp=br.readLine())!= null){
//如果输入over则结束循环
if("over".equals(temp))
break;
String[] str = temp.split(",");
s = new Student();
//给学生对象设置值
s.setName(str[0]);
s.setChinese(Integer.parseInt(str[1]));
s.setMath(Integer.parseInt(str[2]));
s.setEnglish(Integer.parseInt(str[3]));
//将此对象加到TreeSet集合中
al.add(s);
}
} catch (IOException e) {
throw new RuntimeException("读取异常");
} finally{
if(br != null){
try {
br.close();
} catch (IOException e) {
throw new RuntimeException("关闭异常");
}
}
}
return al;
}
/**
* 将TreeSet中的数据写到stu.txt文件中
* @param al
*/
public static void method_write(TreeSet<Student> al){
BufferedWriter bw = null;
try {
//创建输出文件
bw = new BufferedWriter(new FileWriter("stu.txt"));
for(Student s:al){
//循环将每个学生对象输出
bw.write(s.toString());
bw.newLine();
bw.flush();
}
} catch (IOException e) {
throw new RuntimeException("写异常");
} finally{
if(bw != null){
try {
bw.close();
} catch (IOException e) {
throw new RuntimeException("关闭异常");
}
}
}
}
}
/**
* 创建学生类,因为要具备排序功能,所以将此对象放入TreeSet中
* TreeSet集合中的对象具备排序功能,所以要实现Comparable接口
*/
class Student implements Comparable{
//姓名
private String name;
//语文
private int chinese;
//数学
private int math;
//英语
private int english;
//总成绩
private int sum;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getChinese() {
return chinese;
}
public void setChinese(int chinese) {
this.chinese = chinese;
}
public int getMath() {
return math;
}
public void setMath(int math) {
this.math = math;
}
public int getEnglish() {
return english;
}
public void setEnglish(int english) {
this.english = english;
}
public int getSum() {
this.sum = this.chinese+this.math+this.english;
return sum;
}
public void setSum(int sum) {
this.sum = sum;
}
//重写此方法
@Override
public int compareTo(Object o) {
// TODO Auto-generated method stub
if(!(o instanceof Student))
throw new RuntimeException("对比的对象不是学生类");
Student s = (Student)o;
int num = this.getSum()-s.getSum();
//总成绩相同的情况下,用姓名排序
if(num == 0)
return this.getName().compareTo(s.getName());
return num;
}
@Override
public String toString(){
return "姓名:"+this.name+" 语文:"+this.chinese+" 数学:"+this.math+" 英语:"+" 总成绩"+this.getSum();
}
}
题目2:
package com.itheima;
import java.lang.reflect.Field;
public class Test2 {
/**
* 题目2:写一个方法,此方法可将obj对象中名为propertyName的属性的值设置为value.
public void setProperty(Object obj, String propertyName, Object value){}
思路:利用反射机制
*/
public static void main(String[] args) {
//new一个对象,其中有一个属性名为propertyName
TestReflect tr = new TestReflect();
//设置 tr对象中名为propertyName的属性的值
setProperty(tr,"propertyName","value=审阅老师好!");
//测试。。。。。。。。。
System.out.println("取出设置后此对象的值:"+tr.getPropertyName());
}
/**
* 此方法可将obj对象中名为propertyName的属性的值设置为value.
* @param obj
* @param propertyName
* @param value
*/
public static void setProperty(Object obj, String propertyName, Object value){
//获得此对象的Class文件
Class thisClass = obj.getClass();
try {
//获得此对象的属性对应的类
Field f = thisClass.getDeclaredField(propertyName);
//取消java语言访问检查,也就是说private修饰的成员也可见
f.setAccessible(true);
//利用反射,设置此对象的,属性为propertyName的值
f.set(obj, (String)value);
} catch (Exception e) {
throw new RuntimeException("反射异常");
}
}
}
/**
* 一个类,其中有一个属性名为propertyName
* @author 乔栋
*
*/
class TestReflect{
private String propertyName;
public String getPropertyName() {
return propertyName;
}
public void setPropertyName(String propertyName) {
this.propertyName = propertyName;
}
}
题目3:
package com.itheima;
public class Test3 {
/**
* 题目3:方法中的内部类能不能访问方法中的局部变量,为什么?
* 答:可以,因为但是局部变量必须声明为final类型。因为局部变量存在于栈内存中,随着方法的调用而产生,
* 方法调用结束,局部变量则被销毁。而内部类的生存周期可能比局部变量时间长,所以将变量定义成final,随着外部类的
* 消失而消失。内部类的生存周期依赖于外部类。
*/
public static void main(String[] args) {
OutClass out = new OutClass();
out.outFunction(50);
}
}
/**
* 局部内部类
* @author 乔栋
*
*/
class OutClass{
private String outStr = "i am outStr";
public void outFunction(final int a){
final int b = 100;
//内部类,访问外部类变量,访问局部变量
class InnerClass{
public void inFunction(){
System.out.println("访问外部类的成员变量"+outStr);
System.out.println("访问局部变量b:"+b);
System.out.println("访问局部变量a:"+a);
}
}
InnerClass in = new InnerClass();
in.inFunction();
}
}
题目4:
package com.itheima;
import java.lang.reflect.Method;
import java.util.ArrayList;
public class Test4 {
/**
* 题目4: ArrayList<Integer> list = new ArrayList<Integer>();
* 在这个泛型为Integer的ArrayList中存放一个String类型的对象。
*
* 思路:1.利用反射,反射出add方法的Method类
* 2.再调用invoke,将String类型添加进去
*/
public static void main(String[] args) {
//创建ArrayList数组,其中存放Integer类型的数据
ArrayList<Integer> list = new ArrayList<Integer>();
//往list中添加一些数据
list.add(886);
list.add(111);
list.add(666);
list.add(999);
//利用反射得到list对象所对应的Class文件
Class c = list.getClass();
try {
//得到方法名为"add"的Method类
Method method =c.getMethod("add", Object.class);
//反射调用add方法, 并添加String类型的数据
method.invoke(list, "审阅老师好");
method.invoke(list, "我看见你了。。。");
} catch (Exception e) {
throw new RuntimeException("没有找到相应的方法");
}
//输出既有Integer类型,又有String类型的的数组list
System.out.println(list);
}
}
题目5:
package com.itheima;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class Test5 {
/**
* 题目5: 统计一个文本文件中字符出现的次数,结果存入另外的一个文本文件中。例如:
a: 21 次
b: 15 次
c: 15 次
把: 7 次
当: 9 次
前: 3 次
,:30 次
思路:1.首先创建一个test5.txt,存入数据
2.读取此文本,将每个字符和出现的次数存储到ThreeMap(键值对应,键唯一,且数据有序)集合中
3.遍历出此ThreeMap中的数据
*/
public static void main(String[] args) throws Exception{
//创建test5.txt文本
createTxt();
//将Key,Value存入TreeMap集合中
TreeMap<String,Integer> tm= count();
//循环遍历结果
put_count(tm);
}
/**
* 首先,创建一个文本文件
* 为了方便,简化代码。就将异常抛出了。。
* @throws IOException
*/
public static void createTxt() throws IOException{
BufferedWriter bw = new BufferedWriter(new FileWriter("test5.txt"));
bw.write("把当前,aaaa+到c和bbbbfff间,,,ccc");
bw.flush();
bw.close();
}
/**
* 读取此文本,将每个字符和出现的次数存储到ThreeMap(键值对应,键唯一,且数据有序)集合中
* @return
* @throws IOException
*/
public static TreeMap<String,Integer> count() throws IOException{
//创建map对象
TreeMap<String,Integer> tm = new TreeMap<String,Integer>();
//读取文件流
BufferedReader br = new BufferedReader(new FileReader("test5.txt"));
String temp = null;
while((temp=br.readLine())!=null){
//将读到的字符串数据转成字符数组
char[] c = temp.toCharArray();
//遍历此字符数组
for(int x=0;x<c.length;x++){
//用于记录字符出现的次数
int count = 0;
//将每一个字符转化成String类型
String s = Character.toString(c[x]);
//获取此集合中指定Key的Value值
Integer i = tm.get(s);
/**
* 如果集合中不存在此Key,则加入集合,并且Value等于1
* 如果集合中存在此Key,则取出Value,并++
*/
if(i == null){
count = 1;
tm.put(s, count);
}else{
count = i;
count++;
tm.put(s, count);
}
count = 0;
}
}
return tm;
}
/**
*
* 循环遍历此TreeMap,即可得到每个字符出现的次数
* @param tm
*/
public static void put_count(TreeMap<String,Integer> tm){
Set<Map.Entry<String,Integer>> entry = tm.entrySet();
Iterator<Map.Entry<String,Integer>> it = entry.iterator();
while(it.hasNext()){
Map.Entry<String, Integer> me= it.next();
System.out.println(me.getKey()+":"+me.getValue()+"次");
}
}
}
题目6:
package com.itheima;
public class Test6 {
/**
* 题目6: 编写三各类Ticket、SealWindow、TicketSealCenter分别代表票信息、售票窗口、售票中心。
* 售票中心分配一定数量的票,由若干个售票窗口进行出售,利用你所学的线程知识来模拟此售票过程。
*
* 思路:1.生产和消费共享一个车票对象
* 2.有车票就停止生产,进行消费
* 3.没有车票就停止消费,进行生产
* 4.利用synchronized锁住这个车票对象
*/
public static void main(String[] args) {
//车票对象,售票中心(生产),售票窗口(消费)共享
Ticket t = new Ticket();
//售票中心开启
new Thread(new TicketSealCenter(t)).start();
//多个售票窗口同时售票
new Thread(new SealWindow(t)).start();
new Thread(new SealWindow(t)).start();
new Thread(new SealWindow(t)).start();
}
}
/**
* 票信息
* @author 乔栋
*
*/
class Ticket{
//票的称呼
private String name;
//票的编号
private int count = 0;
//是否有票
private boolean flag = false;
/**
* 生产车票
* 如果true则表示有车票,则不生产等待被消费。。
* 如果false表示没有车票,则生产车票,生产完后,叫醒所有等待者。若叫醒消费者,则消费,若叫醒生产者,
* 则会再次等待。
* @param s
*/
public synchronized void put(String s){
//当等待结束后,会再次判断flag
while(flag){
try {
this.wait();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
//车票的名称
this.name = "----"+s+(++count);
//生产一张车票
System.out.println(Thread.currentThread().getName()+"生产:"+name);
//有车票了,该进行消费了
this.flag = true;
//叫醒所有等待
this.notifyAll();
}
/**
* 消费车票
* 如果false,表示还没有车票,等待
* 如果true,生产出了车票,进行消费
*/
public synchronized void out(){
while(!flag){
try {
this.wait();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
System.out.println(Thread.currentThread().getName()+"消费:"+name);
this.flag = false;
this.notifyAll();
}
}
/**
* 票窗口
* @author 乔栋
*
*/
class SealWindow implements Runnable{
private Ticket ticket= null;
SealWindow(Ticket ticket){
this.ticket = ticket;
}
@Override
public void run() {
while(true){
ticket.out();
}
}
}
/**
* 售票中心
* @author 乔栋
*
*/
class TicketSealCenter implements Runnable{
private Ticket ticket= null;
TicketSealCenter(Ticket ticket){
this.ticket = ticket;
}
@Override
public void run() {
while(true){
ticket.put("车票");
}
}
}
题目7:
package com.itheima;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.TreeSet;
public class Test7 {
/**
* 题目7: 把以下IP存入一个txt文件,编写程序把这些IP按数值大小,从小到达排序并打印出来。
61.54.231.245
61.54.231.9
61.54.231.246
61.54.231.48
61.53.231.249
思路:1.按String类型比较,所以少于3位的ip前面都补齐0
2.先全部补2个0(利用正则表达式)
3.每位ip只保留3位。
4.存储到TreeSet(自动排序)集合中
5.输出时,利用正则将ip还原。
*/
public static void main(String[] args) throws Exception{
//将这些ip地址存储在一个ip.txt文件中
ip2Txt();
//将ip按从小到大打印出来
sortIP();
}
/**
* 将这些ip地址存储在一个ip.txt文件中
* @throws Exception
*/
public static void ip2Txt() throws Exception{
//输出流
BufferedWriter bw = new BufferedWriter(new FileWriter("ip.txt"));
bw.write("61.54.231.245");
bw.newLine();
bw.write("61.54.231.9");
bw.newLine();
bw.write("61.54.231.246");
bw.newLine();
bw.write("61.54.231.48");
bw.newLine();
bw.write("61.53.231.249");
bw.flush();
bw.close();
}
/**
* 将ip按从小到大打印出来
* @throws Exception
*/
public static void sortIP() throws Exception{
//输出流
BufferedReader br = new BufferedReader(new FileReader("ip.txt"));
/**
* TreeSet集合元素有序
* 所以讲ip存入此集合中
*/
TreeSet<String> ts = new TreeSet<String>();
String temp = null;
String ip = null;
while((temp=br.readLine())!=null){
//将ip的每一位补全至少3位
ip = temp.replaceAll("(\\d+)", "00$1");
//将ip的每一位,只保留3位。
ip = ip.replaceAll("0*(\\d{3})","$1");
ts.add(ip);
}
//遍历输出ip
for(String s:ts){
//将高位补了0的ip还原
String result = s.replaceAll("0*(\\d+)","$1");
System.out.println(result);
}
}
}
题目8:
package com.itheima;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Properties;
public class Test8 {
/**
* package cn.itcast.heima;
* public class DemoClass {
* public void run()
* {
* System.out.println("welcome to heima!");
* }
* }
*
* 题目8:
* (1) 写一个Properties格式的配置文件,配置类的完整名称。
* (2) 写一个程序,读取这个Properties配置文件,获得类的完整名称并加载这个类,
* 用反射 的方式运行run方法。
*/
public static void main(String[] args) {
try {
//获得配置文件的读取流
InputStream is = new FileInputStream("config.properties");
//创建属性集的对象
Properties pro = new Properties();
//从输入流中读取属性列表
pro.load(is);
is.close();
//获取类名和方法名称
String className = pro.getProperty("className");
String methodName = pro.getProperty("method");
//获得className的Class文件
Class c = Class.forName(className);
//创建实例对象
Object obj = c.newInstance();
//反射methodName方法
Method method = c.getMethod(methodName, null);
method.invoke(obj, null);
} catch (FileNotFoundException e) {
throw new RuntimeException("文件没找到");
} catch (IOException e) {
throw new RuntimeException("读取流异常");
} catch (ClassNotFoundException e) {
throw new RuntimeException("类没找到异常");
} catch (Exception e) {
throw new RuntimeException("反射时出现了异常");
}
}
}
题目9:
package com.itheima;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Test9 {
/**
* 题目9:使用TCP协议写一个可以上传文件的服务器和客户端。
*
* 思路:为了在一个主函数中运行客户端和服务端,将TCPClient和TCPServer都实现Runnable接口。
* 让着两个类同时运行。
*/
public static void main(String[] args) {
//客户端
new Thread(new TCPClient()).start();
//服务端
new Thread(new TCPServer()).start();
}
}
/**
* TCP客户端
* @author 乔栋
*
*/
class TCPClient implements Runnable{
@Override
public void run() {
try {
//连接指定主机ip地址和端口号
Socket s = new Socket("192.168.1.106",8888);
//创建发送的文件
File f = new File("stu.txt");
//读取文件
BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(f)));
//将文件写到输出流中
BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(s.getOutputStream()));
//文件中读取一行,就输出一行
String temp = null;
while((temp=br.readLine())!=null){
bw.write(temp);
bw.newLine();
bw.flush();
}
br.close();
bw.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
/**
* TCP服务器端
* @author 乔栋
*
*/
class TCPServer implements Runnable{
@Override
public void run() {
try {
//建立服务器端指定端口号
ServerSocket ss = new ServerSocket(8888);
//接收来自客户端的Socket
Socket s = ss.accept();
BufferedReader br = new BufferedReader(
new InputStreamReader(s.getInputStream()));
//将此客户端来的数据写到一个名为server.txt的文件中
BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream("server.txt")));
String temp = null;
while((temp=br.readLine())!=null){
bw.write(temp);
bw.newLine();
bw.flush();
}
System.out.println("客户端和服务端运行都结束,并生成了server.txt文件");
bw.close();
s.close();
ss.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
题目10:
package com.itheima;
import java.util.Scanner;
public class Test_10 {
/**
* 题目10: 金额转换,阿拉伯数字转换成中国传统形式。
* 例如:101000001010 转换为 壹仟零壹拾亿零壹仟零壹拾圆整
*
* 思路:1.利用Scanner读取键盘录入
* 2.查表找对应的汉字
* 3.利用正则表达式输出优化后的结果
*/
//定义两个数组类型的静态常量
private static final char[] data={'零','壹','贰','叁','肆','伍','陆','柒','捌','玖'};
private static final char[] units={'圆','拾','佰','仟','万','拾','佰','仟','亿','拾','佰','仟'};
public static void main(String[] args) {
//创建一个扫描去,用于键盘读取
Scanner s = null;
//循环,可以一直录入
while(true){
//键盘录入
s = new Scanner(System.in);
//获取一个长整型
long l = s.nextLong();
//将阿拉伯数字输出对应的中国汉字
System.out.println(convert(l));
}
}
/**
* 将输入的数字字符串转换成中国传统的汉字
* @param money
* @return
*/
public static String convert(long money){
//创建StringBuilder用来存储转化完的汉字
StringBuilder sb = new StringBuilder();
//下角标
int count = 0;
//money循环求余数,对应静态数组表,查找相应的汉字
while(money!=0){
//从右往左写,每次都是先写称谓,再写量词
sb.insert(0, units[count++]);
sb.insert(0,data[(int)(money%10)]);
money = money/10;
}
//将StringBuilder转化成String类型,并优化结果
String s = sb.toString();
s = s.replaceAll("零[仟佰拾]","零").replaceAll("零+万", "万").replaceAll("零+亿","亿").
replaceAll("亿万","亿零").replaceAll("零+", "零").replaceAll("零圆", "圆");
return s+"整";
}
}