



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
This Java program demonstrates the implementation of a stack data structure using an array. The user can perform actions such as displaying the stack, pushing new Student objects onto the stack, and exiting the program. The Student object contains name and age attributes.
Typology: Summaries
1 / 6
This page cannot be seen from the preview
Don't miss anything!




public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("vui long nhap kich co"); int size = sc.nextInt(); Mystack mt = new Mystack(size); while(true){ System.out.println("Hi! vui long chon tinh nang:"); System.out.println("Enter 1: Hien thi:"); System.out.println("Enter 2: nhap va push sinh vien"); System.out.println("Enter 3: thoat"); int t = sc.nextInt(); switch(t) { case 1: System.out.println("In stack:"); mt.print(); break; case 2: for(int i = 0; i<mt.maxSize;i ++){ // Student st = new Student(); // System.out.println("Nhap ten sinh vien: "); // sc = new Scanner(System.in); // String name = sc.nextLine(); // st.setName(name); // System.out.println("Nhap tuoi sinh vien: "); // int age = sc.nextInt(); // st.setAge(age); // mt.push(new Node(st));
System.out.println("Nhap ten sinh vien: "); sc = new Scanner(System.in); String name = sc.nextLine(); System.out.println("Nhap tuoi sinh vien: "); int age = sc.nextInt(); Student st = new Student(name, age); mt.push(new Node(st)); } break; case 3: System.exit(0); break; default: System.out.println("Ban da nhap sai! vui long nhap lai"); break; } } } } public class Mystack { // 1 ngăn xếp thực thi bằng mảng gômg: //maxSize, con trỏ top, mảng các node int maxSize; int top; Node[] stack; // public Mystack(int maxSize, int top, Node[] stack) {
// lấy ra pop public Node pop(){ if (isEmpty()){ System.out.println("Stack is empty"); return null; } else { Node n = stack[top]; top-=1; return n; } } public Node peek(){ if (isEmpty()){ System.out.println("Stack is empty"); return null; } else { Node n = stack[top]; return n; } } // in ra // duyệt từ 0 - top public void print(){ for (int i = 0; i <= top; i++) { stack[i].printData();
public class Node { Student student; public Node(Student student) { this.student = student; } public void printData() { System.out.println("Data: name: " + student.getName() + " - age: " + student.getAge()); } } public class Student { private String name; private int age; public Student(){ } public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; }