Use of Undeclared Identifier 'calculateAge' [closed] - objective-c

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am new to objective and just trying to understand simple concepts.
I have read Objective C for dummies and Cocoa Programming for Mac OSX (most of it).
I tried to make a simple small program on my own and realized I know very little.
I keep getting the "Use of Undeclared Identifier "calculateAge', did you mean 'Calculate' " error.
Can anyone please tell me what's wrong with my code below and why?
Thanks a bunch in advance.
#import <Foundation/Foundation.h>
#interface Calculate : NSObject
{
int myYear;
int nowYear;
}
- (int) calculateAge:(int)birthYear:(int)nowYear;
#end
#implementation Calculate
- (int) calculateAge:(int)birthYear:(int)nowYear// need myYear
{
NSLog(#"The birthYear is: %i\n", birthYear);
int myAge = nowYear - birthYear;
//NSLog(#"The nowYear is: %i\n", nowYear);
NSLog(#"The age is: %i\n", myAge);
return myAge;
}
int main(int argc, const char * argv[])
{
#autoreleasepool {
NSLog(#"Hello, World!");
int myY = 1963;
int nowY = 2012;
int myYear = 1963;
int nowYear = 2012;
//int myAge = calculateAge:(int) birthYear: (int) nowYear;
int myAge = calculateAge:(int) myY: (int) nowY;
NSLog(#"The nowYear is: %i\n", nowYear);
NSLog(#"The age is: %i\n", myAge);
}
return 0;
}
#end

You seem to be conflating the method name with the parameter list. A proper signature would look something like this:
- (int)calculateAgeFromBirthYear:(int)birthYear currentYear:(int)currentYear
This could then be implemented like this:
- (int)calculateAgeFromBirthYear:(int)birthYear currentYear:(int)currentYear
{
NSLog(#"The birthYear is: %i\n", birthYear);
int myAge = currentYear - birthYear;
//NSLog(#"The nowYear is: %i\n", currentYear);
NSLog(#"The age is: %i\n", myAge);
return myAge;
}
This could then be called like this:
Calculate *calculator = [[Calculate alloc] init];
int myAge = [calculator calculateAgeFromBirthYear:myY currentYear:nowY];
Don't implement main inside a class implementation; it belongs outside in the global namespace, preferably in its own file.

There is no need to declare the instance variables in the interface.
The last #end needs to be before the main function, it is not part of the class, it used the class.
The Calculate class needs to be instantiated and the call needs to be made to the instantiated class.
The calculateAge... method should be renamed to indicate each argument.
Variables should be given full names, abreviations generall end up making things less clear.
Here is an example:
#interface Calculate : NSObject
- (int) calculateAgeWithBirthYear:(int)birthYear nowYear:(int)nowYear;
#end
#implementation Calculate
- (int) calculateAgeWithBirthYear:(int)birthYear nowYear:(int)nowYear// need myYear
{
NSLog(#"The birthYear is: %i\n", birthYear);
int myAge = nowYear - birthYear;
NSLog(#"The age is: %i\n", myAge);
return myAge;
}
#end
int main(int argc, const char * argv[])
{
#autoreleasepool {
NSLog(#"Hello, World!");
int myBirthYear = 1963;
int nowYear = 2012;
Calculate *calculator = [[Calculate alloc] init];
int myAge = [calculator calculateAgeWithBirthYear:myBirthYear nowYear:nowYear];
NSLog(#"The nowYear is: %i\n", nowYear);
NSLog(#"The age is: %i\n", myAge);
}
return 0;
}
NSLog output:
Hello, World!
The birthYear is: 1963
The age is: 49
The nowYear is: 2012
The age is: 49
Using instance variables created by `#property~ statements:
#interface Calculate : NSObject
#property int myYear;
#property int nowYear;
- (int) calculateAge;
#end
#implementation Calculate
- (int) calculateAge // need myYear
{
NSLog(#"The birthYear is: %i\n", self.myYear);
int myAge = self.nowYear - self.myYear;
NSLog(#"The age is: %i\n", myAge);
return myAge;
}
#end
int main(int argc, const char * argv[])
{
#autoreleasepool {
NSLog(#"Hello, World!");
Calculate *calculator = [[Calculate alloc] init];
calculator.myYear = 1963;
calculator.nowYear = 2012;
int myAge = [calculator calculateAge];
NSLog(#"The nowYear is: %i\n", calculator.nowYear);
NSLog(#"The age is: %i\n", myAge);
}
return 0;
}

Related

Objective-C Struct problems

I have a student structure that provides the following code:
#import <Foundation/Foundation.h>
#import "Grades.m"
#import <stdio.h>
struct Student
{
NSString *myName;
struct Grades *myGrades;
};
void setName(struct Student *s, NSString *name);
void ssetGrades(struct Student *s, NSString *gradeList);
void setName(struct Student *s, NSString *name)
{
s->myName = name;
}
void ssetGrades(struct Student *s, NSString *gradeList)
{
printf("\n\nWorking\n\n");
setGrades(s->myGrades, gradeList);
printf("\n\nWorking");
}
I have a grades structure that provides the following:
#import <stdio.h>
#import <Foundation/Foundation.h>
#define null NULL
struct Grades
{
double sgrades[100];
int length;
};
void setGrades(struct Grades *grades, NSString *gradeList);
void setGrade(int spot, double grade, struct Grades *grades);
void setGrades(struct Grades *grades, NSString *gradeList)
{
NSString *a = [gradeList substringToIndex:1];
NSString *b = [gradeList substringWithRange:NSMakeRange(3, 19)];
int ln = [a integerValue];
grades->length = ln;
double grade;
int x = 1;
int prev = 1;
int y;
int z = 0;
for(y=0;y<ln;y++)
{
while(x < [b length] && [b characterAtIndex:x] != ' ')
{
z++;
x++;
}
NSString *sub = [b substringWithRange:NSMakeRange(prev, z)];
grade = [sub doubleValue];
printf("%d %d %d %lf\n", y, prev, z, grade);
prev += z+1;
x++;
z=0;
setGrade(y, grade, grades);
}
}
void setGrade(int spot, double grade, struct Grades *grades)
{
grades->sgrades[spot] = grade;
}
And finally, I have a main function with the following:
#import <Foundation/Foundation.h>
#import "Grades.m"
#import "Student.m"
#import <stdio.h>
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
struct Grades test;
setGrades(&test, #"5 - 90 85 95.5 77.5 88");
toString(&test);
printf("\nsum = %lf", getSum(&test));
printf("\nnum grades = %d", getNumGrades(&test));
printf("\nlow grade = %lf", getLowGrade(&test));
printf("\nhigh grade = %lf", getHighGrade(&test));
struct Student stu;
setName(&stu, #"Billy Bob");
ssetGrades(&stu, #"5 - 90 85 95.5 77.5 88");
[pool release];
return 0;
}
Now whenever I get to the ssetGrades (&stu, #"5 - 90 85 95.5 77.5 88") line in the main, it freezes up and says that the program has stopped working. Any guesses why and if so, how can I fix this error?
NOTE: This is all done in Notepad++ on Windows 7
Your primary issue is your definition of your Student structure. Change the Grades reference so it isn't a pointer:
struct Student
{
NSString *myName;
struct Grades myGrades;
};
The problem with the pointer is that you never initialize the pointer. By removing the pointer the memory issues causing the crash will go away.
As a result of this change, you need to change a few other things. The call to setGrades needs to pass the address of myGrades:
setGrades(&(s->myGrades), gradeList);
Even better would be to replace all of this struct/function code with actual classes.

Sum is returning some vague values. All I want to do is get Sum of Elements in my Mutable Array

& yes I did google "How to get sum of array elements" but I want to know what's going on wrong here? If I use break points and see after execution of this line "sum = sum + (int) A[i];" sum has some vague values.
#import <Foundation/Foundation.h>
#interface MyClass : NSObject
#end
#implementation MyClass
#end
int solution(NSMutableArray *A)
{
int sum = 0;
for (int i = 0; i <A.count; i ++)
{
NSLog(#"A.count: %ld", A.count);
sum = sum + (int) A[i]; //A[i] has to return a value right?**strong text**
}
NSLog(#"The final sum is: %d", sum);
return sum;
}
int main(int argc, const char * argv[])
{
#autoreleasepool
{
NSMutableArray *A = [NSMutableArray arrayWithObjects: #"3",#"1",#"2",#"4",#"3", nil];
solution(A);
}
return 1;
}
The elements within your array are NSString objects. You should use NSNumber objects:
NSMutableArray *A = [#[#3,#1,#2,#4,#3] mutableCopy];
Also, you can't just cast them as ints. To get an int from an NSNumber you would need to call call [A[i] intValue]. Otherwise you will be summing the pointer values.
sum = sum + [A[i] intValue];
You are adding the values of the string instead of the integer values.
Simply replace
sum = sum + (int) A[i];
with the following
sum = sum + [A[i] integerValue];

Using NSUInteger Input to insertObject:___ atIndex:___

I'm trying to create a simple commandline tic-tac-toe game using an NSMutableArray.
Created a class called "Board" with the method "getPosition"
(I'm assuming this is the best way to get a user input)
I'm asking for position, then casting from int to NSUInteger)
#import "Board.h"
#implementation Board
-(void)getPosition;
{
int enteredPosition;
scanf("%i", &enteredPosition);
NSUInteger nsEnteredPosition = (NSUInteger ) enteredPosition;
NSLog(#"Position = %lu", (unsigned long)nsEnteredPosition);
}
#import <Foundation/Foundation.h>
#import "Board.h"
int main(int argc, const char * argv[])
{
#autoreleasepool {
NSString *currentPlayer;
NSMutableArray *gameBoard=[[NSMutableArray alloc] initWithCapacity:9];
for(int i; i<=2; i++)
{
if(i %2)
{
currentPlayer=#"X";
}
else
{
currentPlayer=#"O";
}
NSLog(#"Player %#, select an open spot 1 - 9 on the board", currentPlayer);
Board *currentPosition = [[Board alloc] init];
[currentPosition getPosition];
[gameBoard insertObject:currentPlayer atIndex:currentPosition]; //this is where i have a problem
}
As I understand it atIndex requires an NSUInteger parameter, but I'm receiving the error message:
"Incompatible pointer to integer conversion sending 'Board *_strong"
to parameter of type 'NSUInteger' (aka 'unassigned long')
You're using currentPosition as your index which is a Board object. Perhaps [currentPosition getPosition] is supposed to return an NSUInteger. If so, try rewriting the last portion of your code like this:
Board *theBoard = [[Board alloc] init];
NSUInteger currentPosition = [theBoard getPosition];
[gameBoard insertObject:currentPlayer atIndex:currentPosition]; //this is where i have a problem

Make static variable to sum values in class for output, Objective-C

New to Objective-C and had this assignment in which I was to output values of students in two different courses using class/methods.
That was the easy part, the part I need help on is how to declare a static variable and use this variable to add together the values of all the students and output the value.
I've seen all kinds of examples and threads and I'm really trying to wing it on this but I can't figure out how to apply the concept with this problem. It's easy to do in another language but not the same with ObjC...
The code is as follows:
//
// main.m
// yadda yadda
//
// Created by yadda yadda on 8/26/14.
// Display the number of students in two different courses.
//
// Copyright (c) 2014 yadda.self. All rights reserved.
//
#import <Foundation/Foundation.h>
//---- #interface section ----
#interface Students: NSObject
-(void) setCourseOne: (int) a;
-(void) setCourseTwo: (int) b;
-(int) courseone;
-(int) coursetwo;
#end
//---- #implementation section ----
#implementation Students
{
int courseone;
int coursetwo;
}
-(void) setCourseOne:(int) a
{
courseone = a;
}
-(void) setCourseTwo:(int) b
{
coursetwo = b;
}
-(int) courseone
{
return courseone;
}
-(int) coursetwo
{
return coursetwo;
}
#end
//---- Program section ----
int main(int argc, const char * argv[])
{
#autoreleasepool {
Students *myStudents = [[Students alloc] init];
[myStudents setCourseOne: 8];
[myStudents setCourseTwo: 24];
NSLog(#"There are %i students in this class", [myStudents courseone]);
NSLog(#"There are %i students in this class", [myStudents coursetwo]);
//Third output statement for sum of all students
NSLog(#"There are %i students in all of the classes", [myStudents courseone]);
}
return 0;
}
Have you tried a simple addition?
NSLog(#"There are %i students in all of the classes", [myStudents courseone]+[myStudents coursetwo]);
If you want to use a local variable, you can use:
int total = [myStudents courseone] + [myStudents coursetwo];
NSLog(#"There are %i students in all of the classes", total);
There are other comments that could be made to improve your code, but as you are following an assignment we'll assume you'll be coming to those things as your progress.
HTH

Trouble with Polymorphism example from Programming in Objective-C, Stephen Kochan, 6th Edition (Program 9.1)

** UPDATE **
I have changed the extraneous division by zero error in the reduce method. This was not causing the problem.
Original Question Text
I am in the process of reading Stephen Kochan's book, Programming in Objective-C, 6th Edition. There is a program in Capter 9 (9.1) that demonstrates Polymorphism by having complex numbers and fraction each have a print method and an add method.
resultComplex = [c1 add: c2]
and
resultFraction = [f1 add: f2]
and likewise with the print methods. It is completely understandable to me but there appears to be a bust somewhere in the code and I was hoping someone could help. The book is excellent and previous chapters build on themselves with existing code. The earlier versions of the code have all worked. I am suspecting that I have done something stupid like mis-typed something but I've been pouring over it for a few hours.
The output is as follows:
Chapter_9[5617:303] 18 + 2.5i
Chapter_9[5617:303] +
Chapter_9[5617:303] -5 + 3.2i
Chapter_9[5617:303] -----------
Chapter_9[5617:303] 13 + 5.7i
Chapter_9[5617:303]
Chapter_9[5617:303] 1/10
Chapter_9[5617:303] +
Chapter_9[5617:303] 2/15
Chapter_9[5617:303] ------
(lldb)
The program is able to add the Complex numbers but dies at the point it is required to add the Fractions. Xcode identifies add method in Fraction as the offender the following line as the offensive point:
Fraction *result = [[Fraction alloc] init]; // must be alloc/init here
I will include the class files (.h and .m) for the Fraction class. I am leaving out the Complex class because that part of the code runs fine, although there is an analogous line in that Class that seems to work fine. If it is necessary, I will update the post to add those. I just didn't want to drown everyone with that code if my error is obvious.
UPDATE
I am inserting a picture of the debug and output
Fraction Header File
//
// Fraction.h
// Chapter_9
#import <Foundation/Foundation.h>
#interface Fraction : NSObject
#property int numerator, denominator;
-(void) print;
-(void) setTo: (int) n over: (int)d;
-(double) convertToNum;
-(Fraction *) add: (Fraction *) f;
-(void) reduce;
#end
Fraction Implementation File
//
// Fraction.m
// Chapter_9
#import "Fraction.h"
#implementation Fraction
#synthesize numerator, denominator;
-(void) print
{
NSLog (#"%i/%i", numerator, denominator);
}
-(double) convertToNum
{
if (denominator != 0)
return (double) numerator / denominator;
else
return NAN;
}
-(void) setTo: (int) n over: (int) d
{
numerator = n;
denominator = d;
}
-(void) reduce
{
int u = numerator;
int v= denominator;
int temp;
while (v!= 0) {
temp = u % v;
u = v;
v = temp;
numerator /= u;
denominator /=u; //originally there was an unrelated error here
}
}
-(Fraction *) add: (Fraction *) f
{
// To add two fractions:
// a/b + c/d = ((a*d) + (b*c) / (b*d)
// Store the answer in a new Fraction object called (result)
// ************* Here is where Xcode identifies the error *******************
Fraction *result = [[Fraction alloc] init]; // must be alloc/init here
result.numerator = numerator * f.denominator + denominator * f.numerator;
result.denominator = denominator * f.denominator;
[result reduce];
return result;
}
#end
Program Main File:
//
// main.m
// Chapter_9
// Programming in Objective-C, Stephen Kochan, 6th Edition
//Problem 9.1: Shared Method Names: Polymorphism
#import "Fraction.h"
#import "Complex.h"
int main(int argc, const char * argv[])
{
#autoreleasepool {
Fraction *f1 = [[Fraction alloc] init];
Fraction *f2 = [[Fraction alloc] init];
Fraction *fracResult;
Complex *c1 = [[Complex alloc] init];
Complex *c2 = [[Complex alloc] init];
Complex *compResult;
[f1 setTo: 1 over: 10];
[f2 setTo: 2 over: 15];
[c1 setReal: 18 andImaginary:2.5];
[c2 setReal: -5 andImaginary: 3.2];
//add and print 2 complex numbers
[c1 print]; NSLog(#" +"); [c2 print];
NSLog(#"-----------");
compResult = [c1 add: c2]; //compResult is alloc/init in add method
[compResult print];
NSLog(#"\n");
// add and print 2 fractions
[f1 print]; NSLog(#" +"); [f2 print];
NSLog(#"------");
// ******************** Here is where the method call takes place that causes the error
fracResult = [f1 add: f2]; //fracResult is alloc/init in add method
[fracResult print];
}
return 0;
}
I am obviously new to Xcode and Objective-C and so am not able to debug on my own. Sorry for the long and drawn out explanation. I hope someone can help.
Xcode should be giving you a fairly clear division-by-zero error in your reduce method. You haven't copied it correctly from the book, I'm guessing, because your division-by-zero error is being caused by an error in your GCD algorithm.
This:
while (v!= 0) {
temp = u % v;
u = v;
v = temp;
numerator /= u;
denominator /=v;
}
should be this:
while (v!= 0) {
temp = u % v;
u = v;
v = temp;
}
numerator /= u;
denominator /=u;