簡體   English   中英

無法使推方法起作用

[英]Can't get push method to work

我需要一些快速的幫助來完成任務,總之,我完成了一項任務,要求我制作一個程序,該程序允許用戶將pop(),push()和top()數組化。

我做到了,但是我的老師說代碼布局錯誤,因為我在堆棧類中有System.out.println語句,這些語句應該在主菜單應用程序中,並且堆棧類應僅調用它從數組繼承的方法類。

我認為還算公平,我修改了代碼,但現在無法使push()方法正常工作:/

我知道我需要在菜單應用程序push()方法中使用Genio.getInteger方法。

有人可以幫忙嗎?

堆棧類別:

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

}

不知道我是否正確理解了您的問題,但是沒有呼叫s.push? (s.pop也不是嗎?)

如果要更換

if (!s.isFull())

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

一些工作會完成嗎?

如果只希望它是提示,請使用大括號(無論如何使用大括號,有一天可以將您從可怕的bug中解救出來)。 這樣的事情。

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