/*
*1、 SUN提供的JDK内置的异常肯定是不够用的,在实际的开发中,有很多业务,
* 这些业务出现异常后,JDK中都是没有的,和业务挂钩的,异常类我们可以
* 自己定义吗??
* 可以
*2、java中怎样自定义异常?
* 1、写一个类继承Exception 或者 RuntimeException
* 2、提供两个构造方法,一个有参的,一个无参的
* 记住就行,模板SUN公司
* */
public class MyException extends Exception{
//编译时异常
public MyException() {
}
public MyException(String message) {
super(message);
}
}
public class MyExceptionTest {
public static void main(String[] args) {
MyException me = new MyException("啥都没写,就是异常");
me.printStackTrace();
String s = me.getMessage();
System.out.println(s);
}
}
/*
编写程序:使用一维数组,模拟栈数据结构
1、这个栈可以存储java中的任何引用数据类型
2、在栈中提供push方法模拟压栈(栈满了,要有提示信息)
3、在栈中提供pop方法模拟弹栈(栈空了,提示信息)
4、编写测试程序,new栈对象,调用push,pop方法模拟压栈,弹栈操作
5、假设栈的默认初始化容量是10(注意无参数构造方法的编写方式)
*/
public class StackTest {
public static void main(String[] args) {
MoNi01 test01 = new MoNi01();
String[] str = {
"s", "d", "t", "e","w","23","hi","sdg"};
int[] ints = {
1, 2, 3, 4, 5, 3};
Object[] objs = {
new Object(),new Object(),new Object()};
//String类型进行压栈
System.out.println("压栈开始==============");
for (int i = 0; i < str.length; i++) {
try {
test01.push(str[i]);
} catch (MyException e) {
e.printStackTrace();
}
}
//开始弹栈
System.out.println("\n弹栈=================");
for (int i = 0; i < 3 ; i++) {
try {
test01.pop();
} catch (MyException e) {
e.printStackTrace();
}
}
//int类型进行压栈
System.out.println("\n压栈=================");
for (int i = 0; i < ints.length; i++) {
try {
test01.push(ints[i]);
} catch (MyException e) {
e.printStackTrace();
}
}
//Object类型进行压栈
System.out.println("\nObject开始压栈==========");
for (int i = 0; i < objs.length; i++) {
try {
test01.push(objs[i]);
} catch (MyException e) {
e.printStackTrace();
}
}
//Object开始弹栈
System.out.println("\nObject开始弹栈==========");
for (int i = 0; i <2; i++) {
try {
test01.pop();
} catch (MyException e) {
e.printStackTrace();
}
}
//这里以数组中为0代表栈里没有方法,看下栈里都是什么
//推测压了四个栈,弹了3个,又压6个,应该有七个值不为null
System.out.println("\n查看元素==============");
test01.print();
}
}
class MoNi01 {
private int index = 0;
private Object[] array01 = new Object[10];
public MoNi01() {
}
public void push(Object a) throws MyException {
if (index == array01.length) {
//System.out.print(" " + "栈满," +"\"" + a + "\"" + "无法进行压栈");
// MyException e = new MyException("栈满,无法进行弹栈");
// throw e;
throw new MyException("栈满,无法进行弹栈");
} else {
array01[index++] = a;
System.out.print(" " + "压" + a + "成功!!!");
}
//这里a如果是Object的话,就是一个引用,会自动调用System的toString方法
}
public void pop() throws MyException {
if (index == 0) {
//System.out.print(" " + "栈为空,无法进行弹栈");
//return;
// MyException e = new MyException("栈为空,不需要进行弹栈");
// throw e;
throw new MyException("栈为空,不需要进行弹栈");
}
System.out.print(" " + "弹" + array01[--index] + "成功!!!!");
array01[index] = null;
}
public void print() {
for (int i = 0; i < array01.length; i++) {
System.out.print(" " + array01[i]);
}
System.out.println();
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}