1,105,232 Community Members

Stack can`t pop off (see the code). Java with problem? URGENT SOS

Member Avatar
tedtdu
Newbie Poster
18 posts since Aug 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Dear all.
Thanks for you kind and generous supporting.
From the String s="<hell <world </world </hell";
I wanted push the elements "<hello, <world" into stack, and pop off if current element equal to peek element in stack.

Question: Even stack.peek().equals(CURRENT ELEMENT), why can not pop off, but occurs error??
Please give me your suggestion. PLEASE!!!!

import java.util.*;

public class GomiTest{
	
	public static void main(String[] args){
		Stack<String> stack = new Stack<String>();
		String s="<hell <world </world </hell";
		String temp[]=null;
		String jin;
		temp=s.split(" ");
		
		for(int i=0;i<temp.length;i++){
			if(temp[i].startsWith("</")){
				jin=temp[i].replace("/","");
				//System.out.println("jin "+jin);
				if(!stack.empty()&&stack.peek().equals(jin)){
		          System.out.println("pop "+stack.pop());
				}else{
					System.out.println("error");
				}
			//	System.out.println("pushed "+temp[i].replace("</",""));
			}else if(temp[i].startsWith("<")){
				//jin=temp[i].replace("<","");
				System.out.println("pushed "+temp[i]);
			}else{
				System.out.println("other "+temp[i]);
			}
		}
	}
}
Member Avatar
JamesCherrill
... trying to help
10,363 posts since Apr 2008
Reputation Points: 2,081 [?]
Q&As Helped to Solve: 1,749 [?]
Skill Endorsements: 47 [?]
Moderator
Featured
 
0
 

Where do you push into the stack?
Exactly what "error"s do you get?

Member Avatar
tedtdu
Newbie Poster
18 posts since Aug 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

@JamesCherrill , Sorry sir, it was my mistake
Thanks for attention given

Question Answered as of 3 Years Ago by JamesCherrill
Member Avatar
NormR1
Posting Sage
7,723 posts since Jun 2010
Reputation Points: 563 [?]
Q&As Helped to Solve: 793 [?]
Skill Endorsements: 16 [?]
Team Colleague
 
0
 
Member Avatar
jon.kiparsky
Posting Virtuoso
1,837 posts since Jun 2010
Reputation Points: 326 [?]
Q&As Helped to Solve: 192 [?]
Skill Endorsements: 6 [?]
 
0
 

Why are you peeking at the stack in the first place? Think of it as a real stack: push and pop only. When your current token has a '/', you pop the stack. If the item you pop is not equal to the current token (modulo '/', of course) then you know you have an invalid string. For a student code assignment, you can just throw off an error there.
If you want more robust code, you would write more complex handling, which might involve pushing the popped item back on the stack, but for now, do it simple.

You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article