Store user input, calculate and show in the end - iphone

I'm writing a program that calculates input a user gives, simple numbers. 2, 4, 7, 10, 12 and so on.
I need the program to store these inputs (that come in from different textfields) somehow. Use them in an internal equation, and then show them to the user in the end.
How do I do this? Please take note that I'm rather new at programming.
I know how to define textFields, do a calculate IBAction , and I've tried creating a -(void)calculate, which works, but only on 1 input. When I execute the following code, with input from 6 textfields instead of 3 (which are used in the first line (resultOne)) it gives me the wrong numbers. But I still need a better way of doing this.
-(void) calculate{
weightOne = [v1Text.text floatValue]/2;
weightTwo = [v2Text.text floatValue]/2;
resultOne = [m1Text.text floatValue] * weightOne + [s1Text.text floatValue] * weightOne;
resultTwo = [m2Text.text floatValue] * weightTwo + [s2Text.text floatValue] * weightTwo;
_resultTotal = (resultOne + resultTwo) / (weightOne + weightTwo);
NSString *resultString = [[NSString alloc]
initWithFormat: #"%.2f", resultOne];
resultLabel.text = resultString;
[resultString release];
}
I know that the above code outputs resultOne, but this is just for my own testing, to know that the equation works. But I would really like to start all fresh, since I don't believe that the above code is suitable for what I need it to do.
Please bare in mind that I am a beginner, and explain a little more, than just showing me some code.
I look forward to any help you can give me.
EDIT! - BELOW IS NEW CODE
-(IBAction) calculate:(id)sender {
weightOne = 1;
weightTwo = 0.75;
weightThree = 0.50;
mOne = [m1Text.text floatValue];
mTwo = [m2Text.text floatValue];
sOne = [s1Text.text floatValue];
sTwo = [s2Text.text floatValue];
resultOne = (mOne*weightOne) + (sOne*weightOne);
resultTwo = (mTwo*weightTwo) + (sTwo*weightTwo);
_resultTotal = (resultOne + resultTwo) / (weightOne*2 + weightTwo*2);
NSString *resultString = [[NSString alloc]
initWithFormat: #"Gennemsnit %.2f", _resultTotal];
resultLabel.text = resultString;
}
I decided to change my code, in order to easily calculate the input. Now I have another question.
Is it possible to save this equation in some way, so I can reuse it as many times as I want, without having to type the code again and again and again.

First of all calculate can be your IBAction method which will be called when tapped on the button. So change the prototype to -(IBAction)calculate:(id)sender.
Next if you are able to have outlets for the text fields, then there is no harm and absoulutely no difficulty in getting the text entered in them.
Few things you can do are to validate for correct input. [v1Text.text floatValue] is right expression for getting the numbers from text. You can also have a look at intvalue.
Now once you have done your computation, you can use the reference to the label/textfield where you want to display the result.
You can change that label exactly the way you did in your code.

Related

Weird behavior of for loop with multiple sprites in Sprite Kit

I am spawning 12 sprites to place in a game. Each sprite needs to have an original name. I am doing this by using a for loop. I have split the loop up to show you what is happening. So for the first couple of charges:
for (int i = -4; i <= 0; i++)
{
NSLog(#"i = %i", i);
[self spawnChargesWithNumber:i];
}
The NSLog tells me that i is -4, -3, -2, -1, 0. As it should. This calls the method spawnChargesWithNumber:i which looks like this:
- (void)spawnChargesWithNumber:(int)number
{
NSLog(#"number is %i", number);
_chargedBall = [[ChargedBall alloc] initWithImageNamed:[NSString stringWithFormat:#"ChargedBall%i", number]];
//code to make a random position
_chargedBall.position = CGPointMake(actualX, random);
_chargedBall.name = [NSString stringWithFormat:#"chargeNumber%i", number];
_chargedBall.zPosition = 15;
_chargedBall.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:13.0f];
_chargedBall.physicsBody.dynamic = YES;
_chargedBall.physicsBody.affectedByGravity = NO;
_chargedBall.physicsBody.mass = 0.1;
_chargedBall.velocity = CGPointMake(actualVelocityX, 0.0);
_chargedBall.physicsBody.categoryBitMask = chargeCategory;
_chargedBall.physicsBody.contactTestBitMask = playerCategory;
_chargedBall.physicsBody.collisionBitMask = playerCategory | selfCategory;
[self.map addChild:_chargedBall];
NSLog(#"You made charge with name %#", _chargedBall.name);
if (!_enemies) {
_enemies = [[NSMutableArray alloc] init];
}
[_enemies addObject:_chargedBall];
NSLog(#"you added %# to the array", _chargedBall.name);
}
I have an object called ChargedBall. The NSLog first tells me the number, which corresponds to i from above. Then it tells me I made charge (chargeNumberi) where it follows the same pattern. Then I add that chargedBall to an array. During the game if I collide with any of these, my NSLog from didBeginContact method tells me that I have contacted the proper charge. All is working as planned.
Since I actually have 12 charges and not 5 I have another for loop to show you. It is basically the same taking off where the other ended:
for (int i = 1; i <= 7; i++)
{
NSLog(#"i = %i", i);
[self spawnChargesWithNumber:i];
}
I did originally have these together, but I wanted to show you what was happening. After the call to spawnChargesWithNumber:i I get the rest of the charges. However, they are reversed! I don't get it. The NSLog still tells me the i, number, you created chargeNumberi, and added it to the array. I even NSLog the name of the image and it still corresponds. But chargeNumber7 shows picture 1, chargeNumber6shows picture 2, chargeNumber 5 shows picture 3, four is fine because there is an odd number of sprites to make, chargeNumber3 show picture 5, chargeNumber2 shows picture6 and chargeNumber 7 shows picture 1. So the entire thing is flipped. I have checked the pictures and they are all correct. This even happened when I had the for loop as just one loop, the positive charges were switched, but not zero to negative 4. Does anyone know why this would happen? I NSLog everything I could think of, I even changed the picture names, but nothing worked. If you need some more code from other places I can post, I am just so confused right now!
The problem has been solved. I really thought that I had programmed my for loop incorrectly. However, with the help of fuzzygoat and prototypical, I hardcoded everything, and used the debugger to find that all was as I intended. Therefore, prototypical suggested cleaning the derived data, as I had changed the image names after they had been imported to Xcode. I thought that cleaning the product did the same as deleting the derived data, but perhaps not. So thanks to everyone that looked and thanks to all that helped. You filled my brain with knowledge once again!

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.

Adding and subtracting numbers from UILabels - Xcode

I am trying to make an analysis app which calculates percentages of winners etc. Please see the attached picture:
So when there is a smash winner, the user clicks the UIStepper and it should 'add 1' onto the smash winners total and number of rallies, and also update the percentage which is the winner divided by the number of rallies. If there was a drop winner after, then drop winner total gets updated along with the number of rallies and the smash and drop winner percentages.
Hopefully I have explained it well enough for you guys to understand :/
I am using this bit of code to update a generic winner:
- (IBAction)netChanged:(id)sender {
self.netLabel.text = [NSString stringWithFormat:#"%d",
[[NSNumber numberWithDouble:[(UIStepper *)sender value]] intValue]];
float net = [self.netLabel.text floatValue];
float rally = [self.rallyLabel.text floatValue];
float netPercentage = (rally == 0.0) ? 0 : net / rally * 100;
self.netPercentageLabel.text = [NSString stringWithFormat:#"%.2f%%", netPercentage];
}
My question is, what do I need to do in terms of code to update other percentages and rallies played when there is a winner?
Thanks.
You should be saving that data somewhere else, and not in the text property of a UILabel. Update the values, and then update the labels to reflect the updated values.
I highly recommend re-reading the documentation on Model-View-Controller.

Objective-C math function

I want square the number.using pow(). So,pow(3,2) should be 9.But it showing 8 in my iOS Calculator application.here is my code:
else if([opertaion isEqualToString:#"sqrt"])
{
result=pow([self popOperand],[self popOperand]);
}
method
-(double)popOperand
{
NSNumber *operandObject = [self.operandStack lastObject];
if(operandObject)[self.operandStack removeLastObject];
return [operandObject doubleValue];
}
One thing,I'm newibe on iOS programming.
Thanks in advance.
I would imagine you're just thinking about your operands backwards. 2^3 == 8.
result=pow([self popOperand],[self popOperand]);
This statement is being executed from left to right ... so its calculating pow(2,3)
You can use
double x = [self operand];
double y = [self operand];
result = pow(x,y)
It seems like you are trying to pop the first number then the last. So, getPower(3,2) would come up as 2^3 instead. I would look at your stack and make sure that you are arranging them correctly.