HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Simple Stack Demo

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
simplestackdemo

Problem

I wrote this demo just for practice purpose, I would like to get some helps that could further improve my code quality. Any suggestion for improvement would be appreciated.

This code is a simple demonstration of stack implementation (by using array List).

  • User will be asked for the option of a function to demonstrate.



  • Once user made the choice (either use stack algorithm or java Stack), the corresponding function will ask user for size of the stack and elements that user wants to put into the stack.



  • Program will ask for the basic stack operation(push & pop).



  • Program will receive user inputs(integer) and push into the stack then print current stack.



  • After the print is completed, program will continue asking for new input, until user want to clear the stack and exit the function.



Note:

  • If the stack is overflowed, user will be notified and program will add additional space to the stack(perk for using Linked list).



-
If stack is empty, user will be notified and program will break out of the pop option until user deiced to push in some elements.

```
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;

public class basicStack {

public static void main(String[] args) {
System.out.println("Welcome to basic Stack test, please choose your testing subject: ");
try(Scanner user_option = new Scanner(System.in)){

mainMenu(user_option);

}//close the I/O before the program end
System.out.println("Program terminated...");

}

private static void mainMenu(Scanner input){
int option = 0;

do{

System.out.println("Option 1: Simple stack algorithm implementation");
System.out.println("Option 2: Simple java library stack usage");
System.out.println("Option 0: Exit program");

option = input.nextInt();
System.out.println("Current option is: " + option);

switch(option){

case 1:
System.out.println("running 1");
co

Solution

The try-with-resources in main

try(Scanner user_option = new Scanner(System.in)){
    mainMenu(user_option);
}//close the I/O before the program end


is a nice idea, as is passing the Scanner into the rest of the program but later in the program we create several new Scanner instances

private static void constructStackAlg(){
    int optionS1 = 1;
    Scanner sc_Stack1 = new Scanner(System.in);
    //...

private static int getS1Size(){
    int s1Size = 0;
    Scanner scGetS1Size = new Scanner(System.in);
    //...

private static void stackFunction(ArrayList s1, int s1Size){
    ArrayList stack1 = s1;
    int stack1Size = s1Size;
    System.out.println("Please choose the stack option:");
    Scanner scStackFunction = new Scanner(System.in);
    Scanner scElement = new Scanner(System.in);
    //...


none of which are contained in a try-with-resources. A consistent approach to such things is good - if it is worth using it on one of the Scanners it should be used on all. If it is not needed for the later Scanners, why use it on the first. (note: It should be used whenever as it prevents resource leakage). Also, we create two Scanners in stackFunction is there a reason for this? It seems to work with only one scanner used for both the function selection and the element entry.

As an alternative, instead of creating each of the new Scanners we could try passing the Scanner created in main through to each of the other routines.

The post is tagged as Beginner so I do not know if you are comfortable with creating classes, but if you are, a third alternative is to create a class for the Demo, passing in the Scanner, storing it as a member variable and using it in each routine.

Structure

In mainMenu the

while(option!=0)


will never be false because

case 0:
    return;


will return you from the method. As an alternative you can use

while(true);


which will give you an infinite loop terminated by the return on case 0

or

case 0:
    break;


which will do nothing on case 0 but when you get to the while will exit the loop.

Error Handling

The only place we validate the input (check for an exception) is in getS1Size but in every place where we use .nextInt() there is a possibility of an InputMismatchException. If, at the mainMenu, the user enters 'a', the program crashes with the above exception.

As with using try-with-resources on the scanners, if it is worth checking for the exception when getting the stack size, it is worth checking for it wherever we get input. Also, we do not really handle the error here. We ask the user to enter a valid integer but do not give them the opportunity to do so and continue on to the next stage with a stack size of 0.

Note:If we share a scanner between the routines we can end up with an infinite loop if you have an exception, this answer gives a way to deal with this. One of the other answers does mention creating a new Scanner each time we want to read input as a way of bypassing this problem but some of the point of the Scanner is that is provides access to a Stream. In this case the stream is Console.in and creating a new scanner each time is possible. Say it was a file, or a string or any stream where we cared about the position in the stream.

EDIT

We can encapsulate the demo in a class allowing us to refactor an amount of the common functionality

```
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;

public class BasicStack {

public static void main(String[] args) {

System.out.println("Welcome to basic Stack test, please choose your testing subject: ");

try(Scanner scanner = new Scanner(System.in)){
new StackExample().run(scanner);
}//close the I/O before the program end

System.out.println("Program terminated...");

}
}

public class StackExample {

private Scanner _scanner;

public void run(Scanner scanner){
_scanner = scanner;
mainMenu();
}

private void mainMenu(){

do{

writeLine("Option 1: Simple stack algorithm implementation");
writeLine("Option 2: Simple java library stack usage");
writeLine("Option 0: Exit program");

int option = readNumber();
writeLine("Current option is: " + option);

switch(option){

case 1:
writeLine("running 1");
constructStackAlg();
break;
case 2:
System.out.println("running 2");
//constructJavaStack();
break;
case 0:
return;
default:
writeLine("Invaild Option, Please choose a vaild option...");
break;
}

writeLine("-Main Menu-");

}while(true);
}

private void constructStackAlg(){
int optionS1 = 1;

do{

int size = 0;
while(size s1 = buildStack(size);
stackFunct

Code Snippets

try(Scanner user_option = new Scanner(System.in)){
    mainMenu(user_option);
}//close the I/O before the program end
private static void constructStackAlg(){
    int optionS1 = 1;
    Scanner sc_Stack1 = new Scanner(System.in);
    //...

private static int getS1Size(){
    int s1Size = 0;
    Scanner scGetS1Size = new Scanner(System.in);
    //...

private static void stackFunction(ArrayList<Integer> s1, int s1Size){
    ArrayList<Integer> stack1 = s1;
    int stack1Size = s1Size;
    System.out.println("Please choose the stack option:");
    Scanner scStackFunction = new Scanner(System.in);
    Scanner scElement = new Scanner(System.in);
    //...
while(option!=0)
case 0:
    return;
while(true);

Context

StackExchange Code Review Q#158437, answer score: 2

Revisions (0)

No revisions yet.