有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java有人能帮我理解这段代码是如何工作的吗?这是课堂上的一个例子,我想更有效地学习

编写代码,将10个字符串压入堆栈(版本2),边打印边删除

import java.math.*;

public class StackTest {
 public static void main (String[] args){


 Stack2 stk = new Stack2("Stack");
       for(int i = 0; i < 10; i++){
 stk.push("Item: " + (i + 1));

 System.out.println("Pushing: Item: " + (i + 1));
 }
 System.out.println("\n" + stk.print());

      for(int i = 0; i < 10; i++){
 System.out.println("Popping: " + stk.pop());
 }
 System.out.println("\n" + stk.print());
 }
}

共 (1) 个答案

  1. # 1 楼答案

    您拥有的是一个TestClass,用于测试堆栈的自定义实现
    关于堆栈,您需要了解的一些关键问题是:
    后进先出(后进先出)数据结构
    这在浏览器中使用。当你点击后退按钮时
    带您进入您访问的最后一页

    // A class in the default package
    
    // Import java.math
    import java.math.*;
    
    // Class Name: StackTest
    public class StackTest {
    
    // Your main method: The entry point of your program
     public static void main (String[] args){
    
     // Creates an object Stack2 and references it to stk
     Stack2 stk = new Stack2("Stack");
     // Runs a for loop 10 times and pushes an element into the stack and prints the result into the console
           for(int i = 0; i < 10; i++){
             stk.push("Item: " + (i + 1));
    
             System.out.println("Pushing: Item: " + (i + 1));
     }
     // Prints your stack
     System.out.println("\n" + stk.print());
    
     // Runs a loop 10 times and pops each item of the stack out
     for(int i = 0; i < 10; i++){
        System.out.println("Popping: " + stk.pop());
     }
     // Prints your stack
     System.out.println("\n" + stk.print());
     }
    }
    

    您的控制台将显示如下内容:

    Pushing Item: Item 1 
    Pushing Item: Item 2 
    Pushing Item: Item 3
    Pushing Item: Item 4
    Pushing Item: Item 5
    Pushing Item: Item 6
    Pushing Item: Item 7
    Pushing Item: Item 8
    Pushing Item: Item 9
    Pushing Item: Item 10
    
    Stack [Item 10, Item 9, Item 8, Item 7, Item 6, Item 5, Item 4, Item 3, Item 2, Item 1] < depending on what your Stack2 print() method does.
    Popping: Item 10
    Popping: Item 9 
    Popping: Item 8
    Popping: Item 7 
    Popping: Item 6 
    Popping: Item 5 
    Popping: Item 4 
    Popping: Item 3 
    Popping: Item 2 
    Popping: Item 1 
    Stack []