Error when calling a function in C# because variable is used in parameter [closed] - c#-7.0

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm new to c#, but I'm trying to create a basic program that can use a function that adds to numbers (this is just practice I know it's inefficient.
{
int AddNumbers(int num1, int num2) //Here's where the error comes
{
int result = num1 + num2;
return result;
}
int num1 = 10;
int num2 = 20;
AddNumbers(num1, num2);
However, when I try it, it says that "A local parameter named 'num1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter". I assume that this is because I declared the variables while calling the function, but I don't know how to fix it.
Thanks for any help!
EDIT: Just to be clear, the numbers after the functions are the number I would like to be added in the function

Local methods have access to every thing in the parent block. That is why you cannot define the same variable name more than once. Try this instead.
{
int num1;
int num2;
int AddNumbers(int left, int right) => left + right;
AddNumbers(num1, num2);
}
There is a guide for this as well found here: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/local-functions

I guess you were trying to make a method for add Numbers. If you want to make a method, you need make method OUTSIDE of the Main code.
public static int AddNumbers(int num1, int num2)
{
int sum;
sum = num1 + num2;
return sum;
}
static void Main(string[] args)
{
int a = 10;
int b = 20;
Console.WriteLine($"a = {a}, b = {b}");
//First way to control the string: put $ infront of the string, and write code in the {})
Console.WriteLine("a + b = {0}", AddNumbers(a, b));
//Second way to control the string: put {} and number (start with 0) and write code after comma
}
If you write as this, you will get an answer as
a = 10, b = 20
a + b = 30
For public static int AddNumbers(int num1, int num2)
You don't have to think about public static yet.
At the position of int, you can put another variables such as string, long, double. For that case, you have to return (various you put); at the end.
If you put void, you don't have to put return and the thing you wanted will be done in the method.

Welcome to SO.
as you know you cannot have same variable name used in a method
here is what you need
{
int AddNumbers(int num1, int num2) //Here's where the error comes
{
int result = num1 + num2;
return result;
}
int num2 = 10;
int num3 = 20;
AddNumbers(num2, num3);
}
you can have something like this:
class Program
{
int p = 0;
public static void Main(string[] args)
{
int num1 = 10;
int num2 = 20;
int num = Method1(num1,num2);
Console.WriteLine(num);
}
public static int Method1(int num1, int num2)
{
p = num1 + num2;
return p;
}
}

Related

Convert string to double without parse or tryparse in C#

How can I convert a string to a double using a method that does not include parse or tryparse? I have the program for converting a string to a long, would it be the same for a double? I am a complete newbie.
Code snippets from OP comment below:
public static bool isLong(string s) {
bool n = true;
int a = 0;
s = s.Trim();
for (a = 0; (a < s.Length); a = a + 1) {
n = n && ((s[a] >= '0') && (s[a] <= '9'));
}
return (n);
}
public static long toLong(string s) {
long ret = 0;
int a;
s = s.Trim();
if (isLong(s)) {
for (a = 0; (a< s.Length); a = a + 1) {
ret = (ret * 10) + (s[i] - '0');
}
} else {
}
return (ret);
}
I think I now understand the question. If so, the answer is yes, sort of.
long is an integer type, so processing one digit at a time is fairly straight forward.
double is a floating decimal type, so you have to figure out a way to deal with the decimal period in the middle.
Is this a class assignment or something where you absolutely must write this code on your own? If not, please consider using the library functions that already exist for this purpose, such as stod: http://www.cplusplus.com/reference/string/stod/

garbage in loop for no reason

i wrote a function that receives a string as a char array and converts it to an int:
int makeNumFromString(char Str[])
{
int num = 0, len = 0;
int p;
len = strlen(Str);
for (p = 0; p<len; p++)
{
num = num * 10 + (Str[p] - 48);
}
return num;
}
the problem is that no matter how long the string i input is, when "p" gets to 10 the value of "num" turns to garbage!!!
i tried debbuging and checking the function outside of the larger code but no success.
what could be the problem and how can i fix it?
THANKS
Perhaps your int can only store 32 bits, so the number cannot be higher than 2,147,483,647.
Try using a type for num with more storage, like long.

How do I delete a word with Recursion and count the times it deletes?

I've completed about half of my assignment where I have to count the "chickens" in a string, remove the chickens, and return the amount of times I have to remove them.
public static int countChickens(String word)
{
int val = word.indexOf("chicken");
int count = 0;
if(val > -1){
count++;
word = word.substring(val + 1);
//I'm aware the following line doesn't work. It's my best guess.
//word.remove.indexOf("chicken");
val = word.indexOf("chicken");
}
return count;
}
As is, the program counts the correct amount of chickens in the word itself. (Sending it "afunchickenhaschickenfun" returns 2.) However, I need it to be able to return 2 if I send it something like "chichickencken" because it removed the first chicken, and then the second chicken came into play. How do I do the remove part?
Not tested and writen in sudo code, but should give you a better idea on a way to approach this.
int numberOfChickens = 0;
public void CountAndReplaceChicken(string word)
{
int initCheck = word.indexOf("chicken");
if (initCheck > -1)
{
word = word.remove.indexOf("chicken"); // not sure about the syntax in Eclipse but given you figure this part out
numberOfChickens++;
int recursionCheck = word.indexOf("chicken");
if (recursionCheck > -1)
CountAndReplaceChicken(word);
}
}
Okay, the teacher showed us how to do it a few days later. If I understood David Lee's code right, this is just a simplified way of what he did.
public static int countChickens(String word)
{
int val = word.indexOf("chicken");
if(val > -1){
return 1 + countChickens(word.substring(0, val) + word.substring(val + 7));
}
return 0;
}

Java Concept Confusion : Objects and Primitive Types

I am really confused about this concept:
/* Example with primitive data type */
public class Example1 {
public static void main (String[] args){
int a = 1;
System.out.println("a is " + a);
myMethod( a );
System.out.println("a is " + a);
}
public static void myMethod(int b){
b = 3;
System.out.println("b is " + b);
}
}
OUTPUT:
a is 1
b is 3
a is 1
Why does "a" not change?How does this primitive variable CHANGE like for a FOR LOOP or a WHILE LOOP when int i is initialed to zero? Like this:
int i = 1;
while (i < = 3) {
System.out.println(i);
i *= 2;
}
OUTPUT:
1
2
Please let me know in detail, as I am really confused.i is a primitive type, why does it get updated, and why does not int a in the first program?
myMethod() is void, if it returned an int and you assigned a=myMethod(a) then it would change
int a = 1;
System.out.println("a is " + a);
a= myMethod(a); //where myMethod is changed to return b instead of void
System.out.println("a is " + a);
a is 1
b is 3
a is 3
"Why does "a" not change?"
Because primitive a inside of your myMethod is not the same a that you had in your void main. Treat it as completely another variable and that its value got copied into myMethod. This primitive`s lifecycle ends in the end of this method execution.
If you have C++ background then maybe this explanation might help:
When you pass primitive type arguments into method - you are passing
variables that are being copied. You passed value, not instance.
When you pass objects as arguments
into method - you are passing references to that object, but to be more precise: in java, a copy of reference value is being passed. It is like passing a copy of the address of the object to the method. If you modify this object inside this method, the modifications will be visible outside the method. If you =null or =new Obj it, it will affect the object only inside your method.

string definition problem

int main()
{
int score;
string scoreLetter;
char A, B, C, D, F;
cout<<"Enter the grade: ";
cin>> score;
void letterGrade (int score);
void gradeFinal (int score);
cout<<"The letter grade is "<< scoreLetter<<".";
}
void letterGrade (int score)
{
if (score >= 90) {
string scoreLetter = 'A'
} else if (score >= 80) {
scoreLetter = 'B'
} else if (score >= 70)
-When compiling, I am getting an error for the line scoreLetter = 'A', etc. What is wrong with this? Error states 'scoreLetter' undefined. Do I need to define scoreLetter in the function not the main?
Single quotes in C/C++ are used to define a character, not a String. Use double quotes instead. string scoreLetter = "A". Also you need to include the header if std::string is what you are trying to use: #include <string> and using std::string.
You'll want to return whatever value your function determines scoreLetter should be, and in main have a line like scoreLetter = letterGrade(score);. You can't set local variables from another function, unless the caller passed them to you by reference, which isn't happening here (and, in most cases, shouldn't be abused like that).
Aside from that, it looks like you're mixing up declarations and invocations. void letterGrade (int score); doesn't actually call letterGrade; it just says that there is a letterGrade function that takes an int, which we'll call "score". (The score there is just a name that's part of the prototype; it has no connection to your score variable.) So you'll likely find that if you managed to get your code to compile, it'd do something quite different than you're expecting it to do.
To call a function, you'd do something like letterGrade(score);, or if you followed my first suggestion, scoreLetter = letterGrade(score);.
string letterGrade (int score);
// void gradeFinal (int score); // not used in this snippet
int main()
{
int score;
string scoreLetter;
char A, B, C, D, F;
cout<<"Enter the grade: ";
cin>> score;
scoreLetter = letterGrade(score);
cout<<"The letter grade is "<< scoreLetter<<".";
}
string letterGrade (int score)
{
string grade;
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else if (score >= 70)
...
return grade;
}
Your code is cut off there but I think from what is available you are not calling the functions properly.
You should also try to be more specific about what language you are talking about, i.e. C in this case I believe.
A correct call to the functions would be:
letterGrade(score);
And yes, you need to define the string variable at global scope, so just move it out of main and above it.
string scoreLetter;
int main()
{
int score;
char A, B, C, D, F;
cout<<"Enter the grade: ";
cin>> score;
letterGrade (score);
gradeFinal (score);
cout<<"The letter grade is "<< scoreLetter<<".";
}
void letterGrade (int score)
{
if (score >= 90) {
scoreLetter = "A"
} else if (score >= 80) {
scoreLetter = "B"
} else if (score >= 70)

Resources