Java naming conventions
Please follow the Java naming conventions. Variables should start with a lowercase character, so it should read (also note the placing of []
makes it clearer that stack is an array of Character
)
static Character[] stack= new Character[25];
Why maximum stack size?
There is no given requirement for the limit of the size of the stack, so you should not use a fixed-size data structure like array, but rather opt for something like List
static List<Character> stack= new ArrayList<>();
Separation of concerns
There are two functionalities in you code directly interwoven. First, there is the 'Stack', then there is the usage of the Stack
. Move all the Stack
related functionality to its own class.
Don't use magic values
If there is an error in the state of the stack (for example, if you try to pop()
an empty stack, you could throw an Exception
, for example a NoSuchElementException()
. Or you can have the Stack ofuse Optional and return Optional.empty()
. Or even return null
if no empty values on the stack are allowed.
See for example the question here. Also check the answers.
Pair the parentheses, separate to own data type
You could implement a Delimiter enumDelimiter
enum
type, like such:
enum Delimiter
{
PARENTHESES( '(', ')' ),
BRACES ( '{', '}' ),
BRACKETS ( '[', ']' );
//easily expandable with for example: 〔 〕 – tortoise shell brackets
public final char openChar;
public final char closeChar;
public Delimiter(char openChar, char closeChar)
{
this.openChar = openChar;
this.closeChar = closeChar;
}
}
Then, when looping over the characters, you could use:
for (i = 0; i< str.length(); i++)
{
char c = str.charAt(i);
for (Delimiter delimiter : Delimiter.values())
{
if (c == delimiter.openChar)
{
stack.push(delimiter);
}
else if (c == delimiter.closeChar)
{
//pop the stack and check if the closechar matches the openchar of the popped element
}
}