尝试创建一个堆栈,让用户输入堆栈中的数字数量,先入先出,使用 2 种方法 push 和 pop , push 将元素放在堆栈上,pop 删除顶部的元素。尝试调用 push 方法和堆栈有更多空间然后引发异常。即使抛出异常,尝试调用弹出和堆栈也是空的。这个问题有点难以理解,但那是因为我的英语
这是我的主要课程(应用程序)
package com.example.undantag.main;
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
Stack2 st = new Stack2();
System.out.println("Stack "+st);
System.out.println("Please enter how many numbers you would like to enter");
Scanner scan = new Scanner(System.in);
int totalnumber = scan.nextInt();
System.out.println("Please enter the number you would like to begin");
int beginnumber = scan.nextInt();
showPush(st, beginnumber, totalnumber);
System.out.println("Please enter how many numbers you would like to delete");
int deletenumber = scan.nextInt();
if(deletenumber > totalnumber){
throw new IllegalArgumentException("Invalid number");
}
else{
for(int i=0; i<=deletenumber; i++)
{
showpop(st);
}
}
}
}
这是第二课
package com.example.undantag.main;
public class Stack2 {
public static int i;
static int TotalNumber(int totalnumber){
return totalnumber;
}
static void showPush(Stack st, int a, int totalnumber){
for(int i = 0; i <=totalnumber; i++)
{
st.push(new Integer (a++));
System.out.println("Push("+a + ") ");
}
}
static void showpop(Stack st){
System.out.print("Pop: ");
Integer a = (Integer) st.pop();
System.out.println(a);
System.out.println("Stack: "+st);
}
}