简体   繁体   English

无法使推方法起作用

[英]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. 我需要一些快速的帮助来完成任务,总之,我完成了一项任务,要求我制作一个程序,该程序允许用户将pop(),push()和top()数组化。

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. 我做到了,但是我的老师说代码布局错误,因为我在堆栈类中有System.out.println语句,这些语句应该在主菜单应用程序中,并且堆栈类应仅调用它从数组继承的方法类。

Fair enough I thought and I amended the code but I cannot get the push() method to work correctly now :/ 我认为还算公平,我修改了代码,但现在无法使push()方法正常工作:/

I know that I need to use the Genio.getInteger method in the menu app push()method. 我知道我需要在菜单应用程序push()方法中使用Genio.getInteger方法。

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?: 编辑:Genio类是否相关?:

    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.push? (s.pop isn't either?) (s.pop也不是吗?)

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). 如果只希望它是提示,请使用大括号(无论如何使用大括号,有一天可以将您从可怕的bug中解救出来)。 Something like this. 这样的事情。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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