Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Page 2 of 2 FirstFirst 12
Results 26 to 32 of 32

Thread: Splitting text into several components

  1. #26
    Super Moderator Sean4u's Avatar
    Join Date
    Jul 2011
    Location
    Tavistock, UK
    Posts
    637
    Thanks
    5
    Thanked 103 Times in 93 Posts

    Default Re: Splitting text into several components

    I have already explained how to make a TreeMap sort in reverse Integer order. Read the API doc for TreeMap, use the constructor with the Comparator in it and write a Comparator that does what you want. It's much easier than the quantity of documentation would have you believe.

    If you're not using some legacy Java, or some Java that has been written for the sole purpose of annoying you, you shouldn't be casting any references. If you do find yourself believing it necessary, you should fix your code where you went wrong so you don't have to do it.

    Your TreeMap<Integer, Integer> should be *inside* your Polynomial class. Every time you matcher.find() a term in the input string, you should thePoly.add(coeff, exp) - that method will put two Integers into the TreeMap. When you've exhausted your input string, print thePoly and it will magically look right because you'll have a toString() method like:
    @Override
    public String toString()
    {
      StringBuilder sb = new StringBuilder();
      /* terms magically in correct order, thanks to TreeMap */
      for (Map.Entry<Integer/*exp*/, Integer/*coeff*/> entry : MAP.entrySet())
      {
         /* style each term */
      }
      return sb.toString(); 
    }

  2. The Following User Says Thank You to Sean4u For This Useful Post:

    clydefrog (February 23rd, 2012)

  3. #27
    Member clydefrog's Avatar
    Join Date
    Feb 2012
    Posts
    67
    Thanks
    15
    Thanked 2 Times in 2 Posts

    Default Re: Splitting text into several components

    Quote Originally Posted by snowguy13 View Post
    You're welcome! So, I'm curious, what is the extent of this program's functionality? How much and what will it do when it's done?
    Well basically it takes 2 polynomials of the nth degree, and is capable of adding, subtracting, multiplying and dividing them; then returning the result in canonical form.

    I've gotten about everything working except, multiplication (im sort of stuck on this for now) and division (which once i implement multiplication, will be simple as it's just the inverse). It also doesnt simplify the users input correctly yet either, like: -12x^5+6x^3-3x+5 + 1 does NOT simplify into -12x^5+6x^3-3x+6 shouldnt be too hard to get working though.

    if you like, you can go ahead and give it a spin. it even has a gui now lol.


    package project2;
     
    import java.awt.Color;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
     
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
     
    //polynomial class
    class Polynomial
    {
    	Node head;	
     
    	Polynomial()
    	{
    		head = null;
    	}
     
    	//insert Node
    	public void add(int coef, int power)
    	{
     
    		Node temp = new Node(coef, power, null);		
     
    		if (head == null)
    		{
    			head = temp;			
    		}
    		else {			
    			Node p = null;
    			Node q = head;
    			//insert in front if exponent is higher
    			if (temp.getElement2() > q.getElement2())
    			{				
    				temp.setNext(head);
    				head = temp;				
    			} 
    			else 
    			{
    				//insert at middle or end				
    				while ( q != null && q.getElement2() > temp.getElement2())
    				{				
    					p = q;
    					q = q.getNext();
    				}
    				p.setNext(temp);
    				temp.setNext(q);				
    			}
    		}
     
    	}
     
    //add 2 polynomials together
    	public Polynomial addPoly(Polynomial poly1, Polynomial poly2){
    		Polynomial tempPoly = new Polynomial();
     
    		int power = (poly1.head.getElement2() > poly2.head.getElement2()) ? poly1.head.getElement2() : poly2.head.getElement2();
     
    		while (power >=0){
    			Node n1 = poly1.head;
    			while (n1 != null){
    				if (n1.getElement2() == power)
    				break;
    				n1 = n1.getNext();
    			}
     
    			Node n2 = poly2.head;
    			while (n2 != null){
    				if (n2.getElement2() == power)
    				break;
    				n2 = n2.getNext();
    			}
     
    			if((n1 != null) && (n2 != null))
    				tempPoly.add((n1.getElement1() + n2.getElement1()), n1.getElement2());
    			else if (n1 != null)
    				tempPoly.add(n1.getElement1(), n1.getElement2());
    			else if (n2 != null)
    				tempPoly.add(n2.getElement1(), n2.getElement2());
    			power--;
    		}
    		return tempPoly;
    	}
    //Subtract 2 polynomials
    	public Polynomial subPoly(Polynomial poly1, Polynomial poly2){
    		Polynomial tempPoly = new Polynomial();			
     
     
    		int power = (poly1.head.getElement2() > poly2.head.getElement2()) ? poly1.head.getElement2() : poly2.head.getElement2();
     
    		while (power >=0){
    			Node n1 = poly1.head;
    			while (n1 != null){
    				if (n1.getElement2() == power)
    				break;
    				n1 = n1.getNext();
    			}
     
    			Node n2 = poly2.head;
    			while (n2 != null){
    				if (n2.getElement2() == power)
    				break;
    				n2 = n2.getNext();
    			}
     
    			if((n1 != null) && (n2 != null))
    				tempPoly.add((n1.getElement1() + (n2.getElement1()* -1)), n1.getElement2());
    			else if (n1 != null)
    				tempPoly.add(n1.getElement1(), n1.getElement2());
    			else if (n2 != null)
    				tempPoly.add(n2.getElement1()* -1, n2.getElement2());
    			power--;
    		}
    		return tempPoly;
    	}
     
    //Multiply 2 polynomials - not working
     
    	/*public Polynomial multPoly(Polynomial poly1, Polynomial poly2)
    	{
     
    	int coef;
    	int power;
     
    	Polynomial poly3 = new Polynomial();
     
    	Node n1 = poly1.head;
    	Node n2 = poly2.head;
     
    	while ( poly1 != null )
    	            {
     
    		while ( poly2 != null )
    	                {
    	                    coef = n1.Element1 * n2.Element1;
    	                    power = poly1.head.Element1 + poly2.head.Element1;
     
    	                    System.out.println(coef);
    	                    System.out.println(power);
     
    	                    n2 = n2.getNext();
     
     
     
    	                    poly3.add(coef, power) ;
    	                }
     
    	               n2 = poly2.head;  
     
    	                n1 = n1.getNext() ;  
    	            }
     
    	return poly3;
     
    	}*/
     
    	//Prepare the string using regular expression
    	public Polynomial prep(String s)
    	{
     
    		Polynomial poly = new Polynomial();
     
    		s= s.replaceAll("\\s+", "");
     
    		String str1 = "(-?[0-9]{1,})x\\^(-?[0-9]{1,})?";
    		String str2 = "(-?[0-9]{1,})x";
    		String str3 = "(-?[0-9]{1,})";
    		Pattern p = Pattern.compile(str1);
    		Pattern p2 = Pattern.compile(str2);
    		Pattern p3 = Pattern.compile(str3);
     
    		Matcher matcher = p.matcher(s);
    		Matcher matcher2 = p2.matcher(s);
    		Matcher matcher3 = p3.matcher(s);
    		int coef;
    		int exp;
     
    		int index = 0;
    		boolean matchFound;				 
    		do{
    			if(matchFound = matcher.find(index))
    			{
     
    				coef = Integer.parseInt(matcher.group(1));
    				exp = Integer.parseInt(matcher.group(2));  
     
    			    poly.add(coef,exp);
     
    				index = matcher.end();
    			}
    			else if (matchFound = matcher2.find(index))
    			{
    				String groupStr = matcher2.group(1);				
    				poly.add(Integer.parseInt(matcher2.group(1)),1);
     
    				index = matcher2.end();
    			}
    			else if (matchFound = matcher3.find(index))
    			{
    				String groupStr = matcher3.group(1);				
    				poly.add(Integer.parseInt(matcher3.group(1)),0);
     
    				index = matcher3.end();
    			}
    			else
    				matchFound = false;
     
    		}while(matchFound);		
     
    		return poly;
     
    	}
     
    	//to string	
    	public String toString()
    	{
    		Node current = head.getNext();
    		String output = "";
    		if(head != null)
    		{
    			if(head.Element1 == 0)
    			{
     
    			}
    			else if (head.Element2 == 0)
    			{
    				output += head.Element1;
    			}
    			else if (head.Element2 == 1)
    			{
    				output += head.Element1 + "x";
    			}
    			else
    			{
    				output += head.Element1 + "x^" + head.Element2;
    			}
     
    		}
    		while(current != null)
    		{
    			if(current.Element1 == 0)
    			{
     
    			}
    			else if (current.Element2 == 0)
    			{
    				if (current.Element1 > 0)
    				{
    					output += "+" + current.Element1;
    				}
    				else
    					output += current.Element1;
    			}
    			else if (current.Element2 == 1)
    			{
    				if (current.Element1 > 0)
    				{
    					output += "+" + current.Element1 + "x";
    				}
    				else					
    					output += current.Element1 + "x";
    			}
    			else if (current.Element1 > 0)
    			{
    				output += "+" + current.Element1 + "x^" + current.Element2;
    			}
    			else
    			{
    				output += current.Element1 + "x^" + current.Element2;
    			}
    			current = current.getNext();
    		}
    		return output;
    	}
     
    //node class
    	class Node
    	{
    		int Element1, Element2;
    		Node next;
     
    		public Node(int Element1,int Element2)
    		{			
    			this.Element1 = Element1;			
    			this.Element2 = Element2;
    			next = null;
    		}
     
    		public Node(int Element1, int Element2, Node n) 
    		{
    			this.Element1 = Element1;
    			this.Element2 = Element2;
    			next = n;
    		}
     
    		public Node getNext()
    		{
    			return next;
    		}
     
    		public void setNext(Node next)
    		{
    			this.next = next;
    		}
     
    		public int getElement1() {
    			return Element1;
    		}
     
    		public void setElement1(int element1) {
    			Element1 = element1;
    		}
     
    		public int getElement2() {
    			return Element2;
    		}
     
    		public void setElement2(int element2) {
    			Element2 = element2;
    		}		
    	}
    }
     
    //GUI
    class MainWindow extends JFrame
    {
    	JTextField jPoly1;
    	JTextField jPoly2;
    	JTextArea jResult;
    	JButton jAdd;
    	JButton jSub;
    	JButton jMult;
    	JButton jDiv;
    	JButton jExit;
     
     
     
     
    	MainWindow()
    	{
    		JPanel p1 = new JPanel();		
    		JPanel p2 = new JPanel();
    		JPanel p3 = new JPanel();	
     
    		p1.setLayout(new GridBagLayout());
    		p2.setLayout(new GridBagLayout());
    		p3.setLayout(new GridBagLayout());
     
    		GridBagConstraints c = new GridBagConstraints();
    		c.insets = new Insets(6,6,3,3);
     
    		jPoly1 = new JTextField(20);
    		jPoly2 = new JTextField(20);
    		jResult = new JTextArea(1,20);
    		jAdd = new JButton("ADD +");
    		jSub = new JButton("SUB -");
    		jMult = new JButton("MULT *");
    		jDiv = new JButton("DIV  /");
    		jExit = new JButton("EXIT");
    		jExit.setBackground(Color.orange);
    		JLabel label1 = new JLabel("Polynomial 1:");
    		JLabel label2 = new JLabel("Polynomial 2:");
    		JLabel label3 = new JLabel("Result: ");
     
    		c.gridx = 0;
    		c.gridy = 3;
    		p1.add(label1, c);
     
    		c.gridx = 5;
    		c.gridy = 3;
    		p1.add(jPoly1, c);
     
    		c.gridx = 10;
    		c.gridy = 3;
    		c.fill = GridBagConstraints.HORIZONTAL;
    		p2.add(jAdd, c);
     
    		c.gridx = 15;
    		c.gridy = 3;
    		c.weightx = 0;
    		p2.add(jSub, c);
     
    		c.gridx = 0;
    		c.gridy = 6;
    		p1.add(label2, c);
     
    		c.gridx = 5;
    		c.gridy = 6;
    		p1.add(jPoly2, c);
     
    		c.gridx = 10;
    		c.gridy = 6;		
    		p2.add(jMult, c);
     
    		c.gridx = 15;
    		c.gridy = 6;
    		c.fill = GridBagConstraints.HORIZONTAL;
    		p2.add(jDiv, c);
     
    		c.gridx = 0;
    		c.gridy = 9;
    		p1.add(label3, c);
     
    		c.gridx = 5;
    		c.gridy = 9;
    		p1.add(jResult, c);	
     
    		c.weightx = 0.0;
    		c.gridwidth = GridBagConstraints.REMAINDER;
    		c.gridx = 10;
    		c.gridy = 9;
    		p2.add(jExit, c);
     
    		p1.setBorder(BorderFactory.createTitledBorder("Calculator"));
     
    		p3.add(p1);
    		p3.add(p2);
    		add(p3);
     
    	    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	    setTitle("Polynomial");
    		setSize(525,225);
    		setVisible(true);
     
    		class ExitButtonListener implements ActionListener
    		{
    			public void actionPerformed(ActionEvent e) 
    			{
    				System.exit(0);				
    			}		
     
    		}
     
    		class AddButtonListener implements ActionListener
    		{			
    			public void actionPerformed(ActionEvent e) 
    			{
    				Polynomial poly1 = new Polynomial();
    				Polynomial poly2 = new Polynomial();
    				Polynomial result = new Polynomial();
     
    				String input1 = jPoly1.getText();
    				String input2 = jPoly2.getText();
     
    				poly1 = poly1.prep(input1);
    				poly2 = poly2.prep(input2);
     
    				result = result.addPoly(poly1,poly2);
     
    				jResult.setText("");
    				jResult.append(result.toString());
    			}
     
    		}
     
    		class SubButtonListener implements ActionListener
    		{
    			public void actionPerformed(ActionEvent e) 
    			{
    				Polynomial poly1 = new Polynomial();
    				Polynomial poly2 = new Polynomial();
    				Polynomial result = new Polynomial();
     
    				String input1 = jPoly1.getText();
    				String input2 = jPoly2.getText();
     
    				poly1 = poly1.prep(input1);
    				poly2 = poly2.prep(input2);
     
    				result = result.subPoly(poly1,poly2);
     
    				jResult.setText("");
    				jResult.append(result.toString());				
    			}
     
    		}
     
    		ExitButtonListener bl1 = new ExitButtonListener();
    		jExit.addActionListener(bl1);
     
    		AddButtonListener bl2 = new AddButtonListener();
    		jAdd.addActionListener(bl2);
     
    		SubButtonListener bl3 = new SubButtonListener();
    		jSub.addActionListener(bl3);
    	}
     
    }
     
    //Main
    public class Project {
    	public static void main(String[] args) {
     
    		MainWindow mw = new MainWindow();
     
    	}
     
    }

    Sean4u thank you very much. i actually figured out a way to avoid using a treemap all to gether, but i'll be sure to take a look at that for the future.

    Thank you very much to the both of you. I think i would have still been in square one had it not been for your help.

  4. #28
    Member snowguy13's Avatar
    Join Date
    Nov 2011
    Location
    In Hyrule enjoying a chat with Demise and Ganondorf
    Posts
    339
    My Mood
    Happy
    Thanks
    31
    Thanked 48 Times in 42 Posts

    Default Re: Splitting text into several components

    Ah, that's very cool!
    EDIT: I tried out your program, and it looks great! Something maybe to add (if you want to keep going with this): a recent history of operations the user has done (the addends, minuend/subtrahend, etc. and the answer), so that if for some reason the user must do many calculations and use the answers for more calculations, the answers are saved. Just a suggestion.

    and division (which once i implement multiplication, will be simple as it's just the inverse)
    You seem to know your stuff about polynomials, but just checking: do you know how polynomial division works? It is quite a bit more complicated than the multiplication.
    Last edited by snowguy13; February 23rd, 2012 at 08:25 AM.
    Use highlight tags to help others help you!

    [highlight=Java]Your prettily formatted code goes here[/highlight]

    Using these tags makes your code formatted, and helps everyone answer your questions more easily!




    Wanna hear something funny?

    Me too.

  5. #29
    Member clydefrog's Avatar
    Join Date
    Feb 2012
    Posts
    67
    Thanks
    15
    Thanked 2 Times in 2 Posts

    Default Re: Splitting text into several components

    Quote Originally Posted by snowguy13 View Post
    Ah, that's very cool!
    EDIT: I tried out your program, and it looks great! Something maybe to add (if you want to keep going with this): a recent history of operations the user has done (the addends, minuend/subtrahend, etc. and the answer), so that if for some reason the user must do many calculations and use the answers for more calculations, the answers are saved. Just a suggestion.
    hehe thank you.

    You know, thats actually a really good idea! That way, the user can take the result and perform more calculations on it without having to copy and paste all the time. i like it! thanks for the suggestion

    Quote Originally Posted by snowguy13 View Post
    You seem to know your stuff about polynomials, but just checking: do you know how polynomial division works? It is quite a bit more complicated than the multiplication.
    You know, i'm gonna be quite honest; its been about a year since i've taken any math courses so i am a bit rusty. Its amazing how quickly you forget things once you dont use them, even if you've taken 3 years worth of calculus and upper level differential equations lol. I actually found myself struggling to remember how to add polynomials :/

    but if i'm not mistaking, for division, can i not just divide the coefficients and subtract the exponents from one another?

  6. #30
    Member snowguy13's Avatar
    Join Date
    Nov 2011
    Location
    In Hyrule enjoying a chat with Demise and Ganondorf
    Posts
    339
    My Mood
    Happy
    Thanks
    31
    Thanked 48 Times in 42 Posts

    Default Re: Splitting text into several components

    hehe thank you.

    You know, thats actually a really good idea! That way, the user can take the result and perform more calculations on it without having to copy and paste all the time. i like it! thanks for the suggestion
    You're welcome!

    Its amazing how quickly you forget things once you dont use them
    Hehe, yeah. I'm in Calculus BC right now, and we just touched on polynomial division again because of partial fraction decomposition. I hadn't used it for at least a year before then!

    but if i'm not mistaking, for division, can i not just divide the coefficients and subtract the exponents from one another?
    Yes, but remember that polynomial division depends on the LEADING (highest exponent) term only. Furthermore, you can only do polynomial division if the degree of the polynomial on top is equal to or greater than the degree of the polynomial on the bottom.

    x^3 + 2x - 3
    x - 3

    The above works because the top polynomial's degree (3 in x^3) is greater than the bottom polynomial's degree (1 in x). However the below will not work:

    x - 9
    x^2

    because x^2 has a higher degree than x - 9.

    For the entire process of the division, see this page, which illustrates the divisions really well.
    Use highlight tags to help others help you!

    [highlight=Java]Your prettily formatted code goes here[/highlight]

    Using these tags makes your code formatted, and helps everyone answer your questions more easily!




    Wanna hear something funny?

    Me too.

  7. #31
    Member clydefrog's Avatar
    Join Date
    Feb 2012
    Posts
    67
    Thanks
    15
    Thanked 2 Times in 2 Posts

    Default Re: Splitting text into several components

    Quote Originally Posted by snowguy13 View Post
    partial fraction decomposition.
    oh dear god! get it away from me!

    Quote Originally Posted by snowguy13 View Post
    Yes, but remember that polynomial division depends on the LEADING (highest exponent) term only. Furthermore, you can only do polynomial division if the degree of the polynomial on top is equal to or greater than the degree of the polynomial on the bottom.

    x^3 + 2x - 3
    x - 3

    The above works because the top polynomial's degree (3 in x^3) is greater than the bottom polynomial's degree (1 in x). However the below will not work:

    x - 9
    x^2

    because x^2 has a higher degree than x - 9.

    For the entire process of the division, see this page, which illustrates the divisions really well.
    hmmm, well this definitely made my life much more difficult. Here i was thinking i was on the verge of completing this project... lol

  8. #32
    Member snowguy13's Avatar
    Join Date
    Nov 2011
    Location
    In Hyrule enjoying a chat with Demise and Ganondorf
    Posts
    339
    My Mood
    Happy
    Thanks
    31
    Thanked 48 Times in 42 Posts

    Default Re: Splitting text into several components

    oh dear god! get it away from me!
    XD Is it really THAT bad? ;D

    hmmm, well this definitely made my life much more difficult. Here i was thinking i was on the verge of completing this project... lol
    Heehee, aren't polynomials fun?
    Use highlight tags to help others help you!

    [highlight=Java]Your prettily formatted code goes here[/highlight]

    Using these tags makes your code formatted, and helps everyone answer your questions more easily!




    Wanna hear something funny?

    Me too.

Page 2 of 2 FirstFirst 12

Similar Threads

  1. Splitting String
    By JuLiAnc in forum What's Wrong With My Code?
    Replies: 3
    Last Post: December 17th, 2011, 10:23 AM
  2. [SOLVED] Splitting String by Multiple Delimiters
    By relixus in forum What's Wrong With My Code?
    Replies: 0
    Last Post: February 4th, 2011, 08:54 PM
  3. Splitting an Array?
    By ThatGuy1234 in forum Java Theory & Questions
    Replies: 1
    Last Post: January 19th, 2011, 08:20 AM
  4. reading content of the text file, splitting it into strings
    By Dodo in forum File I/O & Other I/O Streams
    Replies: 7
    Last Post: January 6th, 2011, 07:57 PM
  5. Splitting File into Array
    By Scottj996 in forum File I/O & Other I/O Streams
    Replies: 4
    Last Post: March 3rd, 2010, 11:48 AM