How to make an iOS calculator, by just using a UITextField - iphone

I am looking to create an iOS calculator, just by using a UITextField. So for example; somebody may type in '6 - 3 x 2' in the UITextField then hit "Done" or "Go" etc. This would then calculate the answer and display it in a UIAlertView.
So firstly I believe that the UITextField text has to be split up into different sections so '6' '-' '3' '*' '2' would be the separated strings from the UITextField text input. How would I go about separating the text like mentioned above?
How can I then use this information to calculate the answer and to display it?

Use GCMathParser http://apptree.net/parser.htm
It takes an NSString as an input and evaluates it for you.
As Danh said, you can also use DDMathParser https://github.com/davedelong/DDMathParser
An Example(right from the docs)
NSString* mathstring = #"tan(dtor(45))";
double result = [mathstring evaluateMath]; // returns 0.999999999999...
So you simply send message evaluateMath to the NSString you want to parse. That's it)

You could also use NSPredicate as such:
NSPredicate * parsed = [NSPredicate predicateWithFormat:#"22/7.0 + (13*42) - 1024 = 0"];
NSExpression * left = [(NSComparisonPredicate *)parsed leftExpression];
NSNumber * result = [left expressionValueWithObject:nil context:nil];
NSLog(#"result: %#", result);
But I'm not sure about functions like tan and such. More info here.

Related

NSExpression Dividing Lower Number By Higher Number [duplicate]

I am making a calculator that logs input in a label named "inputLabel' and then outputs the answer in a different label named "outputLabel" (similar to a graphing calculator). Once the user is finished entering the expression, the expression is stored in an NSString object and then parsed with the NSPredicate class and evaluated with the NSExpression class. What I have works, but I have noticed for particular operations the answers are not correct. For example, if the user types in "25/2" the calculator returns 12, which is obviously incorrect. However, if the user types in "25/2.0" or "25.0/2" the calculator returns 12.5 which is what I want. It seems that the NSExpression method 'expressionValueWithObject' is interpreting the operands as integers instead of floats. If this is the case, is there a way that I change the 'expressionValueWithObject'method to interpret the operands as floats?
Brain.m
-(float)performCalculation: (NSString *)operation
{
NSPredicate *parsed = [NSPredicate predicateWithFormat:[operation stringByAppendingString:#"=1.0"]];
NSExpression *inputExpressionParsed = [(NSComparisonPredicate *)parsed leftExpression];
NSNumber *result = [inputExpressionParsed expressionValueWithObject:inputExpressionParsed context:nil];
return [result floatValue];
}
ViewController.m
- (IBAction)equalsPressed:(id)sender
{
//self.inputLabel.text = [self.inputLabel.text stringByAppendingString:#".0"];
NSString *inputExpression = self.inputLabel.text;
self.inputLabel.text = [self.inputLabel.text stringByAppendingString:#"="];
float result = [self.brain performCalculation:inputExpression];
self.outputLabel.text = [NSString stringWithFormat:#"%g", result];
}
No, NSExpression cannot do that. You could try to append ".0" to all integer numbers
in the string before evaluating it, but the better solution is probably to use a "proper"
math expression parser, for example
https://github.com/davedelong/DDMathParser
You could iterate through the expression tree replacing the expression with the integer value (expressionType == NSConstantExpression). It depends a little bit of the features of your calculator, whether it is worth or not.

How to Multiply Two textfield values Without converting the text into integer or Number

I have two text fields and user entered the values. I can get the values of textFields like below
NSString *number1 = firstTextField.text;
NSString *number2 = secondTextField.text;
I want to multiply number1 and number2 without converting them into integer or number.I am doing like below
NSExpression *expression = [NSExpression expressionWithFormat:[NSString stringWithFormat:#"%#*%#",number1,number2]];NSLog(#"Multiplication result is----%#",[expression expressionValueWithObject:nil context:nil]);
I don't know if it is correct or not. If it is not correct please give me the suggestions how it can be possible.
By using NSExpression is one way to Multiply/Add/Subtract two number strings without converting them into integer or number.
NSExpression *expression = [NSExpression expressionWithFormat:expressionFormat];
You are using here expressionFormat as [NSString stringWithFormat:#"%#*%#",number1,number2];.
If you want to add or subtract number1 and number2 then replace * with + or -. In this way you have to proceed.
If the question was in an interview.
The interviewers were probably expecting you to write a method to go through both arrays and multiply the characters (converting one by one to integers) or (also identifying the represented character to know the equivalent integer number).
Searching on google there are some examples in different languages.
JAVA
http://csjobinterview.wordpress.com/2012/04/05/string-multiplication/
string multiplication
C++
Multiplying two number arrays
It is a common question in interviews.
I simply used textfields... and used the values that the user input into those textfields... here is one calculation example that has worked for me... in this example the user is trying to find the volume of beachstone they would need to order... the formula is pretty straight forward. Make sure you use the math brackets () to distinguish order of operations...
-(IBAction)calculate_beachstone:(id)sender {
float floatanswer =
([area1.text floatValue])+([area2.text floatValue])+([area3.text floatValue])+([area4.text floatValue])+([area5.text floatValue])+([area6.text floatValue])+([area7.text floatValue])+([area8.text floatValue])+([area9.text floatValue])+([area10.text floatValue]))
*([beachstone_depth.text floatValue])/12)/27);
NSString *stringRectResult=[[NSString alloc]
initWithFormat:#"%.1f",floatanswer];
answer_beachstone.text=stringRectResult;
}
I am adding the text found in the textfield (which user can only use numbers for input - custom keyboard)... in this example I have up to 10 fields which can be added together... then I use the * (multiply) to apply a depth in this example, and convert it back to a text string so I can display the result somewhere else...
In fact, if you write this part answer_beachstone to NSUserDefaults, you can use the result anywhere in different controllers, by calling it back.
If you're interested, here is how I did that...
-(IBAction)save_answer_beachstone:(id)sender {
save_answer_beachstone = [[NSString alloc] initWithString:answer_beachstone.text];
[answer_beachstone setText:save_answer_beachstone];
NSUserDefaults *save = [NSUserDefaults standardUserDefaults];
[save setObject:save_answer_beachstone forKey:#"save_answer_beachstone"];
}
Then I can use the resulting "answer" in any controller inside viewDidLoad...
[answer_beachstone setText:[[NSUserDefaults standardUserDefaults] objectForKey:#"save_answer_beachstone"]];
I know the question was asked 4 years ago, but this formula syntax works for me in a number of ways, in various apps...
You can't multiply two strings. It's not possible.
For this you have to convert it into Integer or int using NSNumber or using:
[secondTextField.text intValue].
NSInteger number = [firstTextField.text integerValue]*[secondTextField.text integerValue];

How to convert from text to number integer?

i have input only number from text field and i want to change it to integer. what code should i write in?
just say text field say for 10 and i want to take that 10 = x, x = integer. so if i use it for mathematic process a = x + 1 and display say 11. is there any chance? i hope you understand what i mean. thank you. i think both of you will answer this simple question but i not because im beginner. im a 3d design graphic switch 180 degree become xcode programming. BTW ive tried this before but it cant.
NSInteger number = [[txtBtn text] integerValue];
Edited :
i've got this error, local declaration of 'number' hides instance variable, pointed to number at result = (number * 2) - 1; and i put the code like this.
NSInteger number = [[txtBtn text] intValue];
result = (number * 2) - 1;
i dont know whats wrong.
Are you sure it's a TextField and not a UIButton you are trying to get the integerValue from?
[txtBtn text]
I created a TextField and a UIButton, and implemented your code:
- (IBAction)btnClicked:(id)sender {
NSInteger i = [[inputField text] intValue];
int result = (i*2)-1;
NSLog(#"%i", result);
}
the output results is correct.
ex: type 5, output in console is 9.

Compare, Getting string from a label

I'm making a word game and I've finally come up to one of the most important parts of my game, the compare part.
I got this label which will be invisible when it launches with the word that has to be guessed displaying in it with a random word generator. For example the word is: GARAGE
Now, for my game I have to compare the word with the input now I've already done this with the entire word with NSString but I want it to compare every letter. I want to be able to show that if the input has G as the first letter aswell, like garage. I want it to do something.
I want to know if this is possible and which methods you would use. I was thinking about making 6 strings since all my random words have 6 letters, and then break the word to 6 strings and the input aswell and then compare strings?
Hope someone has some usefull tips or example code thanks
So, assuming your string to be guessed...
NSString *stringToGuess = #"GARAGE";
and you were checking to see if it started with "GA"
NSString *myString = #"GA";
you would check it with hasPrefix:
if ([stringToGuess hasPrefix:myString]) {
// <stringToGuess> starts with <myString>
}
The documentation for NSString describes lots of neat methods for just about anything string related.
hasPrefix will let you tell if one string begins with another string. There's also characterAtIndex. You could use that to get one character from each string and compare it to the other.
You could write a method that would take an integer index and compare the two strings at that index:
- (BOOL) compareStringOne: (NSString *) stringOne
toStringTwo: (NSString *) stringTwo
atIndex: (NSUInteger) index;
{
if ([stringOne length] < index+1 || [stringTwo length] < index+1)
return FALSE;
return [stringOne characterAtIndex: index] == [stringTwo characterAtIndex: index];
}

objective-c code to right pad a NSString?

Can someone give a code example of how to right pad an NSString in objective-c please?
For example want these strings:
Testing 123 Long String
Hello World
Short
if right padded to a column width of say 12: and then a sting "XXX" is added to the end of each, it would give:
Testing 123 xxx
Hello World xxx
Short xxx
That is a 2nd column would like up.
Adam is on the right track, but not quite there. You do want to use +stringWithFormat:, but not quite as he suggested. If you want to pad "someString" to (say) a minimum of 12 characters, you'd use a width specifier as part of the format. Since you want the result to be left-justified, you need to precede the width specifier with a minus:
NSString *padded = [NSString stringWithFormat:#"%-12#", someString];
Or, if you wanted the result to be exactly 12 characters, you can use both minimum and maximum width specifiers:
NSString *padded = [NSString stringWithFormat:#"%-12.12#", someString];
2nd column of what would line up?
Given that you are on iOS, using HTML or a table view would be far more straightforward than trying to line up characters with spaces. Beyond being programmatically more elegant, it will look better, be more resilient to input data changes over time, and render a user experience more in line with expectations for the platform.
If you really want to use spaces, then you are going to have to limit your UI to a monospace font (ugly for readability purposes outside of specific contexts, like source code) and international characters are going to be a bit of a pain.
From there, it would be a matter of getting the string length (keeping in mind that "length" does not necessarily mean "# of characters" in some languages), doing a bit of math, using substringWithRange: and appending spaces to the result.
Unfortunately, Objective-C does not allow format specifiers for %#. A work-around for padding is the following:
NSString *padded = [NSString stringWithFormat:#"%#%*s", someString, 12-someString.length, ""];
which will pad the string to the right with spaces up to a field length of 12 characters.
%-# does not work, but %-s works
NSString *x = [NSString stringWithFormat:#"%-3#", #"a" ];
NSString *y = [NSString stringWithFormat:#"%-3#", #"abcd" ];
NSString *z = [NSString stringWithFormat:#"%-3# %#", #"a", #"bc" ];
NSString *zz = [NSString stringWithFormat:#"%-3s %#", "a", #"bc" ];
NSLog(#"[%#][%#][%#][%#].......", x,y,z,zz);
output:
[a][abcd][a bc][a bc].......
Try below. its working for me.
NSString *someString = #"1234";
NSString *padded = [someString stringByPaddingToLength: 16 withString: #"x" startingAtIndex:0];
NSLog(#"%#", someString);
NSLog(#"%#", padded);
First up, you're doing this a bad way. Please use separate labels for your two columns and then you will also be able to use proportional fonts. The way you're going about it you should be looking for an iPhone curses library.
If you really have to do it this way just use stringWithFormat:, like:
NSString *secondColumnString = #"xxx";
NSString *spacedOutString = [NSString stringWithFormat:#"testingColOne %#", secondColumnString];
NSString *spacedOutString = [NSString stringWithFormat:#"testingAgain %#", secondColumnString];