I am trying to make a guessing app for school.
-(IBAction)check:(id)sender
{
if (answerField.text.length > 0)
{
[self number];
}
else
{
UIAlertView *error = [[UIAlertView alloc]
initWithTitle:#"Error"
message:#"Please type in more than one chracter"
delegate:self
cancelButtonTitle:#"Okay!"
otherButtonTitles:nil];
[error show];
}
}
-(void)number
{
for (int i = 0; i < 100; i++)
{
if (answerField.text > strNumber)
{
hlLabel.text = #"Guess Lower";
answerField.text = #"";
}
if (answerField.text < strNumber)
{
hlLabel.text = #"Guess Higher";
answerField.text = #"";
}
}
}
The Problem: The for loop does not work. It only checks once. Also, everytime it checks, it always says "Guess Higher" when in fact, I guess higher than the computer generate number.
Other Information: I have a method where every time I click the keyboard done from the textfield, it will check the number method.
answerField.text is returning an NSString, not a number.
Try answerField.text.intValue.
And strNumber must be an integer for that to work, btw.
It took me some time to understand what you were trying to do. But I suspect that you are just trying to have a user enter some number in a field to guess a number with up to 100 attempts. Something like that.
But a for loop is not how you can make a user retry something. What you need is some state saved in the object (i.e. an ivar) which counts each attempt.
Second problem here is that it seems you are numerically comparing strings which does not make sense here. You want to compare numerical values.
So your program would likely look like:
-(IBAction)check:(id)sender
{
if (answerField.text.length > 0)
{
[self checkFieldValueAgainstCorrectAnswer]; // use better naming
}
else
{
UIAlertView *error = [[UIAlertView alloc]
initWithTitle:#"Error"
message:#"Please type in more than one chracter"
delegate:self
cancelButtonTitle:#"Okay!"
otherButtonTitles:nil];
[error show];
}
}
-(void)checkFieldValueAgainstCorrectAnswer
{
NSUInteger fieldValue = [answerField.text unsignedIntegerValue];
NSUInteger correctValue = [strNumber unsignedIntegerValue];
if (fieldValue > correctValue) {
// guess lower
} else if(fieldValue < correctValue) {
// guess higher
} else {
// you won!
return;
}
answerField.text = #"";
attempts++;
if (attempts > 100) {
// Too many attemps, you lost!
}
}
Related
I'm working on an application where I've to use sqlite and there are lots of data. I want to load data from "residents_status" column of a table named "tblResident". it is taking too much time to load data of that column (residents_status) more than 8 seconds and other data takes just a second. During the period of fetching the data from "residents_status" column, if I press a button its give me 'query error'
in else part but if I click button after 8 seconds than it is working fine.
Here is my code:
if(sqlite3_exec(database, insert_stmt, NULL, NULL, &error)==SQLITE_OK)
{
NSLog(#"succeddd.....");
IsValidate = true;
if([self checkNetConnection])
{
[self UpdateServerWith_LocalDB];
NSString *Key= [DefaultsValues getStringValueFromUserDefaults_ForKey: #"Key"];
if([[DefaultsValues getStringValueFromUserDefaults_ForKey: #"LastAuthenticationStatus"] isEqualToString:#"false"]){
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:nil message:#"Your Access is Restrcited,Please contact us" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
}
}
else{
NSLog(#"query error");
ErrorMsg = [NSString stringWithFormat:#"%s", error ];
IsValidate = false;
}
This working perfectly in iOS 8.
But creating issue in iOS 9.Here is code :
self.eventManager.eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (granted) {
// Create a new calendar.
EKCalendar *calendar = [EKCalendar calendarForEntityType:EKEntityTypeEvent
eventStore:self.eventManager.eventStore];
// Set the calendar title.
calendar.title = #"<APP name>";
calendar.CGColor=APP_Blue_COLOR.CGColor;
// Find the proper source type value.
for (int i=0; i<self.eventManager.eventStore.sources.count; i++) {
EKSource *source = (EKSource *)[self.eventManager.eventStore.sources objectAtIndex:i];
EKSourceType currentSourceType = source.sourceType;
if (currentSourceType == EKSourceTypeLocal) {
calendar.source = source;
break;
}
}
// Save and commit the calendar.
NSError *error;
[self.eventManager.eventStore saveCalendar:calendar commit:YES error:&error];
// If no error occurs then turn the editing mode off, store the new calendar identifier and reload the calendars.
if (error == nil) {
// Turn off the edit mode.
// Store the calendar identifier.
[self.eventManager saveCustomCalendarIdentifier:calendar.calendarIdentifier];self.eventManager.selectedCalendarIdentifier=calendar.calendarIdentifier;//chirag
}
else{
// Display the error description to the debugger.
NSLog(#"CREATE_CALENDER %#", [error localizedDescription]);
}
}
else
{
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"" message:#"Please give permission to access your iPhone calender." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
}
}];
It give me success message but not creating my app calendar in iPhone calendar.
I though that it does not showing it due to no event set to it.so I also tried to set new event.
But it give me following code & error while creating new event.
// Create a new event object.
EKEvent *event = [EKEvent eventWithEventStore:self.eventManager.eventStore];
// Set the event title.
event.title = title;
// Set its calendar.
event.calendar = [self.eventManager.eventStore calendarWithIdentifier:self.eventManager.selectedCalendarIdentifier];
// Set the start and end dates to the event.
event.startDate = startDate;
event.endDate = endDate;
// Save and commit the event.
NSError *error;
if ([self.eventManager.eventStore saveEvent:event span:EKSpanThisEvent commit:YES error:&error]) {
// Call the delegate method to notify the caller class (the ViewController class) that the event was saved.
return true;
}
else{
// An error occurred, so log the error description.
NSLog(#"%#", [error localizedDescription]);
return false;
}
It give following error internally however it return will in NSError object:
Error getting shared calendar invitations for entity types 3 from daemon: Error Domain=EKCADErrorDomain Code=1014 "(null)"
The problem is that when iCloud calendars switched on, it hides the locally created ones from the calendar app. To bypass this problem the solution is to add a new calendar to iCloud source:
for (EKSource *source in self.eventStore.sources)
{
if (source.sourceType == EKSourceTypeCalDAV &&
[source.title isEqualToString:#"iCloud"]) //This is a patch.
{
localSource = source;
break;
}
}
if (localSource == nil)
{
for (EKSource *source in self.eventStore.sources)
{
if (source.sourceType == EKSourceTypeLocal)
{
localSource = source;
break;
}
}
}
if (stash != 0) {
for (i=1; i<=6; i++) {
a[1][i]=a[1][i]/stash;
}
}
else
{
NSLog (#"Matrix is Not Invertible");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Matrix is not invertible!" delegate:nil cancelButtonTitle:#"Review Input" otherButtonTitles:nil, nil];
[alert show];
}
I Want to stop the program if the variable "stash" is zero, but i can't use break since it's not in a loop, i wanted to use return but it says that void should not return any value... what should i do to get this working? thanks for all your help....
I don't know if you need to exit the method only but you could use:
return;
or redefine the method to return an integer -(int)myMethod; and then return 0;
//Add return statement, returning nothing
return;
- (void)yourMethod {
//your code
//your declerations
if (stash != 0) {
for (i=1; i<=6; i++) {
a[1][i]=a[1][i]/stash;
}
}
else
{
NSLog (#"Matrix is Not Invertible");
UI *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Matrix is not invertible!" delegate:nil cancelButtonTitle:#"Review Input" otherButtonTitles:nil, nil];
[alert show];
//Add return statement here, returning nothing
return;
}
//other code in your method
//your code
}
I am new to programming. I am having trouble finding out what all is wrong with this. It is an alert view that i am trying to randomize the text displayed in the message.
-(void)alert:(id)sender{
int randomNumber;
randomNumber = (randomNumber() %3 + 1);
NSLog(#"%i", randomNumber);
if (randomNumber == 1) {
self.YouWin.text = [NSString stringWithFormat:#"You Win"];
}
else if (randomNumber == 2) {
self.YouWin.text = [NSString stringWithFormat:#"You Lose"];
}
else if (randomNumber == 3) {
self.YouWin.text = [NSString stringWithFormat:#"Tie"];
}
NSLog(#"%#",YouWin);
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Hello" message:[NSString stringWithFormat:#"%#",YouWin] delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
button.hidden = YES;
Try this one:
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Hello"
message:self.YouWin.text
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
You needed text-value stored in YouWin, but you passed the YouWin object itself.
*Note: you can use arc4random() for generating random numbers.
There are many good suggestions; I agree with AKB8085.
Replacing the randomNumber() with arc4random() will help at compile time.
But you might want to re-think implementing a random number generator. The reason is in fairness to your user. I pose the question, “Is it fair to assume you want your user to guess a number with this large of a number range?”
Did you Know?
Using the arc4random(3), rand(3), or random(3) you are using a C function.
You are asking the user to guess a number with the following ranges:
arc4random(3) = 0 to 4294967296
rand(3) and random(3) that top out at a RAND_MAX of 0x7fffffff (214748647)
To help in answering your question, answer the following requirement questions:
Is there a min/max range restraint?
What type of compelling delays will happen
by using arc4random(3), rand(3), or random(3)?
Is using NSArray like in the Fisher–Yates_shuffle a better answer?
SUGGESTION:
Read an article on random numbers and NSArray.
NOTE:
Random numbers tend to task the compiler and your user experience will be hindered.
As Anoop noted you are using stringWithFormat but you're not providing a format string at all.
You should do
[NSString stringWithFormat:#"%#", #"You Win"];
but that's extremely redundant, although correct, and it's totally equivalent to just using #"You Win".
Also an advice for the general approach on the problem. Instead of having a big if-else statement, it's better to store all your string into a data structure and then randomly access to it.
In code this would translate to
NSArray * outcomes = #[ #"You Win", #"You lose", #"Tie" ];
int randomIndex = arc4random_uniform(outcomes.count);
NSString * randomOutcome = outcomes[randomIndex];
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Hello"
message:randomOutcome
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alert show];
button.hidden = YES;
Note the usage of arc4random_uniform() that gives you back a random number between 0 and the argument provided, excluded.
Replace
randomNumber = (randomNumber() %3 + 1);
with
randomNumber = arc4random() %3 + 1;
Also use this...
if (randomNumber == 1) {
self.YouWin.text = [NSString stringWithFormat:#"You Win"];
}
else if (randomNumber == 2) {
self.YouWin.text = [NSString stringWithFormat:#"You Lose"];
}
else if (randomNumber == 3) {
self.YouWin.text = [NSString stringWithFormat:#"Tie"];
}
NSLog(#"%#",YouWin);
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Hello"
message:self.YouWin.text
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alert show];
button.hidden = YES;
I am creating an iPhone app which is taking many values from the user and assigning them to variables.
I want to display an alert message if more than two of the variables' values are equal to zero.
Basically, if the user has two empty fields, it should show an alert stating that there is insufficient data.
Any idea how to do this?
Your question is a bit vague but what about
Find errors
Display an alert
Somewhere alone the lines of this pseudo code:
int errorCount = 0;
if(var1 == 0) {
errorCount++;
}
if(var2 == 0) {
errorCount++;
}
// check all variables...
// Show alert if there are any errors
if(errorCount > 0) {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Title"
message:[NSString stringWithFormat:#"You have %d errors", errorCount]
delegate:nil
cancelButtonTitle:#"GoFightWin"
otherButtonTitles: nil, nil];
[alert show];
[alert release];
}