简体   繁体   中英

Can't get push method to work

I am need some quick help with finishing an assignment, In short I completed an assignment that required me to make a program that allowed the user to pop(), push() and top() an array.

I did it but my tutor said that the code layout wrong as I had System.out.println statements in the stack class and these should be in the main menu app, and the stack class should only called the methods that it inherits from the array class.

Fair enough I thought and I amended the code but I cannot get the push() method to work correctly now :/

I know that I need to use the Genio.getInteger method in the menu app push()method.

Can anyone help?

Stack Class:

    public class Stack extends Array
    {
    private int x;


public Stack()
{
    super();// initialise instance variables
    x = 0;
}

public Stack(int newsize)
{
    super(newsize);
    System.out.println("Stack Created!");
}

/**
    * @push user is asked to enter value at keyboard which is then added to the top of the stack
    *
    */
public boolean push(int item)
{
    return add(item);
}


/**
    * @pop removes the current value staored at the top of the stack
    *
    */
public int pop()
{
        deleteLast();
        return getItemback();
}         

/**
    * @top displays the current value stored at the top of the stack
    *
    */
public int top()
{
    displayLast();
    return getItemback();
}         

}

Menu app:

    public static void main()
    {
        int option;
        int item;

        Stack s = new Stack();
        String []menuitems = {"1 - Display Stack","2 - Pop Stack", "3 - Push Onto Stack","4 - Top Of Stack","5 - Quit Program"};            
        Menu m = new Menu(menuitems,5);

        s.add(12);s.add(2);s.add(1);s.add(13);s.add(24);

        do
        {
            clrscr();
            option = m.showMenu();
            if ( option == 1 )                
            {                    
                s.display();
                pressKey();
            }
            if ( option == 2 )                
            {      
                if (!s.isEmpty())
                System.out.println ("Number Popped: ");
                else
                System.out.println ("The Stack Is Empty! ");
                pressKey();
            }


             // THIS IS THE PART I CANNOT GET TO WORK!! NOT SURE WHERE/HOW TO CALL PUSH    
             // METHOD?
            if ( option == 3 )                
            {    
                item = Genio.getInteger(); 
                if (!s.isFull())
                System.out.println("Please Enter Number To be Pushed(" + item + ")");
                else
                System.out.println("Stack Overflow! "); 
                pressKey();
            }
            if ( option == 4 )                
            {    
                if (!s.isEmpty())
                s.top();
                else
                System.out.println ("The Stack Is Empty! ");
                pressKey();
            }
        }
        while ( option != 5 );
        System.out.println("\nDone! \n(You Can Now Exit The Program)\n");
    }
/**
* @clrscr removes all text from the screen
*
*/
    public static void clrscr()
    {           
        for ( int i=1;i<=50;i++)
            System.out.println();
    }
/**
* @pressKey requires the user to press return to continue
*
*/
    public static void pressKey()
    {
        String s;
        System.out.print("\nPress return to continue : ");
        s = Genio.getString();
    }            
}

EDIT: Genio class if relevant?:

    public class Genio

{

/**
 * Constructor for objects of class genio, but nothing needing constructed!
 */
public Genio()
{
}


/** 
 * getStr()  is a private method which safely returns a string for use
 * by the public methods getString() and getCharacter() in the class.
 * 
 * @return String for further processing withing the class
 */

private static String getStr() 
{
    String inputLine = "";
    BufferedReader reader = 
        new BufferedReader(new InputStreamReader(System.in));
    try 
    {
        inputLine = reader.readLine();
    }

    catch(Exception exc) 
    {
        System.out.println ("There was an error during reading: "
                            + exc.getMessage());
    }
    return inputLine;
}

/** 
 * getInteger() returns an integer value. Exception handling is used to trap
 * invalid data - including floating point numbers, non-numeric characters
 * and no data. In the event of an exception, the user is prompted to enter
 * the correct data in the correct format.
 * 
 * @return validated int value 
 */
public static int getInteger()
{
    int temp=0;
    boolean OK = false;

    BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
    do 
    {
        try
        {
            temp = Integer.parseInt(keyboard.readLine());
            OK = true;
        }

        catch (Exception eRef)
        {
            if (eRef instanceof NumberFormatException) 
            {
                System.out.print("Integer value needed: ");
            }
            else
            {
                System.out.println("Please report this error: "+eRef.toString());
            }
        }

    } while(OK == false);
    return(temp);
 }

/** 
 * getFloat() returns a floating point value. Exception handling is used to trap
 * invalid data - including non-numeric characters and no data.
 * In the event of an exception (normally no data or alpha), the user is prompted to enter
 * data in the correct format
 * 
 * @return validated float value
 */        
public static float getFloat()
{
    float temp=0;
    boolean OK = false;

    BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
    do 
    {
        try
        {
            temp = Float.parseFloat(keyboard.readLine());
            OK = true;
        }


        catch (Exception eRef)
        {
            if (eRef instanceof NumberFormatException) 
            {
                System.out.print("Number needed: ");
            } 
            else
            {
                System.out.println("Please report this error: "+eRef.toString());
            }
        }

    } while(OK == false);

    return(temp);
 }

/** 
 * getDouble() returns a double precision floating point value. 
 * Exception handling is used to trap invalid data - including non-numeric
 * characters and no data.
 * In the event of an exception, the user is prompted to enter
 * data in the correct format
 * 
 * @return validated double precision value
 */        
public static double getDouble()
{
    double temp=0;
    boolean OK = false;
    BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
    do 
    {
        try
        {
            temp = Double.parseDouble(keyboard.readLine());
            OK = true;
        }

        catch (Exception eRef)
        {
            if (eRef instanceof NumberFormatException) 
            {
                System.out.print("Number needed: ");
            }
            else
            {
                System.out.println("Please report this error: "+eRef.toString());
            }
        }

    } while(OK == false);

    return(temp);
 }

/** 
 * getCharacter() returns a character from the keyboard. It does this by 
 * reading a string then taking the first character read. Subsequent characters
 * are discarded without raising an exception.
 * The method checks to ensure a character has been entered, and prompts 
 * if it has not.
 * 
 * @return validated character value
 */

 public static char getCharacter()
 {
     String tempStr="";
     char temp=' ';
     boolean OK = false;
     do 
     {
         try
         {
             tempStr = getStr();
             temp = tempStr.charAt(0);
             OK = true;
         }

         catch (Exception eRef)
         {
             if (eRef instanceof StringIndexOutOfBoundsException)
             {
                 // means nothing was entered so prompt ...
                 System.out.print("Enter a character: ");
             }            
             else 
             {
                 System.out.println("Please report this error: "+eRef.toString());
             }
         }

     } while(OK == false);

     return(temp);
 }

 /** 
  * getString() returns a String entered at the keyboard.
  * @return String value
  */

 public static String getString()
 {
    String temp="";
    try
    {
        temp = getStr();
    }
    catch (Exception eRef)
    {
        System.out.println("Please report this error: "+eRef.toString());
    }
    return(temp);
 }     

}

Not sure if I understood your question correctly, but s.push isn't being called? (s.pop isn't either?)

If you'll replace

if (!s.isFull())

with

if (!s.isFull() && s.push(item))

some work will get done?

If you want it only to be a prompt, use curly brackets (use them anyway, it'll save you from horrid bugs one day). Something like this.

if (!s.isFull()) {
    System.out.println("enter a number to add");
    Scanner sc = new Scanner(System.in);
    s.push(sc.nextInt());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM