无法使用推送方法工作

时间:2013-12-21 22:34:47

标签: java arrays

我需要一些快速帮助完成作业,简而言之,我完成了一项任务,要求我制作一个程序,允许用户pop(),push()和top()一个数组。

我做了但是我的导师说代码布局错误,因为我在堆栈类中有System.out.println语句,这些应该在主菜单应用程序中,而堆栈类应该只调用它继承的方法来自数组类。

我认为很公平,我修改了代码,但我现在无法使push()方法正常工作:/

我知道我需要在菜单app push()方法中使用Genio.getInteger方法。

有人可以帮忙吗?

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();
}         

}

菜单应用:

    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();
    }            
}

编辑:如果相关的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);
 }     

}

1 个答案:

答案 0 :(得分:0)

不确定我是否正确理解了您的问题,但s.push没有被调用? (s.pop不是?)

如果你要替换

if (!s.isFull())

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

有些工作会完成吗?

如果你只希望它是一个提示,请使用大括号(无论如何使用它们,它会让你在一天之内免受可怕的错误)。这样的事情。

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