2016/5/30学习记录
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2016/5/30学习记录相关的知识,希望对你有一定的参考价值。
1.模拟栈
package Exercise; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Scanner; public class Test { public static void main(String[] args) { ArrayList<Object> list = new ArrayList<>(); Test a = new Test(list); System.out.print("is the steak empty? "); System.out.println(a.isEmpty()); a.push(2); a.push(3); a.push(5); System.out.print("the size of the steak is "); System.out.println(a.getSize()); System.out.print("is the steak empty? "); System.out.println(a.isEmpty()); System.out.print("get the peek number "); System.out.println(a.peek()); System.out.print("pop the peek and return it "); System.out.println(a.pop()); System.out.print("now the peak is "); System.out.println(a.peek()); System.out.print("the size of the steak "); System.out.println(a.getSize()); System.out.print("list the numbers "); System.out.println(a.toString()); } Test(ArrayList<Object> list){ this.list = list; } //类Test模拟栈 private ArrayList<Object> list; public boolean isEmpty(){ return list.isEmpty(); } public int getSize(){ return list.size(); } public Object peek(){ return list.get(list.size()-1); } public Object pop(){ Object o = list.get(list.size()-1); list.remove(list.size()-1); return o; } public void push(Object i){ list.add(i); } public String toString(){ return "the steak is "+ list.toString(); } }
输出如下
is the steak empty? true the size of the steak is 3 is the steak empty? false get the peek number 5 pop the peek and return it 5 now the peak is 3 the size of the steak 2 list the numbers the steak is [2, 3]
2.对象作为成员变量的例子,时钟。
package Exercise; public class Times { private int limit; private int num = 0; Times(int limit) { this.limit = limit; } int getLimit() { return limit; } int getNum() { return num; } void tick() { num++; if (num == limit) num = 0; } void show() { while (true) { tick(); System.out.println(num); } } public String toString() { if (num < 10) return "0" + num; else return "" + num; } public static void main(String[] args) { // TODO Auto-generated method stub Times t = new Times(24); t.show(); } }
此函数定义了数字如何跳动。接下来在另一个类中引用两个Times的对象作为变量
1 package Exercise; 2 3 public class ShowTime { 4 private Times hours = new Times(24); 5 private Times minutes = new Times(60); 6 7 void show() { 8 while (true) { 9 minutes.tick(); 10 if (minutes.getNum() == 0) 11 hours.tick(); 12 // System.out.printf("%02d:%02d\n",hours.getNum() 13 // ,minutes.getNum()); 14 System.out.println(hours + ":" + minutes); 15 } 16 17 } 18 19 public static void main(String[] args) { 20 // TODO Auto-generated method stub 21 ShowTime st = new ShowTime(); 22 st.show(); 23 // String s = "123"; 24 // Integer i = 12; 25 // s=i+""; 26 // System.out.println(s); 27 } 28 29 }
其中第14行,直接用hours和minutes调用了Times中的toString函数,因为hours+":"编译器判断时会默认hours为字符串,所以直接调用之。
以上是关于2016/5/30学习记录的主要内容,如果未能解决你的问题,请参考以下文章