Results 1 to 13 of 13

Thread: how to convert a string with operands to an integer

  1. #1

    Thread Starter
    Frenzied Member System_Error's Avatar
    Join Date
    Apr 2004
    Posts
    1,111

    Resolved how to convert a string with operands to an integer

    I guess it's obvious I've been working on a Calculator. I got stumped pretty soon into the project. How can I get the String entered and then convert it to an int when it has operands? I've tried so many different ways:

    String s = textfield.getText();// were the text might be 1+1
    int i = integer.parseInt(s);

    I thought if there was no spaces between the 1 and + it would work...

    The only sensible way I can think of is using a string tokenizer. But how would you append the operand to the numbers?



    <Moderator added green checkmark in the first thread>
    Last edited by NoteMe; Feb 17th, 2005 at 07:21 AM.

  2. #2
    Dazed Member
    Join Date
    Oct 1999
    Location
    Ridgefield Park, NJ
    Posts
    3,418

    Re: how to convert a string with operands to an integer

    Yeah there is no way that
    Code:
    String s = textfield.getText();// were the text might be 1+1
    int i = integer.parseInt(s);
    would work. The code would throw a NumberFormatException. Also you have a typo on the class type of the static method call.

  3. #3
    Dazed Member
    Join Date
    Oct 1999
    Location
    Ridgefield Park, NJ
    Posts
    3,418

    Re: how to convert a string with operands to an integer

    The following works.
    Code:
     String s = "1 + 1";
     StringTokenizer st = new StringTokenizer(s,"+");
     int result = Integer.parseInt(st.nextToken().trim()) +               
     Integer.parseInt(st.nextToken().trim());
     System.out.println(result);

  4. #4

    Thread Starter
    Frenzied Member System_Error's Avatar
    Join Date
    Apr 2004
    Posts
    1,111

    Re: how to convert a string with operands to an integer

    Now when you do this:

    Code:
    StringTokenizer st = new StringTokenizer(s,"+");

    Is the "+" a delimeter? If it is, could I have multiple delimiters?

  5. #5
    Dazed Member
    Join Date
    Oct 1999
    Location
    Ridgefield Park, NJ
    Posts
    3,418

    Re: how to convert a string with operands to an integer

    To be honest i am not quite sure. Everytime i used a StringTokenizer it was only with one delimiter. You would have to check the documentation over at sun.

    Even if it is possible, i am curious about how you plan on being able to determine which operator to apply. If you could parse using multiple delimiters and return each delimeter as the string is parsed then i guess you could just use a switch statement to test if the returned delimiter is a match for an operator. Then take it from there.

  6. #6

    Thread Starter
    Frenzied Member System_Error's Avatar
    Join Date
    Apr 2004
    Posts
    1,111

    Re: how to convert a string with operands to an integer

    I'll show you what I have right now. Right now, I think the way I'm doing it, is kind of nubish, messy, dumb, or whatever you want to call it. I like how you showed me, but as you said, how to tell which operator is being used might be trivial. The only thing I'm unsure about at this point, is how can I use more than one operand?

    like right now, alll I can do is simple two operand equations like this:

    1+2


    I want to be able to do this crap right here:

    1+2-3*4

  7. #7

    Thread Starter
    Frenzied Member System_Error's Avatar
    Join Date
    Apr 2004
    Posts
    1,111

    Re: how to convert a string with operands to an integer

    Forgot my code:

    Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class Calculator extends JFrame implements ActionListener
    {
    	JButton[] btnNums;
    	JButton btnBack;
    	JButton btnClear;
    	JButton btnCalculate;
    	String[] strNames;
    	String strOperand1;
    	String strOperand2;
    	Boolean wasClicked;
    	String answer;
    	double dd;
    
    	final String STR_MULTIPLY = "MULTIPLY";
    	final String STR_DIVIDE = "DIVIDE";
    	final String STR_ADD = "ADD";
    	final String STR_SUBTRACT = "SUBTRACT";
    
    	String whichOperator;
    	
    	
    	JTextField txtDisplay;
    	
    	public Calculator()
    	{
    		Container content = getContentPane();
    		setSize(210,250);
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		
    		
    		/*  construct a JPanel and the textfield that 
    		 *  will show the inputed values and outputed 
    		 *  results
    		 */
    		JPanel jpDisplay = new JPanel();
    		jpDisplay.setLayout(new BorderLayout());
    		txtDisplay = new JTextField(15);
    		txtDisplay.setHorizontalAlignment(JTextField.RIGHT);
    		jpDisplay.add(txtDisplay);
    		
    		/*  contstruct a JPanel that will contain a back
    		 *  button and a clear button.
    		 */
    		JPanel jpRow2 = new JPanel();
    		btnBack = new JButton("Backspace");
    		btnBack.addActionListener(this);
    		btnClear = new JButton("Clear");
    		btnClear.addActionListener(this);
    		btnClear.addActionListener(this);
    		jpRow2.add(btnBack);
    		jpRow2.add(btnClear);
    		
    		/*  construct a string array with all the names of the
    		 *  buttons, then in a for loop create the new buttons
    		 *  and add their name and an actionListener to them.
    		 */
    		String[] strNames = {"7","8", "9","/", "4", "5", "6","*", "1",
    					   "2", "3","+", "0", "+/-", ".", "-"};
    		btnNums = new JButton[16];
    		JPanel jpButtons = new JPanel();
    		jpButtons.setLayout(new GridLayout(4,4));
    		
    		  for (int i = 0; i < 16; i++)
    		  {
    			  btnNums[i] = new JButton(strNames[i]);
    			  btnNums[i].addActionListener(this);
    			  jpButtons.add(btnNums[i]);
    		  }
    		  
    		  /*  construct the final JPanel and add a 
    		   *  calculate button to it.
    		   */
    		  JPanel jpLastRow = new JPanel();
    		  btnCalculate = new JButton("Calculate");
    		  btnCalculate.addActionListener(this);
    		  jpLastRow.add(btnCalculate);
    		  
    		  
    		  //make wasClicked have a default value of false
    		  wasClicked = false;
    		  
    		  /*  set the contentPane and create the layout
    		   *  add the panels to the container
    		   */
    		  setContentPane(content);
    		  setLayout(new FlowLayout());
    		  setResizable(false);
    		  content.add(jpDisplay, BorderLayout.NORTH);
    		  content.add(jpRow2);
    		  content.add(jpButtons);
    		  content.add(jpLastRow);
    		  setTitle("Mini Calculator");
    		  setVisible(true); 
    		  
    	}
    	
     
    	public void actionPerformed(ActionEvent ae)
    	{
    		// if any of the array buttons was clicked append the button's text
    		for (int i =0; i < 16; i++)
    		{
    			if (ae.getSource() == btnNums[i])
    			{
    				txtDisplay.setText(txtDisplay.getText()
    						+ btnNums[i].getText());
    				
    			}
    		}
    		
    		
    		/*  if the backspace button was clicked, then create substring
    		 *  to to subtract the farthest character to the right
    		 */
    		if (ae.getSource() == btnBack)
    		{
    			String strAll = txtDisplay.getText();
    			int length = strAll.length();
    			String strShowThis = strAll.substring(0,length - 1);
    			txtDisplay.setText(strShowThis);
    		}
    			else if (ae.getSource() == btnClear)
    			{
    				txtDisplay.setText(null);
    			}	
    			else if (ae.getSource() == btnCalculate)
    			{
    				String strText = txtDisplay.getText();
    				try 
    				{
    					int equation = Integer.parseInt(strText);
    					txtDisplay.setText("" + equation);
    				}
    				catch (ArithmeticException aee)
    				{
    					aee.printStackTrace();
    		 	 }
    			
    			}
    			
    			/*  start the process of finding which operator was 
    			 *  chosen, and the process the equation in a new 
    			 *  method
    			 */
    			 
    			 if (ae.getSource() == btnNums[3])
    			 {
    				 processDivide();
    			 }
    			 else if (ae.getSource() == btnNums[7])
    			 {
    				 processMultiply();
    			 }
    			 else if (ae.getSource() == btnNums[11])
    			 {
    				 processAdd();
    			 }
    			 else if (ae.getSource() == btnNums[13])
    			 {
    				processPosOrNeg();
    			 }
    			 else if (ae.getSource() == btnNums[15])
    			 {
    				 processSubtract();
    			 }
    			 else
    			 {
    			 }
    
    		// and finally process the calculation
    		if (ae.getSource() == btnCalculate)
    		{
    			processCalc();
    		}
    		else
    		{
    		}
    	}
    	
    	public void processDivide()
    	{
    		whichOperator = STR_DIVIDE;
    		strOperand1 = txtDisplay.getText();
    		int x = strOperand1.length();
    		String s = strOperand1.substring(0, x - 1);
    		dd = Double.parseDouble(s);
    		txtDisplay.setText(null);
    	}
    	public void processMultiply()
    	{
    		whichOperator = STR_MULTIPLY;
    		strOperand1 = txtDisplay.getText();
    		int x = strOperand1.length();
    		String s = strOperand1.substring(0, x - 1);
    		dd = Double.parseDouble(s);
    		txtDisplay.setText(null);
    	}
    	public void processAdd()
    	{
    		whichOperator = STR_ADD;
    		strOperand1 = txtDisplay.getText();
    		int x = strOperand1.length();
    		System.out.println("variable x = " + x);
    		String s = strOperand1.substring(0, x - 1);
    		System.out.println("variable s = " + s);
    		dd = Double.parseDouble(s);
    		System.out.println("variable d = " + dd);
    		txtDisplay.setText(null);
    	}
    	public void processPosOrNeg()
    	{
    	}
    	public void processSubtract()
    	{
    		whichOperator = STR_SUBTRACT;
    		strOperand1 = txtDisplay.getText();
    		int x = strOperand1.length();
    		String s = strOperand1.substring(0, x - 1);
    		dd = Double.parseDouble(s);
    		txtDisplay.setText(null);
    	}
    
    	public void processCalc()
    	{
    		strOperand2 = txtDisplay.getText();
    		int x = strOperand2.length();
    		String s = strOperand2.substring(0, x);
    		double d = Double.parseDouble(s);
    		
    		if (whichOperator == STR_SUBTRACT)
    		{
    			double a = dd - d;
    			txtDisplay.setText(dd + "-" + d + " = " + a);
    		}
    		else if (whichOperator == STR_ADD)
    		{
    			double a = dd + d;
    			txtDisplay.setText(dd + "+" + d + " = " + a);
    		}
    		else if (whichOperator == STR_MULTIPLY)
    		{
    				double a = dd * d;
    			txtDisplay.setText(dd + "*" + d + " = " + a);
    		}
    		else if (whichOperator == STR_DIVIDE)
    		{
    				double a = dd / d;
    			txtDisplay.setText(dd + "/" + d + " = " + a);
    		}
    		else 
    		{
    		}
    	
    	}
    	
    	public static void main(String[] args)
    	{
    		Calculator calc = new Calculator();
    	}
    }

  8. #8
    Dazed Member
    Join Date
    Oct 1999
    Location
    Ridgefield Park, NJ
    Posts
    3,418

    Re: how to convert a string with operands to an integer

    You could do the following. Get the String representation of the text from the display(JTextField) using the getText() method. Convert the String over to a char[] then take it from there.

    Here is a small hack. I haven't compiled or ran this so i don't know if my indexing is on point but this gives you a general idea. When you get a chance see if this compiles and the output is what should be expected.
    Code:
    public class Calculator{
      public static void main(String[] args){
      String s = "6*2+5";
      char[] data = s.toCharArray();
      int i = 0;
       
      if(Character.isDigit(data[0])){
       i = Character.getNumericValue(data[0]); 
      }
    
      for(int index = 1; index < data.length; ++index){
       if(!Character.isDigit(data[index])){
         if((data[index] == '*') && (Character.isDigit(data[index + 1]))){
          i = i * Character.getNumericValue(data[index + 1]); 
         }
         if((data[index] == '+') && (Character.isDigit(data[index + 1]))){
           i = i + Character.getNumericValue(data[index + 1]); 
         }
        }
       }
       System.out.println(i);
      }

  9. #9

    Thread Starter
    Frenzied Member System_Error's Avatar
    Join Date
    Apr 2004
    Posts
    1,111

    Re: how to convert a string with operands to an integer

    YEP! I got 17 when I compiled! So this method works. I'll have to take a look at doing this. I REALLY like how you did that. right now I can't because I have a project due this week and I haven't worked on it, and when I started, my compiler feels like being gay.

  10. #10
    Dazed Member
    Join Date
    Oct 1999
    Location
    Ridgefield Park, NJ
    Posts
    3,418

    Re: how to convert a string with operands to an integer

    When i was laying in bed last night i thought of this. The code will only work with single digits. If the String contains "100*2" Then toCharArray(); would chop up the String as '1','0','0','*','2'. Pretty much not what we want.

  11. #11

    Thread Starter
    Frenzied Member System_Error's Avatar
    Join Date
    Apr 2004
    Posts
    1,111

    Re: how to convert a string with operands to an integer

    Well that sucks. Glad you caught it before I started; I might have killed myself over trying to figure out what's wrong. I wonder if I can use what I have right now, except when the user goes on to use a third operand, calculate what they have already, and then process the next one. Of course, this will defeat order of operations or PEMDAS;

  12. #12

    Thread Starter
    Frenzied Member System_Error's Avatar
    Join Date
    Apr 2004
    Posts
    1,111

    Re: how to convert a string with operands to an integer

    like this:

    user clicks 1
    user clicks +
    user clicks 2
    user clicks - // calculate 1+2 = 2
    user clicks 1
    user clicks calculate button // then get the previous calculation and do the next operation

    I think this is a stupid idea, but I'll wait to see what you think.

  13. #13

    Thread Starter
    Frenzied Member System_Error's Avatar
    Join Date
    Apr 2004
    Posts
    1,111

    Re: how to convert a string with operands to an integer

    Ok, I fixed it. It was simple, all I had to do, was change the calc() method. Instead of having it show the full equation I just did the answer;

    Code:
    	public void processCalc()
    	{
    		strOperand2 = txtDisplay.getText();
    		int x = strOperand2.length();
    		String s = strOperand2.substring(0, x);
    		double d = Double.parseDouble(s);
    		
    		if (whichOperator == STR_SUBTRACT)
    		{
    			double a = dd - d;
    			txtDisplay.setText("" + a);
    		}
    		else if (whichOperator == STR_ADD)
    		{
    			double a = dd + d;
    			txtDisplay.setText("" + a);
    		}
    		else if (whichOperator == STR_MULTIPLY)
    		{
    				double a = dd * d;
    			txtDisplay.setText("" + a);
    		}
    		else if (whichOperator == STR_DIVIDE)
    		{
    				double a = dd / d;
    			txtDisplay.setText(" " + a);
    		}
    		else 
    		{
    		}
    	
    	}

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width