黑马程序员技术交流社区
标题:
创建一个学生对象,并输出成绩最大的人的信息,并排序
[打印本页]
作者:
kfz0507
时间:
2017-6-14 17:09
标题:
创建一个学生对象,并输出成绩最大的人的信息,并排序
@interface Person : NSObject
@property(nonatomic,copy)NSString *name;
@property(nonatomic,assign)int score;
-(instancetype)initWithName:(NSString *)name andScore:(int)score;
+(instancetype)personWithName:(NSString *)name andScore:(int)score;
@end
@implementation Person
-(instancetype)initWithName:(NSString *)name andScore:(int)score{
if (self=[super init]) {
self.name=name;
self.score=score;
}
return self;
}
+(instancetype)personWithName:(NSString *)name andScore:(int)score{
return [[self alloc]initWithName:name andScore:score];
}
@end
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person *p1=[Person personWithName:@"jack" andScore:90];
Person *p2=[Person personWithName:@"jack" andScore:80];
Person *p3=[Person personWithName:@"cathy" andScore:90];
Person *p4=[Person personWithName:@"yeat" andScore:88];
NSMutableArray *arr=[NSMutableArray arrayWithObjects:p1,p2,p3,p4, nil];
int max=0;
int index=0;
for (int i=0; i<arr.count; i++) {
if (max<[arr[i] score]) {
max=[arr[i] score];
index=i;
}
}
NSLog(@"最好成绩的是:%@,%d",[arr[index]name],[arr[index]score]);
for (int i=0; i<arr.count-1; i++) {
for (int j=0; j<arr.count-1-i; j++) {
if ([arr[j]score]<[arr[j+1]score]) {
Person *temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}else if([arr[j]score]==[arr[j+1]score]){
if ([[arr[j]name]compare:[arr[j+1]name]] == NSOrderedAscending) {
Person *temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
}
for (int i=0; i<arr.count; i++) {
NSLog(@"%@ %d",[arr[i]name],[arr[i]score]);
}
}
return 0;
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2