2016-07-27 7 views
-1

이 toString 메서드를 구현하는 데 어려움이 있습니다. 문제는 가장 큰 인덱스에 대해 ArrayStack의 각 값을 (콘솔에) 인쇄해야하며 각 인덱스가 다른 행에 있어야한다는 것입니다. 문제는 int() 배열이 아닌 일반 스택으로 구현되기 때문에 값이 (분명히) 정수가 아니라는 것입니다. 이것을 성취하는 것이 간단해야합니다. 나는 Java에 익숙하지 않기 때문에 작업 할 수있는 지식이 극히 제한되어 있습니다. 나는 아래의 toString 메서드를 붙여 넣고 전체 코드를 추적했다.Java - ArrayStack을 구현할 수 없습니다. toString 메서드는 모든 다른 행에 인쇄해야합니다.

 public String toString(){ 
      String test = ""; 
      int tester; 
      if(size()>0){ 
       for(int i=size()-1;i>-1;i--){ 

       test+= Integer.toString(stack[i]) + "\n"; 
       } 
      }else{ 
       test = " This stack is empty"; 
      } 
      return test; 
     } 

전체 코드

import java.util.*; 
import java.util.Arrays; 
public class Miller_A05Q1 { 

    /** 
    * Program entry point for stack testing. 
    * @param args Argument list. 
    */  
    public static void main(String[] args) 
    { 
     ArrayStack<Integer> stack = new ArrayStack<Integer>(); 

     System.out.println("STACK TESTING"); 

     stack.push(3); 
     stack.push(7); 
     stack.push(4); 
     System.out.println(stack.peek()); 
     stack.pop();   
     stack.push(9); 
     stack.push(8); 
     System.out.println(stack.peek());   
     System.out.println(stack.pop()); 
     System.out.println(stack.peek());   

     System.out.println("The size of the stack is: " + stack.size()); 
     System.out.println("The stack contains:\n" + stack.toString());   
    } 

    /** 
    * An array implementation of a stack in which the bottom of the 
    * stack is fixed at index 0. 
    * 
    * @author Java Foundations 
    * @version 4.0 
    */ 
    public static class ArrayStack<T> implements StackADT<T> 
    { 
     private final static int DEFAULT_CAPACITY = 100; 
     private int count; 
     private int top; 
     private T[] stack; 

     /** 
     * Creates an empty stack using the default capacity. 
     */ 
     public ArrayStack() 
     { 
      this(DEFAULT_CAPACITY); 
     } 

     /** 
     * Creates an empty stack using the specified capacity. 
     * @param initialCapacity the initial size of the array 
     */ 
     @SuppressWarnings("unchecked") //see p505. 
     public ArrayStack(int initialCapacity) 
     { 
      top = 0; 
      stack = (T[])(new Object[initialCapacity]); 
     } 

     /** 
     * Adds the specified element to the top of this stack, expanding 
     * the capacity of the array if necessary. 
     * @param element generic element to be pushed onto stack 
     */ 
     public void push(T element) 
     { 
      if (size() == stack.length) 
       expandCapacity(); 

      stack[top] = element; 
      top++; 
     } 

     /** 
     * Creates a new array to store the contents of this stack with 
     * twice the capacity of the old one. 
     */ 
     private void expandCapacity() 
     { 
      stack = Arrays.copyOf(stack, stack.length * 2); 
     } 

     /** 
     * Removes the element at the top of this stack and returns a 
     * reference to it. 
     * @return element removed from top of stack 
     * @throws EmptyCollectionException if stack is empty 
     */ 
     public T pop() throws EmptyCollectionException 
     { 
      if (isEmpty()) 
       throw new EmptyCollectionException("stack"); 

      top--; 
      T result = stack[top]; 
      stack[top] = null; 

      return result; 
     } 

     /** 
     * Returns a reference to the element at the top of this stack. 
     * The element is not removed from the stack. 
     * @return element on top of stack 
     * @throws EmptyCollectionException if stack is empty 
     */ 
     public T peek() throws EmptyCollectionException 
     { 
      if (isEmpty()) 
       throw new EmptyCollectionException("stack"); 

      return stack[top-1]; 
     } 

     /** 
     * Returns true if this stack is empty and false otherwise. 
     * @return true if this stack is empty 
     */ 
     public boolean isEmpty() 
     { 
      if (size() == 0){ 
       return true; 

      }else{ 
      return false; 
     } 
     } 

     /** 
     * Returns the number of elements in this stack. 
     * @return the number of elements in the stack 
     */ 
     public int size() 

     {  count = 0; 
       for(int i = 0;i<stack.length;i++){ 
       if(stack[i] != null){ 
        count++; 
       } 
      } 
       return count; 
     } 

     /** 
     * Returns a string representation of this stack. The string has the 
     * form of each element printed on its own line, with the top most 
     * element displayed first, and the bottom most element displayed last. 
     * If the list is empty, returns the word "empty". 
     * @return a string representation of the stack 
     */ 
     public String toString(){ 
      String test = ""; 
      int tester; 
      if(size()>0){ 
       for(int i=size()-1;i>-1;i--){ 

       test+= Integer.toString(stack[i]) + "\n"; 
       } 
      }else{ 
       test = " This stack is empty"; 
      } 
      return test; 
     } 

    } 
    public static class EmptyCollectionException extends RuntimeException 
{ 
    /** 
    * Sets up this exception with an appropriate message. 
    * @param collection the name of the collection 
    */ 
    public EmptyCollectionException(String collection) 
    { 
     super("The " + collection + " is empty."); 
    } 
} 
    public class LinearNode<T> 
{ 
    private LinearNode<T> next; 
    private T element; 

    /** 
    * Creates an empty node. 
    */ 
    public LinearNode() 
    { 
     next = null; 
     element = null; 
    } 

    /** 
    * Creates a node storing the specified element. 
    * @param elem element to be stored 
    */ 
    public LinearNode(T elem) 
    { 
     next = null; 
     element = elem; 
    } 

    /** 
    * Returns the node that follows this one. 
    * @return reference to next node 
    */ 
    public LinearNode<T> getNext() 
    { 
     return next; 
    } 

    /** 
    * Sets the node that follows this one. 
    * @param node node to follow this one 
    */ 
    public void setNext(LinearNode<T> node) 
    { 
     next = node; 
    } 

    /** 
    * Returns the element stored in this node. 
    * @return element stored at the node 
    */ 
    public T getElement() 
    { 
     return element; 
    } 

    /** 
    * Sets the element stored in this node. 
    * @param elem element to be stored at this node 
    */ 
    public void setElement(T elem) 
    { 
     element = elem; 
    } 
} 
    public interface StackADT<T> 
{ 
    /** 
    * Adds the specified element to the top of this stack. 
    * @param element element to be pushed onto the stack 
    */ 
    public void push(T element); 

    /** 
    * Removes and returns the top element from this stack. 
    * @return the element removed from the stack 
    */ 
    public T pop(); 

    /** 
    * Returns without removing the top element of this stack. 
    * @return the element on top of the stack 
    */ 
    public T peek(); 

    /** 
    * Returns true if this stack contains no elements. 
    * @return true if the stack is empty 
    */ 
    public boolean isEmpty(); 

    /** 
    * Returns the number of elements in this stack. 
    * @return the number of elements in the stack 
    */ 
    public int size(); 

    /** 
    * Returns a string representation of this stack. 
    * @return a string representation of the stack 
    */ 
    public String toString(); 


} 
} 
+2

이 유형의 경우 일반적인 필요하지 않은 'Integer.toString (...)'을 수행하려면'String.valueOf (stack [i])'를 사용할 수 있습니다. –

답변

0

자바의 모든 개체가 더 나은 아직 + 운영자, 또는를 사용하여 String에 concatinate 때 암시 적으로 호출되는 toString() 방법을 가지고, 때를 StringBuilder에 추가하십시오. ,

@Override 
public String toString(){ 
    StringBuilder sb = new StringBuilder(); 
    if (size() > 0) { 
     for (int i = size() - 1; i > -1 ; i--) { 
      sb.append(stack[i]).append(System.lineSeparator()); 
     } 
     return sb.toString(); 
    } 
    return "This stack is empty"; 
} 

는 그런 말로 미루어 보아, 자바 (8)의 스트림이 여기 보일러 플레이트 코드를 많이 절약 할 수 있습니다 : : 그래서 당신이 뭔가를 할 수

@Override 
public String toString(){ 
    StringBuilder sb = new StringBuilder(); 
    if (size() > 0) { 
     return Arrays.stream(stack) 
        .collect(Collectors.joining(System.lineSeparator())); 
    } 
    return "This stack is empty"; 
}