+ 1

Can someone tell me what I'm doing wrong? The debugger says that "answer" does not exist in the current context.

using System; public class Program { public static void Main() { Console.WriteLine("Enter a number: "); int num01 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter another number: "); int num02 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Do you want to add or multiply them? (Type 'A' for addition and 'M' for multiplication)"); string userInput = Console.ReadLine().ToUpper(); if (userInput == "A" ) { int answer = num01 + num02; } else { elsehappens(num01, num02); } Console.WriteLine(answer); // It shows the error in this line. } public static int elsehappens(int num01, int num02) { int answer = num01 * num02; return answer; } }

20th Feb 2018, 3:08 PM
Aashish
Aashish - avatar
6 Réponses
+ 2
It's good practice to declare your variables at the top and then use them as needed, rather than just randomly all over your code. Just a little tip to help avoid such issues. 1. Variable 'answer' is out of scope for how you're using it, so declare it at the top to prevent that issue. It'll compile after that. Example: public static void Main() { int answer = 0; 2. Your multiplication route doesn't work. In order to resolve that, when you call the 'elsehappens' function, make sure you're storing it in a variable so you can use its value. 'answer' in the elsehappens function is in a different scope than the 'answer' variable in your main loop. Example: answer = elsehappens(num01, num02); https://code.sololearn.com/cr6RRn832xEz/#cs ^Your code working as intended.
20th Feb 2018, 3:11 PM
Fata1 Err0r
Fata1 Err0r - avatar
+ 3
if (userInput == "A" ) { // answer only exists within this block int answer = num01 + num02; } // answer no longer exists Put: int answer; before the if statement. Remove the existing "int " before answer assignment. Add a "answer = " in front of elsehappens call to save the function return value.
20th Feb 2018, 3:15 PM
John Wells
John Wells - avatar
+ 1
when else executes and " elsehappened()" is called. it returns an int. but your not using it or saving in a variable
20th Feb 2018, 2:57 PM
Farshaad Heydari
Farshaad Heydari - avatar
+ 1
add "int answer =" before the call for "elsehappened ()"
20th Feb 2018, 2:58 PM
Farshaad Heydari
Farshaad Heydari - avatar
+ 1
but best way is to create a global variable for answer (and not declaring one inside each of if else statements)
20th Feb 2018, 3:00 PM
Farshaad Heydari
Farshaad Heydari - avatar
+ 1
Thanks a lot @farshaad heydari. Creating global variable solved the problem!
20th Feb 2018, 3:10 PM
Aashish
Aashish - avatar