黑马程序员_基础练习(1)

来源:互联网 发布:淘宝店铺转让后 编辑:程序博客网 时间:2024/05/22 10:50
------------ android培训java培训、java博客、java学习型技术博客、期待与您交流! -------------
<div style="text-align: center;">// 1、模拟String类trim方法,去除字符串两端的空格</div>class Test {public static void main(String[] args) {String str = "   iamunique  ";str = myTrim1(str);System.out.println(str);}public static String myTrim1(String str){int start=0,end=str.length()-1;while (str.charAt(start)==' '){start++;}while (str.charAt(end)==' '){end--;}return str.substring(start,end+1);//注意此处需加1}}

// 2、将一个字符串进行反转,将字符串中指定部分进行反转,例如“abcdefg”-"abfdceg"class Test{public static void main(String[] args){String str = "abcdefg";str = myReverse(str,2,5);System.out.println(str);}public static String myReverse(String str,int start,int end){char[] chs = str.toCharArray();for (;start<end;start++,end--){swap(chs,start,end);}return new String(chs);}public static void swap(char[] chs,int start,int end){char temp = chs[start];chs[start] = chs[end];chs[end] = temp;}}

// 3,获取一个字符串在另一个字符串出现的次数,例如:"abkkcdkkefkkskk"class Test{public static void main(String[] args){String s1 = "abkkcdkkefkkskk";String s2 = "kk";System.out.println(getCount(s1,s2));}public static int getCount(String s1,String s2){int count = 0,begin = 0;while (s1.indexOf(s2,begin)!=-1){begin = s1.indexOf(s2,begin)+s2.length();count++;}return count;}}

//4、获取两个字符串中最大的相同字串class Test{public static void main(String[] args){String s1="abcwerthelloyuiodef";String s2="cvhellobnm";System.out.println(MaxSub(s1,s2));}public static String MaxSub(String s1,String s2){//先明确哪个字符串长,哪个短String maxStr = s1.length()>s2.length()?s1:s2;String minStr = s1.length()>s2.length()?s2:s1;//嵌套for循环,将短的字符串从最长到依次减少1个长度进行匹配for (int x=0;x<minStr.length();x++){for (int start=0,end=minStr.length()-x; end<=minStr.length() ; start++,end++){if(maxStr.contains(minStr.substring(start,end)))return minStr.substring(start,end);}}return null;}}

/* 5、两个窗口同时卖票,验证非静态同步函数所是this   同理可将ticket变量用静态修饰,同步函数变为静态的来验证静态函数的锁是类名.class对象 */class Ticket implements Runnable{private int ticket = 100;boolean flag = true;public void run(){if(flag){while(true){synchronized(this){  //验证非静态同步函数是不是this,看所得票是否有误if (ticket>0){try{Thread.sleep(10);}catch(Exception e){}System.out.println(Thread.currentThread().getName()+".."+ticket--);}}}}elsewhile(true)method();}public synchronized void method(){if (ticket>0){try{Thread.sleep(10);}catch(Exception e){}System.out.println(Thread.currentThread().getName()+":::"+ticket--);}}}class Test{public static void main(String[] args){Ticket t = new Ticket();new Thread(t).start();try{Thread.sleep(10);}catch(Exception e){}//保证第一个线程进入到第一个循环里t.flag = false;  //让第二个线程进入第二个循环里new Thread(t).start();}}

// 6、单例设计模式,饿汉式和懒汉式class Single_1{private static final Single_1 instance = new Single_1();private Single_1(){}public static Single_1 getInstance(){return instance;}}class Single_2{private static Single_2 instance = null;private Single_2(){}public static Single_2 getInstance(){if(instance==null){synchronized(Single_2.class){if(instance==null)instance = new Single_2();}}return instance;}}class Text{public static void main(String[] args){Single_1.getInstance();Single_2.getInstance();}}


/*7、线程间通信,两个生产者生产商品,两个消费者消费商品,且生产一个就对应消费一个思路:资源类,属性商品,行为生产和消费生产者类,两个线程同步调用资源对象生产方法消费者类,两个线程同步调用资源对象消费方法生产一个后该线程需等待消费完才能再开始*/class Resource{private String product;private int count=1;private boolean flag = true;public synchronized void set(String product){while(!flag){//用if会导致多个生产而消费一个或消费多个却只生产一个try{wait();}catch(Exception e){e.printStackTrace();}}this.product = product;System.out.println(Thread.currentThread().getName()+" 生产"+product+count);flag = false;notifyAll();//只notify就有可能导致线程全部等待}public synchronized void get(){while(flag){try{wait();}catch(Exception e){e.printStackTrace();}}System.out.println(Thread.currentThread().getName()+"   消费"+product+count++);flag = true;notifyAll();}}class Producer implements Runnable{private String product="商品";private Resource res;Producer(Resource res){this.res = res;}public void run(){while(true){res.set(product);}}}class Consumer implements Runnable{private Resource res;Consumer(Resource res){this.res = res;}public void run(){while(true){res.get();}}}class Test{public static void main(String[] args){Resource res =new Resource();Producer pro = new Producer(res);Consumer con = new Consumer(res);new Thread(pro).start();new Thread(con).start();new Thread(pro).start();new Thread(con).start();

// 练习7,用lock锁来实现该需求import java.util.concurrent.locks.*;class Resource{private String product;private int count =1;private boolean flag=false;private Lock lock = new ReentrantLock();private Condition condition_pro = lock.newCondition();private Condition condition_con = lock.newCondition();public void set(String product){lock.lock();try{while (flag)condition_pro.await();this.product = product+count++;System.out.println(Thread.currentThread().getName()+"生产:"+this.product);flag = true;condition_con.signal();}catch(InterruptedException e){}finally{lock.unlock();}}public void get() {lock.lock();try{while (!flag)condition_con.await();System.out.println(Thread.currentThread().getName()+"消费:  "+product);flag = false;condition_pro.signal();}catch(InterruptedException e){}finally{lock.unlock();}}}class Producer implements Runnable{private Resource res;Producer(Resource res){this.res = res;}public void run(){while (true)res.set("商品-");}}class Consumer implements Runnable{private Resource res;Consumer(Resource res){this.res = res;}public void run(){while (true)res.get();}}class Text{public static void main(String[] args){Resource res = new Resource();Producer pro = new Producer(res);Consumer con = new Consumer(res);new Thread(pro).start();new Thread(pro).start();new Thread(con).start();new Thread(con).start();}}

// 8、取出ArrayList集合中的重复元素import java.util.*;class Demo2 {public static void main(String[] args) {ArrayList<String> al = new ArrayList<String>();al.add("java01");al.add("java02");al.add("java01");al.add("java02");al.add("java01");al.add("java03");sop(singleElement(al));}public static ArrayList<String> singleElement(ArrayList<String> al){ArrayList<String> newAl = new ArrayList<String>();Iterator<String> it = al.iterator();while (it.hasNext()){String s = it.next();if (!newAl.contains(s))newAl.add(s);}return newAl;}public static void sop(Object obj){System.out.println(obj);}}

/*9、将自定义对象作为元素存到ArrayList集合中,并去除重复元素   比如:存人对象,同姓名同年龄,视为同一个人,为重复元素,   将取出重复元素类定义成了泛型类*/import java.util.*;class Person{private int age;private String name;Person(String name,int age){this.name = name;this.age = age;}public String getName(){return name;}public int getAge(){return age;}public boolean equals(Object obj){if (!(obj instanceof Person))throw new ClassCastException("no Person");Person s = (Person)obj;return  this.name.equals(s.name) && this.age == s.age;}public String toString(){return this.name+":"+this.age;}}class Test{public static void main(String[] args) {ArrayList<Person> al = new ArrayList<Person>();al.add(new Person("lisi01",30));al.add(new Person("lisi02",32));al.add(new Person("lisi03",33));al.add(new Person("lisi04",35));al.add(new Person("lisi02",32));al.add(new Person("lisi04",35));SingleElement<Person> se = new SingleElement<Person>();al = se.singleElement(al);System.out.println(al);}}class SingleElement<T>//将泛型应用在类上{public  ArrayList<T> singleElement(ArrayList<T> al){ArrayList<T> newAl = new ArrayList<T>();Iterator<T> it = al.iterator();while (it.hasNext()){T t = it.next();if (!newAl.contains(t))newAl.add(t);}return newAl;}}

/*10、使用LinkedList 模拟出一个堆栈或者队列数据结构堆栈:先进后出 First in last out;如通一个杯子,一个球一个球的放进去,取的时候,最后的先取出来队列:先进先出  First in First out;如通一根水管,一个球一个球放进去,先进去的,就先出去*/import java.util.*;class Duilei<T>{private LinkedList<T> ll = new LinkedList<T>();public void add(T t){ll.addFirst(t);}public T remove(){return ll.removeLast();}public boolean isEmpty(){return ll.isEmpty();}}class DiuZhan<T>{private LinkedList<T> ll = new LinkedList<T>();public void add(T t){ll.addLast(t);}public T remove(){return ll.removeLast();}public boolean isEmpty(){return ll.isEmpty();}}class Test{public static void main(String[] args){Duilei<String> dl = new Duilei<String>();dl.add("java01");dl.add("java02");dl.add("java03");dl.add("java04");while (!dl.isEmpty()){System.out.println(dl.remove());}}}

/*11、"sdfgzxcvasdfxcvdf"获取该字符串中的字母出现的次数打印结果:a(1)c(2)....思路结果是字母与出现次数且按照abcd...自然顺序的形式1、将字符串变数组,遍历获取每一个元素2、定义Map集合,将遍历到的元素依次存入,字母作为键,数字作为值3、存入之前先判断Map对象是否有该键,有就取出其对应的值加1,再存入,   若没有则将值定义为1和键存入4、遍历所得map集合将键值一次存入StringBuilder,然后以String形式返回 */import java.util.*;class Test{public static void main(String[] args){String str = "sdfgzxcvasdfxcvdf";System.out.println(charCount(str));}public static String charCount(String str){char[] chs = str.toCharArray();Map<Character,Integer> map = new TreeMap<Character,Integer>();int count ;for(char ch : chs){count = 1;if(map.get(ch)!=null){count = map.get(ch)+1;map.put(ch,count);}elsemap.put(ch,count);}Set<Character> keySet = map.keySet();StringBuilder sbuf = new StringBuilder();for(char ch : keySet){sbuf.append(ch+"("+map.get(ch)+")");}return sbuf.toString();}}

/*12、往HashSet集合中存入自定义对象,姓名和年龄相同为同一个人,即重复元素明确HashSet集合底层数据结构,复写hashCode和equals方法*/import java.util.*;class Person{private int age;private String name;Person(String name,int age){this.name = name;this.age = age;}public String getName(){return name;}public int getAge(){return age;}public int hashCode(){return name.hashCode()+age*39;}public boolean equals(Object obj){if (!(obj instanceof Person))throw new ClassCastException("no Person");Person s = (Person)obj;return  this.name.equals(s.name) && this.age == s.age;}public String toString(){return this.name+":"+this.age;}}class Test{public static void main(String[] args) {HashSet<Person> al = new HashSet<Person>();al.add(new Person("lisi01",30));al.add(new Person("lisi02",32));al.add(new Person("lisi03",33));al.add(new Person("lisi04",35));al.add(new Person("lisi02",32));al.add(new Person("lisi04",35));for (Iterator<Person> it =al.iterator();it.hasNext(); ){System.out.println(it.next());}}}

/*13、往TreeSet集合中存储自定义对象学生并按照学生的年龄进行排序    明确TreeSet集合底层数据结构,两种情形,对象本身具备比较行,TreeSet加入了比较器*/import java.util.*;class Student implements Comparable<Student>{private String name;private int age;Student(String name , int age){this.name = name;this.age = age;}public String toString(){return name+":"+age;}public int hashCode(){return name.hashCode()+age*39;}public boolean equals(Object obj){if(obj instanceof Student)throw new ClassCastException("no student");Student s = (Student)obj;return this.name.equals(s.name) && this.age==s.age;}public int compareTo(Student s){int num = new Integer(this.age).compareTo(s.age);if(num==0)return this.name.compareTo(s.name);return num;}public int getAge(){return age;}public String getName(){return name;}}class Test{public static void main(String[] args) {TreeSet<Student> ts = new TreeSet<Student>(new Com());ts.add(new Student("alisi02",22));ts.add(new Student("clisi007",20));ts.add(new Student("dlisi09",19));ts.add(new Student("blisi01",19));Iterator<Student> it = ts.iterator();while (it.hasNext()){Student stu = it.next();sop(stu.toString());}}public static void sop(Object obj){System.out.println(obj);}}class Com implements Comparator<Student>{public int compare(Student s1,Student s2){int num = s1.getName().compareTo(s2.getName());if(num==0)return new Integer(s1.getAge()).compareTo(s2.getAge());return num;}}

/*14、一个学校有多个教室,每一个教室都有名称    创建两个map,学号与姓名一个map,班级与上一个map 为另一个map     另外也可以将姓名和学号封装成对象,用Collection来存,在用Map存两者关系*/import java.util.*;class Test{public static void main(String[] args){HashMap<String,ArrayList<Student>> czbk = new HashMap<String,ArrayList<Student>>();ArrayList<Student> yure =new ArrayList<Student>();ArrayList<Student> jiuye =new ArrayList<Student>();czbk.put("yure",yure);czbk.put("jiuye",jiuye);yure.add(new Student("01","zhangsan"));yure.add(new Student("04","wangwu"));jiuye.add(new Student("01","zhouqi"));jiuye.add(new Student("02","zhaoliu"));Set<String> keySet = czbk.keySet();for (String s:keySet){System.out.println(s);ArrayList<Student> al = czbk.get(s);for (Student stu:al ){System.out.println(stu);}}}public static void firstMethod(){HashMap<String,HashMap<String,String>> czbk = new HashMap<String,HashMap<String,String>>();HashMap<String,String> yure = new HashMap<String,String>();HashMap<String,String> jiuye = new HashMap<String,String>();yure.put("01","zhangsan");yure.put("02","wangwu");jiuye.put("01","zhouqi");jiuye.put("02","zhaoliu");czbk.put("yure",yure);czbk.put("jiuye",jiuye);Set<String> keySet = czbk.keySet();Iterator<String> it = keySet.iterator();while (it.hasNext()){String s = it.next();HashMap<String,String> hm = czbk.get(s);System.out.println(s);Set<String> keySet1 = hm.keySet();for (String str :keySet1){System.out.println(str+","+hm.get(str));}}}}class Student implements Comparable<Student>{private String name;private String id;Student(String id ,String name){this.name = name;this.id = id;}public String toString(){return id+":"+name;}public int hashCode(){return name.hashCode()+id.hashCode();}public boolean equals(Object obj){if(obj instanceof Student)throw new ClassCastException("no student");Student s = (Student)obj;return this.name.equals(s.name) && this.id.equals(s.id);}public int compareTo(Student s){int num = this.id.compareTo(s.id);if(num==0)return this.name.compareTo(s.name);return num;}public String getId(){return id;}public String getName(){return name;}}

//15、复制文件通过BufferedReader/Writer复完成文件的复制import java.io.*;class Test{public static void main(String[] args) {BufferedReader bufr = null;BufferedWriter bufw = null;try{bufr = new BufferedReader(new FileReader("Demo1.java"));bufw = new BufferedWriter(new FileWriter("copy_Demo1.java"));int num = 0;String line=null ;while ((line=bufr.readLine())!=null){bufw.write(line);bufw.newLine();bufw.flush();}}catch (IOException e1){throw new RuntimeException("failed to operate");}finally{if (bufr!=null){try{bufr.close();}catch (IOException e2){throw new RuntimeException("failed to close BufferedReader");}}if (bufw!=null){try{bufw.close();}catch (IOException e3){throw new RuntimeException("failed to close BufferedWriter");}}}}}

/*16、自定义BufferedReader类,readLine方法,另Reader有两个抽象方法需要复写windos下换行为\r\n两个字符,另BufferedReader类只输出行字符不带任何行终止符*/import java.io.*;class Test {public static void main(String[] args)throws IOException {MyBufferedReader mbr = new MyBufferedReader(new FileReader("copy_Demo1.java"));BufferedWriter bufw = new BufferedWriter(new FileWriter("copy3_Demo1.java"));String line = null;while ((line=mbr.readLine())!=null){bufw.write(line);bufw.newLine();bufw.flush();}bufw.close();mbr.close();}}class MyBufferedReader extends Reader{private Reader r ;MyBufferedReader(Reader r){this.r = r;}public String readLine()throws IOException{StringBuilder sb = new StringBuilder();int ch = 0;while((ch=r.read())!=-1){if (ch=='\r')continue;else if(ch=='\n')return sb.toString();elsesb.append((char)ch);}if(sb.length()!=0)  //注意此处还需在判断下以防止数据丢失return sb.toString();return null;}public void close() throws IOException{r.close();}public int read(char[] cbuf,int off,int len)throws IOException{return r.read(cbuf,off,len);}}

/*17、LineNumberReader类, 带行号的打印,加练习模拟一个带行号的缓冲区对象LineNumberReader为BufferedReader类子类,readLine方法都是父类方法,只是内部定义了一个计数器,没读一次,计数器自增1,这样就可以带行输出*/import java.io.*;class Test {public static void main(String[] args)throws IOException {//lineDemo();//用自己封装的对象,输出带行号的复制文件MyLineNumberReader mlnr = new MyLineNumberReader(new FileReader("copy_Demo1.java"));BufferedWriter bufw = new BufferedWriter(new FileWriter("copy2_Demo1.java"));String line = null;while ((line=mlnr.readLine())!=null){bufw.write(mlnr.getLineNumber()+":"+line);bufw.newLine();bufw.flush();}mlnr.close();bufw.close();}public static void lineDemo()throws IOException{LineNumberReader lnr = new LineNumberReader(new FileReader("copy_Demo1.java"));BufferedWriter bufw = new BufferedWriter(new FileWriter("copy1_Demo1.java"));String line = null;while ((line=lnr.readLine())!=null){bufw.write(lnr.getLineNumber()+line);bufw.newLine();bufw.flush();}lnr.close();bufw.close();}}class MyLineNumberReader extends BufferedReader{private int lineNumber=0;MyLineNumberReader(Reader r){super(r);}public void setLineNumber(int lineNumber){this.lineNumber = lineNumber;}public String readLine()throws IOException{lineNumber++;return super.readLine();}public int getLineNumber(){return lineNumber;}}

/*18、复制图片、音乐等数据,这时就要用到字节流,FileInputStream BufferedInputStream ,另自定义MyBufferInputStream类BufferedInputStream类内部封装了数组用来缓存输入流读取的数据,通过指针和计数器来完成数据的正确输出另外需要注意的是,读取一个字节会自动提升为int型之后将高位补零,这样就不会与定义的返回-1为数据终止冲突*/import java.io.*;class Test{public static void main(String[] args)throws IOException {long start = System.currentTimeMillis();//method_1();method_2();long end = System.currentTimeMillis();System.out.println("time:"+(end-start));}public static void method_2() throws IOException{MyBufferedInputStream mbs = new MyBufferedInputStream(new FileInputStream("1.mp3"));BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy_2.mp3"));int b = 0;while ((b=mbs.read())!=-1){bos.write(b);}bos.close();mbs.close();}public static void method_1()throws IOException{BufferedInputStream bis = new BufferedInputStream(new FileInputStream("1.mp3"));BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy_1.mp3"));byte[] buf = new byte[1024];int len=0;while ((len=bis.read(buf))!=-1){bos.write(buf,0,len);}bos.close();bis.close();}}class MyBufferedInputStream {private InputStream in;byte[] buf = new byte[1024];int pos=0,count=0;MyBufferedInputStream(InputStream in){this.in =in;}public int read()throws IOException {if(count>0){byte by = buf[pos];pos++;count--;return by&255;//pay attention}if(count==0){count = in.read(buf);if(count<0)return -1;pos=0;byte by = buf[pos];count--;pos++;return by&255;  //pay attention}return -1;}public void close()throws IOException{in.close();}}

/*19、异常日志信息*/import java.io.*;import java.text.*;import java.util.*;class Test{public static void main(String[] args){try{int[] arr = new int[2];System.out.println(arr[3]);}catch (Exception e){try{Date d = new Date();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String s = sdf.format(d);PrintStream ps = new PrintStream("exception.log");ps.println(s);System.setOut(ps);}catch (IOException e1){throw new RuntimeException("failed to create exception log");}e.printStackTrace(System.out);}}}

/*20、Properties 演示,自定义其load方法    内部封装BufferedReader类,读取一行,然后用字符串split方法切割获取两个字符串,在将两个字符串存入*/import java.io.*;import java.util.*;class Test{public static void main(String[] args)throws IOException{//setAndGet();//myLoad();loadAndStore();}public static void loadAndStore()throws IOException{BufferedReader bufr = new BufferedReader(new FileReader("info.txt"));BufferedWriter bufw = new BufferedWriter(new FileWriter("info.txt",true));Properties prop = new Properties();prop.load(bufr);prop.setProperty("lisi","15");prop.store(bufw,"");bufr.close();bufw.close();}public static void myLoad()throws IOException{BufferedReader bufr = new BufferedReader(new FileReader("info.txt"));String line = null;Properties prop = new Properties();while ((line=bufr.readLine())!=null){//如果写入的非=格式,和中间有空行都会导致错误String[] arr = line.split("=");prop.setProperty(arr[0],arr[1]);}bufr.close();prop.list(System.out);}public static void setAndGet(){Properties prop = new Properties();prop.setProperty("java01","21");prop.setProperty("java02","22");prop.setProperty("java03","23");prop.setProperty("java04","24");Set<String> set = prop.stringPropertyNames(); for (String s : set ){System.out.println(s+"="+prop.getProperty(s));}}}

/*21、创建配置文件用于记录应用程序运行次数,如果使用次数已到,那么给出注册提示。*/import java.io.*;import java.util.*;class Test{public static void main(String[] args)throws IOException{method_1();}public static void method_1()throws IOException{File file = new File("count.ini");if(!file.exists())file.createNewFile();Properties prop = new Properties();prop.load(new FileReader(file));int count =0;String value = prop.getProperty("time");if (value!=null){count = Integer.parseInt(value);if (count>5){System.out.println("please pay off");return;}}count++;prop.setProperty("time",count+"");prop.store(new FileWriter(file),"");}}

/*22、切割文件并通过序列流还原    定义数组缓冲用来存储读取的数据,然后再输出    用SequenceInputStream来连接各part读取流,各part读取流用ArrayList实例存储    并且用该存储器的迭代器去复写Enumration实例*/import java.io.*;import java.util.*;class Test{public static void main(String[] args)throws Exception{File file = new File("copy_2.mp3");//splitFile(file);merge();}public static void splitFile(File file)throws Exception{FileInputStream fis = new FileInputStream(file);byte[] buf = new byte[1024*1024];int len = 0;int count=1;while((len=fis.read(buf))!=-1){FileOutputStream fos = new FileOutputStream((count++)+".part");fos.write(buf,0,len);fos.close();}fis.close();}public static void merge()throws IOException{ArrayList<InputStream> al = new ArrayList<InputStream>();for (int x=1;x<7 ; x++){FileInputStream fis = new FileInputStream(x+".part");al.add(fis);}Iterator<InputStream> it = al.iterator();//通过迭代器复写Enumeration方法创建匿名内部类实例对象,以提高效率SequenceInputStream sis = new SequenceInputStream(new Enumeration<InputStream>(){public boolean hasMoreElements(){return it.hasNext();}public InputStream nextElement(){return it.next();}});FileOutputStream fos = new FileOutputStream("copy_3.mp3");byte[] buf = new byte[1024];int len =0;while ((len=sis.read(buf))!=-1){fos.write(buf,0,len);fos.flush();}fos.close();sis.close();}}
<pre><pre style="text-align: center; ">------------ <span style="color: rgb(255, 0, 0); ">android培训</span>、<span style="color: rgb(255, 0, 0); ">java培训</span>、java博客、java学习型技术博客、期待与您交流! -------------
详情请查看:http://edu.csdn.net/heima/

                                             
0 0
原创粉丝点击