Page 1 of 4 123 ... LastLast
Results 1 to 10 of 32
  1. #1
    Elite Member
    Join Date
    May 2011
    Gender
    Male
    Posts
    1,465

    Default tabang in Java. tabang!


    gamit ani kai stacks

    Input String: {[()]}
    Output: balanced


    Input String: [][](){}
    Output: balanced

    Input String: {[][]}
    Output: balanced

    Input String: {[}]
    Output: error // kai di man balance, ang input kai {[}] man, ang [ kai nasud man sa {} nya iyang pares na ] kai
    naa man sa gawas, dapat {[]} or, {}[] ,or {[]}[] para balance

    Input String: [(])Output: error //kai same japon, di man balance, ang ( kai nasud man sa [] nya ang pares kai na ), kai naa man sa gawas. dapat [()], or [](), or [()]() para balance
    here's my code. tabang ninyu pls. tnx
    Code:
     
    import java.util.*;
    public class Assignment {
        private static Scanner in = new Scanner(System.in);
        private String input;
        private char [] array;
        private int index1, index2;
        private static Stack myStack = new Stack();
        private boolean tf=false;
        private int condition=0,condition1, condition2;
        
        
        public Assignment(){
            askInput();
            Process();
            Output();
        }
        private void askInput(){
            try{
            System.out.println("Input String: ");
            setInput(in.nextLine());
            setArray(new char [getInput().length()]);
            }catch(Exception e){
                System.out.println("You got an error. Try again. "+e.getMessage());
                askInput();
            }
        }
        private void Process(){
            for(int y = 0;y<getInput().length(); y++){
                char i = getInput().charAt(y);
                array[y] = i;
            }
            
            
            for(int x =0; x<input.length();x++){
                if(array[x]=='{'){
                    condition++;
                    myStack.push(array[x]);
                    tf=true;
                }
                if(array[x]=='}'){
                    condition--;
                    tf=true;
                    if(myStack.empty()){}
                    else{
                    myStack.pop();
                    }
                }
                if(array[x]=='['){
                    tf=true;
                    condition1++;
                    myStack.push(array[x]);
                }
                if(array[x]==']'){
                    tf=true;
                    condition1--;
                    if(myStack.empty()){}
                    else{
                    myStack.pop();
                    }
                }
                if(array[x]=='('){
                    tf=true;
                    condition2++;
                    myStack.push(array[x]);
                }
                if(array[x]==')'){
                    tf=true;
                    condition2--;
                    if(myStack.empty()){}
                    else{
                    myStack.pop();
                    }
                }
                 
            }
        }
        private void Output(){
            System.out.println("Output:");
            if(tf==true){
                if(condition==0&condition1==0&condition2==0)
                System.out.println("balanced");
                else
                    System.out.println("error");
            }
            else
                System.out.println("error");
            
                
             
            /*
            if(myStack.isEmpty())
                System.out.println("balanced");
            else
                System.out.println("error");
             * 
             */
                
            
        }
       
        private void setInput(String input){
            this.input = input;
        }
        private String getInput(){
            return input;
        }
        private void setArray(char [] array){
            this.array = array;
        }
        private char [] getArray(){
            return array;
        }
        
        
        public static void main(String args[]){
            Assignment a = new Assignment();
        }
        
    }

  2. #2

    Default Re: tabang in Java. tabang!

    suwayi daw ni jairoh if ok ba...bag-o ra ko nahuman code...hehehe....
    comment lang if asa imo wa nasabtan

    simple but rock ang code...
    Code:
    import javax.swing.*;
    import java.util.*;
    
    public class Stacker
    {
    	private Stack<Object> stack;
    	private String input;
    	private int size;
    
    
    	public Stacker()
    	{
    		input = JOptionPane.showInputDialog(null, "Input String");
    		size = input.length();
    		stack = new Stack<Object>();
    		Process();
    	}
    
    	public void Process()
    	{
    		for (int i = 0; i < size; i++)
    		{
    			char c = input.charAt(i);
    			switch(c)
    			{
    				case '{':
    				case '[':
    				case '(':
    					stack.push(c);
    					break;
    
    				case '}':
    					if (isBrace(stack.peek().toString().charAt(0)))
    					{
    						stack.pop();
    					}
    					break;
    				case ']':
    					if (isBracket(stack.peek().toString().charAt(0)))
    					{
    						stack.pop();
    					}
    					break;
    				case ')':
    					if (isParenthesis(stack.peek().toString().charAt(0)))
    					{
    						stack.pop();
    					}
    					break;
    
    			}
    		}
    	}
    
    	public boolean isParenthesis(char c)
    	{
    		return c == '(' || c == ')';
    	}
    
    	public boolean isBracket(char c)
    	{
    		return c == '[' || c == ']';
    	}
    
    	public boolean isBrace(char c)
    	{
    		return c == '{' || c == '}';
    	}
    
    	public String toString()
    	{
    		StringBuffer sb = new StringBuffer();
    
    		if (stack.isEmpty())
    			sb.append("Balanced");
    		else
    			sb.append("Not Balanced");
    
    		return sb.toString();
    	}
    
    	/* for testing to view the contents of stack
    	public void display()
    	{
    		while (!stack.isEmpty())
    		{
    			System.out.print(stack.peek() + ",");
    			stack.pop();
    		}
    	}
    	*/
    
    	public static void main(String[] args)
    	{
    		Stacker s = new Stacker();
    		System.out.println(s);
    	}
    }

  3. #3
    Elite Member
    Join Date
    Jun 2010
    Gender
    Male
    Posts
    1,018

    Default Re: tabang in Java. tabang!

    Superstar's work should be correct.
    Basically it boils down to algorithm, you could have been more explicit sa pairing sa opening object vs. closing object.
    Plus the latest opened object is waiting to be closed first, bali FIRST IN LAST OUT.
    You should have taken full advantage of the Stack.
    Sa imong current algorithm, basta within sa string nigawas ang open og ang close og walay sobra, balanced gihapon siya.

    Mao ni ako algorithm. (though same ra jud kay Superstar)

    Loop the string.

    If '{' or '[' or '(' => PUSH sa Stack

    If '}' or ']' or ')' => Check sa top item sa Stack.

    If pair sila Pop sa one time ang stack unya Continue sa loop.
    If dili end dayon (no need to continue), unya Unbalanced na siya.

    Lastly, kung empty ang stack, after sa loop, balanced siya.
    Last edited by Klave; 02-29-2012 at 04:06 PM.

  4. #4

    Default Re: tabang in Java. tabang!

    @klave: yes bro, naa kuwang sa akoa code ang pag exit if dili na parehas sa top item sa stack...since i used switch mao dili nako mag break dayon...its up to jairoh kung iya na himuon if statements den break the loop if not parehas ang top stack. hehehe

    note: sakto daghan man algorithm bro and i can create much lesser code than this and OPTIMIZED pa kaso lang si jairoh is still a student an i'm giving him codes that are easy to read and understand...
    mao man gud na tudlo sa amo teacher...hehehe

  5. #5
    Elite Member
    Join Date
    May 2011
    Gender
    Male
    Posts
    1,465

    Default Re: tabang in Java. tabang!

    ok, basically pasabta ko anang mga boolean2x nimo bro @SuperStar b, kanang mga
    if (isBrace(stack.peek().toString().charAt(0))) nimo. nakahimo nako sakong codes w/c runs perfectly, salamat sa imong concept bro Klave.
    here is my code
    Code:
    import java.util.*;
    import javax.swing.*;
    public class brackets2 {
        private static Stack myStack;
        private String input;
        //q1qw22222222 private static PriorityQueue q;
        
        public brackets2(){
            while(true){
            askInput();
            }
        }
        public void askInput(){
            input = JOptionPane.showInputDialog(null,"Input String: ");
            myStack = new Stack();
            Process();
            
        }
        public void Process(){
            try{
            for(int x=0; x<input.length();x++){
                char i = input.charAt(x);
                switch(i){
                    case '{':
                    case '[':
                    case '(':
                        myStack.push(i);
                        break;
                    case '}':
                        if(myStack.peek()=='{')
                            myStack.pop();
                        break;
                    case ']':
                        if(myStack.peek()=='[')
                            myStack.pop();
                        break;
                    case ')':
                        if(myStack.peek()=='(')
                            myStack.pop();
                        break;
                }
            }
            }catch(Exception e){
                JOptionPane.showMessageDialog(null,"error");
                Continue();
            }
            toString();
            Continue();
        }
        public String toString(){
            StringBuffer sb = new StringBuffer();
            
            if(myStack.isEmpty())
                sb.append("balanced");
            else
                sb.append("error");
            
            JOptionPane.showMessageDialog(null,sb);
            return sb.toString();
            
        }
        public void Continue(){
            input = JOptionPane.showInputDialog(null,"Do you want to continue? y/n");
            if(input.equalsIgnoreCase("n"))
                System.exit(0);
            else if(!input.equalsIgnoreCase("y")){
                JOptionPane.showMessageDialog(null,"Invalid Input.");
                Continue();
            }
            askInput();
        }
        
        public static void main(String args[]){
            brackets2 b2 = new brackets2();
        }
        
    }
    Last edited by jairoh_; 02-29-2012 at 04:36 PM.

  6. #6

    Default Re: tabang in Java. tabang!

    Quote Originally Posted by jairoh_ View Post
    ok, basically pasabta ko anang mga boolean2x nimo bro @SuperStar b, kanang mga
    if (isBrace(stack.peek().toString().charAt(0))) nimo. nakahimo nako sakong codes w/c runs perfectly, salamat sa imong concept bro Klave.
    if (isBrace(stack.peek().toString().charAt(0)))

    kani nga code kay mas optimize man kay i'm using the built-in stack class from java...mas pas2x man ni execution time....especially if DAKO na kaayo ang size sa stack...lets say million

  7. #7
    Elite Member
    Join Date
    May 2011
    Gender
    Male
    Posts
    1,465

    Default Re: tabang in Java. tabang!

    @bro superstar, nosebleed japon ko ani(kanang bolded)
    Quote Originally Posted by SuperStar View Post
    Code:
    import javax.swing.*;
    import java.util.*;
    
    public class Stacker
    {
    	private Stack<Object> stack;
    	private String input;
    	private int size;
    
    
    	public Stacker()
    	{
    		input = JOptionPane.showInputDialog(null, "Input String");
    		size = input.length();
    		stack = new Stack<Object>();
    		Process();
    	}
    
    	public void Process()
    	{
    		for (int i = 0; i < size; i++)
    		{
    			char c = input.charAt(i);
    			switch(c)
    			{
    				case '{':
    				case '[':
    				case '(':
    					stack.push(c);
    					break;
    
    				case '}':
    					if (isBrace(stack.peek().toString().charAt(0)))
    					{
    						stack.pop();
    					}
    					break;
    				case ']':
    					if (isBracket(stack.peek().toString().charAt(0)))
    					{
    						stack.pop();
    					}
    					break;
    				case ')':
    					if (isParenthesis(stack.peek().toString().charAt(0)))
    					{
    						stack.pop();
    					}
    					break;
    
    			}
    		}
    	}
    
    	public boolean isParenthesis(char c)
    	{
    		return c == '(' || c == ')';
    	}
    
    	public boolean isBracket(char c)
    	{
    		return c == '[' || c == ']';
    	}
    
    	public boolean isBrace(char c)
    	{
    		return c == '{' || c == '}';
    	}
    
    	public String toString()
    	{
    		StringBuffer sb = new StringBuffer();
    
    		if (stack.isEmpty())
    			sb.append("Balanced");
    		else
    			sb.append("Not Balanced");
    
    		return sb.toString();
    	}
    
    	/* for testing to view the contents of stack
    	public void display()
    	{
    		while (!stack.isEmpty())
    		{
    			System.out.print(stack.peek() + ",");
    			stack.pop();
    		}
    	}
    	*/
    
    	public static void main(String[] args)
    	{
    		Stacker s = new Stacker();
    		System.out.println(s);
    	}
    }

  8. #8

    Default Re: tabang in Java. tabang!

    Code:
    for(int x=0; x<input.length();x++)
    jairoh, i suggest that you should not use this style of code because it will affect the program during runtime...you'll know a lot of this during your Data Structures subject.

    much better if you'll assign it to a variable, e.g. size like this
    Code:
    size = input.length();
    for(int x=0; x<size ;x++)
    well, explainan tka gamay.. if imo ukayon ang .length() method..you'll see that it will loop individually the charater...so ang mahitabo ana, every increment nimo nag loop pud ang lenght() method which will double the loop imbis dili unta dapat....nahulog nga nag nested loop naka ana imbis linear loop ra imo gibuhat

  9. #9

    Default Re: tabang in Java. tabang!

    Code:
    	public boolean isParenthesis(char c)
    	{
    		return c == '(' || c == ')';
    	}
    is equivalent to

    Code:
    	public boolean isParenthesis(char c)
    	{
                  if (c == '(' || c == ')')
    		return true;
                  else
                    return false;
    	}
    tan-awa ari bro kay naa diri ang nindot nga sample ug simple pag ka explain
    http://www.cafeaulait.org/course/week2/43.html
    hope this helps

  10. #10
    Elite Member
    Join Date
    May 2011
    Gender
    Male
    Posts
    1,465

    Default Re: tabang in Java. tabang!

    Quote Originally Posted by SuperStar View Post
    Code:
    for(int x=0; x<input.length();x++)
    jairoh, i suggest that you should not use this style of code because it will affect the program during runtime...you'll know a lot of this during your Data Structures subject.

    much better if you'll assign it to a variable, e.g. size like this
    Code:
    size = input.length();
    for(int x=0; x<size ;x++)
    well, explainan tka gamay.. if imo ukayon ang .length() method..you'll see that it will loop individually the charater...so ang mahitabo ana, every increment nimo nag loop pud ang lenght() method which will double the loop imbis dili unta dapat....nahulog nga nag nested loop naka ana imbis linear loop ra imo gibuhat
    let me correct you bro if i'm correct bro about this code
    Code:
    for(int x=0; x<input.length();x++)
    sa akong nasabtan kunohay, pananglitan 5 ang length sa input. and then x is 0, nya 0 is less than 5 man, so mag.loop cya 5 times ra. hantod maabot sa 4 which is true kai 4 is less than 5 man. wa ko kasabot sa imong ipasabot nako nga it'll double the loop. hehehe. sorry noob pa tawn ta.



    Quote Originally Posted by SuperStar View Post
    Code:
    	public boolean isParenthesis(char c)
    	{
    		return c == '(' || c == ')';
    	}
    is equivalent to

    Code:
    	public boolean isParenthesis(char c)
    	{
                  if (c == '(' || c == ')')
    		return true;
                  else
                    return false;
    	}
    tan-awa ari bro kay naa diri ang nindot nga sample ug simple pag ka explain
    The ? : operator in Java
    hope this helps
    ako sa ning sabton bro ha.. hapit na hurot akong tissue dri(nosebleed man ta)

  11.    Advertisement

Page 1 of 4 123 ... LastLast

Similar Threads

 
  1. Jeepney fare history in Cebu.. tabang istoryans..
    By nodols3 in forum Business, Finance & Economics Discussions
    Replies: 51
    Last Post: 06-14-2016, 03:27 PM
  2. Tabang mga Java programmers!!!
    By IGN.Boss Wax in forum Programming
    Replies: 4
    Last Post: 11-08-2012, 02:17 PM
  3. How to clear buffer in Java?
    By ares623 in forum Programming
    Replies: 17
    Last Post: 09-22-2009, 11:20 AM
  4. TABANG In good terms mi sa manghod sa ako EX-
    By truelegitballer in forum Relationships (Old)
    Replies: 146
    Last Post: 05-17-2009, 01:04 AM
  5. image bigger than its panel in java
    By manick in forum Programming
    Replies: 4
    Last Post: 09-11-2008, 08:55 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
about us
We are the first Cebu Online Media.

iSTORYA.NET is Cebu's Biggest, Southern Philippines' Most Active, and the Philippines' Strongest Online Community!
follow us
#top