Implement something like a stack in Java

Introduction

For some reason, I suddenly decided to create a stack-like program and explain it for those who started learning Java. However, due to time constraints, I couldn't explain it at all, so I will continue the explanation in this article as a supplement and Qiita mission.

The target audience is those who are new to Java. To be more specific, it is assumed that you have just learned the basics of data types and arrays through Hello World and learned how to write if statements, for statements, and while statements.

However, I think it is difficult to suddenly implement a stack (something like that), so in Chapter 1 we will create only the minimum framework, and in Chapter 2 and later we will introduce the functions required as a stack sequentially. We will implement it additionally. So, if you code in order from Chapter 1, you should be able to create a stack (something like that) without much confusion.

In addition, paiza.io is used as the development environment. As the title suggests, the language is Java.

Then, please stay with me for a while.

Chapter 0 About the stack

A stack is one of the data structures, and has a mechanism (LIFO: Last In First Out) to put out the last one. Imagine an elevator. If you do not consider the manners of working people, when you get on the elevator, start from the back. And when getting off the elevator, the person near the door, that is, the person who got on last, gets off.

In this article, we will create a stack-like program that pushes (stores) the input integers into an array that has the role of a stack, and pops (outputs) in order from the last input integer. Our ultimate goal is to meet the following requirements:

--Implement an array containing 5 integers as a stack. --Continue to enter strings and integers from the command prompt. --When "push integer" is entered, add the integer to the beginning of the array. If 5 have already been input, "push error" is output. --When "pop" is entered, the beginning of the array is output to the prompt, and the output integer is deleted from the array (or __ it looks as if it was deleted __). If there is no integer on the stack, "pop error" is output. --The program ends when "end" is entered.

Let's implement it little by little from Chapter 1.

Chapter 1 Input processing

In this chapter, let's start with the following relatively simple items.

--Continue to enter strings and integers from the command prompt.

Go to paiza.io and click "Try Code Creation (Free)". At first you may see samples from other languages such as PHP, but in that case Java should be your choice. You should see a simple program containing the println method as follows:

import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        // Your code here!
        
        System.out.println("XXXXXXXX");
    }
}

Now, in order to accept the input of character strings and integers, we will once receive it as a String type and convert it to an int type only when it is treated as an integer. Now, let's write a program that keeps the input character string stored in the String type for the time being. Also, add a process to display "Your input is [input string]" to check if the input is accepted correctly when executed. If you can write it, let's check the answer example 1-1 below.

Answer example 1-1 (Click to open)
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        while (true) {
            String input = sc.nextLine();
            System.out.println("Your input is [" + input + "]");
        }
    }
}

Let's try it out. In paiza.io, instead of typing from the command prompt, you need to select the input tab and write everything you want to type in the window that appears. So, if you click the input tab, write as follows.

push 1
push 2
push 3
end

Once you've done this, it's time to really do it. This will create a tab called Run-Time Error with the message "No line found". The reason for this is that the while statement repeat condition is true, so the process is to repeat forever. Even though I accepted the input to the end, I tried to receive more input, so I was told "No more." In fact, if you click on the output tab, you can see that it accepts up to "end" properly.

Now, let's consider the following items.

--The program ends when "end" is entered.

To determine if the entered string is equal to "end", you can use the equals method provided by the String class object. Please check the detailed usage by yourself, and write a process to break out of the while statement loop when "end" is input. If you can write it, let's check the answer example 1-2 below.

Answer example 1-2 (Click to open)
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        while (true) {
            String input = sc.nextLine();
            System.out.println("Your input is [" + input + "]");
            if (input.equals("end")) {
                break;
            }
        }
    }
}

Please try it. After accepting "end", I exited the while statement loop and the program ended normally, so there is no run-time error. The input process is now OK.

Chapter 2 push processing

This chapter implements the following items:

--When "push integer" is entered, add the integer to the beginning of the array. If 5 have already been input, "push error" is output.

Let's prepare an int type array that acts as a stack. The name of the array should be stack. Also, when declaring an array, don't write 5 directly to specify the number of elements. Instead, assign 5 to the int type variable N in advance, and use N when declaring the array. These are written before the while statement.

Next, let's think about how to handle the input of "push integer". Since the input character string is push, half-width space and integer, first make it possible to judge that it is a push command by looking only at the first 4 characters. To do this, use the substring method provided by the String class.

Also, since only integers are extracted from the input string, let's also use the split method provided in the String class to separate them into push and integers. However, since the integer is treated as a character string just by dividing it, use the parseInt method of the Integer class to convert the character string to an int type. Use the parseInt method as follows:

int number = Integer.parseInt(string);

Finally, let's consider the process of determining the number of the array stack to store when pushing an integer. You might think that the array has both front and back, but here we decide that the 0th element is the front and the N - 1 ($ = $ 4) th element is the back. .. That is, integers are stored from the N - 1st in the back to the 0th in the foreground. However, if an integer up to the 0th is already stored, it is necessary to output an error message, so please write it with caution. If you can write it, let's check the answer example 2 below.

Answer example 2 (click to open)
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        int N = 5;
        int[] stack = new int[N];
        int indexPointer = N;
        
        while (true) {
            String input = sc.nextLine();
            System.out.println("Your input is [" + input + "]");
            if (input.equals("end")) {
                break;
            } else if (input.substring(0, 4).equals("push")) {
                if (indexPointer >= 1 && indexPointer <= N) {
                    String[] commands = input.split(" ");
                    int number = Integer.parseInt(commands[1]);
                    indexPointer --;
                    stack[indexPointer] = number;
                    System.out.println(number + " pushed. index:" + indexPointer);
                } else {
                    System.out.println("push error.");
                }
            }
        }
    }
}

I will supplement a little. We have prepared a new int variable indexPointer to know which element of the array the integer is stored in. When performing push processing, it is determined whether an integer can be stored one before the element that was viewed immediately before, that is, whether indexPointer is __now__1 or more and N or less. If it is true, decrement indexPointer by 1 and store the integer in place of that value. For this process, the initial value when declaring indexPointer must be N.

Now, let's test a little to see if the process so far is correct. Select the Input tab and write as follows.

push 1
push 2
push 3
push 4
push 5
push 6
end

I will try it.

Your input is [push 1]
1 pushed. index:4
Your input is [push 2]
2 pushed. index:3
Your input is [push 3]
3 pushed. index:2
Your input is [push 4]
4 pushed. index:1
Your input is [push 5]
5 pushed. index:0
Your input is [push 6]
push error.
Your input is [end]

Integers are stored in order from the back of the array, and after storing 5 integers, an error message is displayed.

Chapter 3 pop processing

If you've made it this far, the stack is almost complete. In the previous chapter, we decided to use the variable indexPointer to grasp the number of the element in the array. This variable can be used for pop processing as it is. If you can write it, let's check the answer example 3 below.

Answer example 3 (Click to open)
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        int N = 5;
        int[] stack = new int[N];
        int indexPointer = N;
        
        while (true) {
            String input = sc.nextLine();
            System.out.println("Your input is [" + input + "]");
            if (input.equals("end")) {
                break;
            } else if (input.length() >= 4 && input.substring(0, 4).equals("push")) {
                if (indexPointer >= 1 && indexPointer <= N) {
                    String[] commands = input.split(" ");
                    int number = Integer.parseInt(commands[1]);
                    indexPointer --;
                    stack[indexPointer] = number;
                    System.out.println(number + " pushed. index:" + indexPointer);
                } else {
                    System.out.println("push error.");
                }
            } else if (input.equals("pop")) {
                if (indexPointer >= 0 && indexPointer < N) {
                    System.out.println(stack[indexPointer] + " poped. index:" + indexPointer);
                    indexPointer ++;
                } else {
                    System.out.println("pop error.");
                }
            }
        }
    }
}

What do you think. I think it was a little easier than the push process. Now, try typing the following in the Input tab:

pop
push 1
push 2
push 3
pop
pop
pop
push 4
push 5
push 6
push 7
push 8
push 9
end

I will try it.

Your input is [pop]
pop error.
Your input is [push 1]
1 pushed. index:4
Your input is [push 2]
2 pushed. index:3
Your input is [push 3]
3 pushed. index:2
Your input is [pop]
3 popped. index:2
Your input is [pop]
2 popped. index:3
Your input is [pop]
1 popped. index:4
Your input is [push 4]
4 pushed. index:4
Your input is [push 5]
5 pushed. index:3
Your input is [push 6]
6 pushed. index:2
Your input is [push 7]
7 pushed. index:1
Your input is [push 8]
8 pushed. index:0
Your input is [push 9]
push error.
Your input is [end]

Properly, the pushed 1, 2, and 3 are popped in reverse order. Also, if you try to pop even though no integers are stored, or if you try to push even though 5 integers are already stored, an error message will be output.

in conclusion

This time, I implemented a simple stack using the basic Java grammar. You can actually implement a queue with just a few changes to the above program, so if you have the time, please try it.

Thank you for reading.

Recommended Posts

Implement something like a stack in Java
3 Implement a simple interpreter in Java
[Java] Create something like a product search API
How to implement a like feature in Rails
Do something like a JS immediate function in Ruby
How to implement a like feature in Ajax in Rails
Implement two-step verification in Java
Implement Basic authentication in Java
Quickly implement a singleton with an enum in Java
Implement math combinations in Java
2 Implement simple parsing in Java
Implement Email Sending in Java
Implement functional quicksort in Java
Implement rm -rf in Java.
Implement XML signature in Java
Study Java: Use Timer to create something like a bomb timer
Implement Table Driven Test in Java 14
I created a PDF in Java.
Implement a like feature for posts
Implement a gRPC client in Ruby
Implement a contact form in Rails
Try to implement Yubaba in Java
Get stuck in a Java primer
1 Implement simple lexical analysis in Java
Implementation of like function in Java
Create a named Skip List like redis sorted set in Java
I wrote a Stalin sort that feels like a mess in Java
About returning a reference in a Java Getter
What is a class in Java language (3 /?)
When seeking multiple in a Java array
How to implement date calculation in Java
How to implement Kalman filter in Java
Implement API Gateway Lambda Authorizer in Java Lambda
Try to implement n-ary addition in Java
Make something like Java Enum with Typescript
[Creating] A memorandum about coding in Java
Various things like bit flags in Java
Java creates a table in a Word document
Java creates a pie chart in Excel
What is a class in Java language (1 /?)
What is a class in Java language (2 /?)
Create a TODO app in Java 7 Create Header
How to implement coding conventions in Java
Try making a calculator app in Java
Split a string with ". (Dot)" in Java
Creating a matrix class in Java Part 1
[Java] Implement a function that uses a class implemented in the Builder pattern
I made a primality test program in Java
GetInstance () from a @Singleton class in Groovy from Java
Read a string in a PDF file with Java
Create a CSR with extended information in Java
Implement user management functions in a wizard format
A story about the JDK in the Java 11 era
Partization in Java
How to display a web page in Java
[Android / Java] Operate a local database in Room
Measure the size of a folder in Java
Try to create a bulletin board in Java
Changes in Java 11
I tried to implement deep learning in Java
Rock-paper-scissors in Java