java中类与构造函数举例说明

相关主题
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
package first;
//This class defines an integer stack that can hold 10 values. class Stack { int stck[] = new int[10]; int tos; //Initialize top-of-stack Stack() { tos = -1; } //Push an item onto the stack void push(int item) { if(tos==9) System.out.println("Stack is full."); else stck[++tos] = item;//s(0)=0;s(1)=1;s(9)=9;s(0)=10;S(1)=11;S(9)=19 } //Pop an item from the stack int pop() { if(tos < 0) { System.out.println("Stack underflow."); return 0; } else return stck[tos--]; } } class TestStack { public static void main(String args[]) { Stack mystack1 = new Stack(); Stack mystack2 = new Stack(); // push some numbers onto the stack for(int i=0; i<10; i++) mystack1.push(i); for(int i=10; i<20; i++) mystack2.push(i); // pop those numbers off the stack System.out.println("Stack in mystack1:"); for(int i=0; i<10; i++) System.out.println(mystack1.pop()); System.out.println("Stack in mystack2:"); for(int i=0; i<10; i++) System.out.println(mystack2.pop()); } }
输出结果 Stack in mystack1: 9 8 7 6 5 4 3 2 1 0 Stack in mystack2: 19 18 17 16 15 14 13 12 11 10
Baidu Nhomakorabea
相关文档
最新文档