2016-06-01 43 views
1

如何傳遞一個整數的堆棧,它返回偶數的個數。該方法完成執行後,堆棧必須保持不變。如果堆棧爲空,則返回null。從棧中返回偶數?

這是我走到這一步,對不起,我是一個初學者。

public static int countEven(Stack<Integer> stk) { 

     Stack stack = new stack(); 
     int count = 0; 

     while (int i=0; i<stack.length; i++);   
      int value = s.pop(); 

      if (stack %2 == 0);      
       count++; 

      stack.push(value); 

     while (int i=0; stack != 0; i++); 
      s.push(stack.pop()); 

    return 0; 
} 
+0

本教程中,你有沒有在Python代碼學習Java之前?只是好奇。無論如何,你需要學習基本的語法 - 特別是如何使用大括號'''''''''',特別是在哪裏放置分號。 – dasblinkenlight

+1

此代碼不能編譯。請拿一本書並瞭解該語言的基礎知識。我建議學習迭代構造和變量的範圍。在提交到StackOverflow之前,也可以使用代碼編譯的IDE。 – Paolof76

回答

0

您檢查模塊2上的堆棧?您必須檢查堆棧中的值。 你也可以使用「get」功能。它只給你堆棧中的值(對於給定的索引)而不刪除它。

如果返回一個整數,你不能返回null。只需返回-1 ...

public static int countEven(Stack<Integer> stk) { 

    int count = 0; 
    if (stk.size() == 0) 
     return -1; 

    while (int i=0; i<stk.size(); i++) { 
     int value = stk.get(i); 
     if (value %2 == 0)      
      count++; 
    }  

    return count; 
} 
0

您不需要從堆棧中刪除元素。您可以獲得Iterator並遍歷所有元素並處理您的支票。

您的方法可能看起來像。

static int countEven(Stack<Integer> stack) { 
    // get an Iterator for the passed stack 
    Iterator<Integer> iterator = stack.iterator(); 
    int count = 0; 
    // as long the iterator would return another element process the loop 
    while (iterator.hasNext()) { 
     // check if the integer is even 
     if (iterator.next() % 2 == 0) { 
      // increase the even counter 
      count++; 
     } 
    } 
    // return the count, if there was no element returned by the iterator 
    // `count` would not have been incremented and therefor return zero 
    return count; 
} 
0

你並不需要修改你堆疊或使用其他堆棧使用java.util.Stack

Stack延伸Vector把所有的元素,所以你可以使用get(int)

public static int countEven(Stack<Integer> stack) { 
    // Return 0 if the stack is empty 
    if (stack == null || stack.isEmpty()) { 
     return 0; 
    } 

    int count = 0; 
    int size = stack.size(); 

    for (int i = 0; i < size; i++) {   
     int value = stack.get(i); // get ith element 
     if (value % 2 == 0)      
      count++; 
    } 

    return count; 
} 

正如你新的Java,我建議你通過一些關於Java的基礎知識。 您可以參考上TutorialsPoint