Invalid token errors with enums - c#

I'm having a little trouble with this code that I'm writing for a simple program. I get tons of errors saying "invalid token".
The program basically asks for 2 integers and sums them up, but the program needs to be called in another method.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AustinPDangeloJPA03
{
class Add
{
static void Main(string[] args)
{
double num1,
num2,
sum;
Console.Write("Enter the First integer: ");
num1 = int.Parse(Console.ReadLine());
//First Integer entered and storred
Console.Write("Enter the Second integer: ");
num2 = int.Parse(Console.ReadLine());
//Second Integer entered and storred
sum = Display(double a, double b);
//First and second numbers added together
Console.WriteLine(" {0} + {1} = {2} ",num1,num2,sum);
//displays the sum
//Instructs the user to press the Enter key to end the program
Console.WriteLine("Press the Enter key to terminate the program...");
Console.ReadLine();
}//Closes Main Method
static enum Display(a,b)
{
double c = a + b;
return c;
}//closes display method
}//Closes Class Add
}

This is not correct:
static enum Display(a,b)
{
double c = a + b;
return c;
}
The enum keyword is used to declare an enumeration. In order to define a method, you need a valid return type (such as int or double), and you need to provide the proper types for the individual arguments. You can optionally add static if you want it to be a static method, but that depends on its purpose.
I suspect you want to use something more like:
double Add(double a, double b)
{
// ...
If you then correct the line that called this method:
sum = Display(double a, double b);
This should compile and give you what you expect.

Your Display method is not declared correctly.
You need to declare a method that takes two numbers and returns a third number.
Consult your textbook and assignment for more information on how to declare a method and which types to use.
You're also not calling it correctly; method calls do not take types.

While it is not the source of your errors, it does indicate a misunderstanding of types:
double num1, num2,sum;
[...]
num1 = int.Parse(Console.ReadLine());
The first line declares some double variables.
The second line tries to parse int variables.
While the int will get auto-converted to a double, your code will be better if it is consistent with the use of types. You should switch to either int types, or to Double.Parse().

The enum keyword is for creating enumerations, for example:
public enum Color { Red, Green, Blue };
You have to specify a data type as return type for your Display method, and data types for the parameters:
static double Display(double a, double b) {
double c = a + b;
return c;
}
Also, you don't specify data types when you call the method, so change that to:
sum = Display(a, b);

Change this line to:
double sum = Display(num1, num2);
And change your Display method to be a method.
private static double Display(double a, double b)
{
double c = a + b;
return c;
}

Related

My code works, but I don't fully understand how

using System;
namespace SimpleweightConversion
{
public class PoundstoKilos
{
public static void Main()
{
double pounds = 0.0;
Console.Write("How many pounds? ");
double.TryParse(Console.ReadLine(), out pounds);
double kilograms = pounds * 0.453592;
Console.WriteLine("{0} pounds is equal to {1} kilograms", pounds,
kilograms);
Console.WriteLine("Press enter to exit.");
Console.ReadLine();
}
}
}
I'm trying to learn C# and I created this code to convert from pounds to kilograms, I added the tryparse bit to avoid an error if the user throws something other than numbers at the program, and it works!.The only problem I have is it doesn't clearly show when does it assign the user's input to the pounds variable, because at the start, the value of the pounds variable is 0.0, but at some point, the value provided by the user is assigned to the pounds variable, or at least that's what I think is happening.
From the Microsoft Docs, the syntax for TryParse() is:
public static bool TryParse(
string s,
out double result
)
This means that if the string s is numeric, its parsed value is immediately assigned to the variable result.
In your code, you have the line double.TryParse(Console.ReadLine(), out pounds);
In this case, the input from the console is parsed to a double, and assigned to pounds if possible.
The user's input is assigned to the pounds variable within the TryParse() method.
The out modifier indicates that the argument is being passed by reference - which means that any changes to the argument (in this case, pounds) that occur within the method call will be applied to the actual variable.
It is get assigned when u take user's input using Console. ReadLine() method.
"I.e. double.TryParse(Console.ReadLine(), out pounds);"
User's input is extracted into pounds variable.
The other answers have explained your error. I thought I'd just show you how you should write your code to make it easier to understand:
public class PoundsToKilos
{
public static void Main()
{
double pounds = 0.0;
Console.Write("How many pounds? ");
if (double.TryParse(Console.ReadLine(), out pounds))
{
//`pounds` has been assigned a value
double kilograms = pounds * 0.453592;
Console.WriteLine("{0} pounds is equal to {1} kilograms", pounds, kilograms);
}
else
{
//`pounds` has NOT been assigned a value
Console.WriteLine("You didn't enter a valid number.");
}
Console.WriteLine("Press enter to exit.");
Console.ReadLine();
}
}

Getting Error while using Math.Sqrt function in C#

In the program given below, Math.Sqrt function is throwing an error that is
"Expression denotes a variable', where amethod group' was expected."
What seems to be problematic here?
using System;
class program{
static void Main(){
Console.WriteLine("Enter the sides(a,b,c) of a triangle :");
int a = Convert.ToInt16(Console.ReadLine());
int b = Convert.ToInt16(Console.ReadLine());
int c = Convert.ToInt16(Console.ReadLine());
double s = (a+b+c)/2;
double area = Math.Sqrt(s(s-a)(s-b)(s-c));
if (a==b&&b==c){
Console.WriteLine("This is an Equilateral trangle");
}
else if(a==b&&b!=c||a!=b&&b==c){
Console.WriteLine("This is an Isosceles trangle");
}
else{
Console.WriteLine("This is an Scalene trangle");
}
}
}here
C# will not assume a multiplication in the same way you write down an equation, and instead will see s(s-a) as a function called s that takes a parameter of s-a. You need to explicitly state the multiplication sign:
double area = Math.Sqrt(s*(s-a)*(s-b)*(s-c));

Error 1 Type 'Pay' already defines a member called 'ComputePay' with the same parameter types

I can't seem to figure our what the issue is here. pph and with both equal to different values in the different overloads. I'm not sure what I'm doing wrong. I don't see how the values are the same.
public class Pay
{
public double ComputePay(double h,double pph,double with)
{
double net = 0;
try
{
double gross = h * pph;
net = gross - with;
}
catch (FormatException)
{
Console.WriteLine("Hour's cannot be less than zero");
}
return net;
}
public double ComputePay(double h, double pph, double with = 0.15)
{
double net = 0;
try
{
double gross = h * pph;
net = gross - with;
}
catch (FormatException)
{
Console.WriteLine("Hour's cannot be less than zero");
}
return net;
}
public double ComputePay(double h, double pph = 5.85, double with = 0.15)
{
double net = 0;
try
{
double gross = h * pph;
net = gross - with;
}
catch (FormatException)
{
Console.WriteLine("Hour's cannot be less than zero");
}
return net;
}
}
I'm not sure what I'm doing wrong.
You've got three methods which both have three double parameters:
public double ComputePay(double h,double pph,double with)
public double ComputePay(double h, double pph, double with = 0.15)
public double ComputePay(double h, double pph = 5.85, double with = 0.15)
The fact that some of the parameters in some of the method declarations are optional is irrelevant to overloading here - you simply can't specify three methods like that. Which method would you expect to be called if the caller specifies three arguments?
Why do you want three methods anyway, given that they all do the same thing? Just get rid of the first two.
You cannot have two or more methods with the same signature. This means that they cannot have the same name and parameter-types. This has nothing to do with the value that will be passed to the method.
Correct could be:
public int Sum(int a, int b)
{
return Sum(a, b, 0);
}
public int Sum(int a, int b, int c)
{
return a + b + c;
}
Edit:
Here's an interesting MSDN-article giving guidelines about Member Overloading.
Your method signature (double, double, double) is the same. In this case, just delete the first two implementations. The last one will most likely already behave the way you want.
Your last two ComputePay (double, double, double) are the same. Having a default variable doesn't make the method different. Just use the second one and you'll be good to go.

Function definition in case of different type of arguments?

I am writing a simple program in which I have defined a function which accepts certain type of argument , now new requirement I got has same procedures to be done which I had already in written in earlier function , but this time it should on different type of argument.I am not able to call straight way this same function for two different types of arguments. So my question is how I should modify my function to behave in such a way. I am hoping that it is possible. I would like something as ,I have function like Sum(int 1,int j) now I would like to use same function for double type arguments.
This is called overloading. What you can do is simply write two functions:
public double Sum(int 1, int j)
public double Sum(double 1, double j)
And your program will call the appropriate one based on the arguments you pass to it.
Simple with generics
T Sum<T>(T i,T j) { ... }
However, you won't be able to do i+j or anything, so it depends.
Why don't you define a method with double as parameter type and later you can call it for integer values as well.
private double Sum(double a, double b)
{
return a+b;
}
and later you can call it like:
int a = 1;
int b = 2;
int Sum = (int) Sum(a,b);
Since an integer can be passed to a double type parameter. But if your method involves complex calculation then you are better of with multiple overloads of the Sum method with different types.
In .NET there is no type encompassing different numeric types. So you need two overloads of the same method, one that takes int arguments, one that takes double arguments.
You declare a new method with the same amount of parameters but different types.
public Int32 Sum(Int32 i, Int32 j)
{
return i + j;
}
public Double Sum(Double i, Double j)
{
return i + j;
}
So you have a method that takes int parameters
public int Sum(int val1,int val2)
{
return val1 + val2;
}
Now you need a method that takes doubles:
public double Sum(double val1,double val2)
{
return val1 + val2;
}
If you want a generic class which supports all "numeric" types you can have a look here:
http://www.codeproject.com/Articles/33617/Arithmetic-in-Generic-Classes-in-C
You can write GENERIC METHODS for different datatypes.
check this Link
Look more into this link. It shows how o create a function that can handle several datatypes.
int a = 2, b = 3;
double c = 2.345, d = 3.45;
object inta = a, intb = b;
object doublec = c, doubled = d;
Console.WriteLine(Sum(inta, intb).ToString());
Console.WriteLine(Sum(doublec, doubled).ToString());
public object Sum(object a, object b)
{
object sum = null;
if (a.GetType().ToString() == "System.Int32" && b.GetType().ToString() == "System.Int32")
{
sum = Convert.ToInt32(a.ToString()) + Convert.ToInt32(b.ToString());
}
if (a.GetType().ToString() == "System.Double" && b.GetType().ToString() == "System.Double")
{
sum = Convert.ToDouble(a.ToString()) + Convert.ToDouble(b.ToString());
}
return sum;
}

Clarification about delegates

What is the below code doing? I think the pointer will be changed to the multiply method.
But what is "+=" doing here. I am confused.
delegate int calc(int a , int b);
static void Main(string[] args)
{
calc c = new calc(Add);
c += new calc(Multiply);
Console.WriteLine(c(3, c(4, 2)));
Console.Read();
}
public static int Add(int a, int b)
{
return (a + b);
}
public static int Multiply(int a, int b)
{
return (a * b);
}
The + and += operator
Similar to how you use the + operator to add values, you can use the += operator to both add and assign back to the same value.
An example of these operators applied to ints:
int a = 5;
a += 7; // a is now 12
a = a + 11;
Console.WriteLine(a);
24
Combining delegates
As AVD mentioned, you use the + and += operators to combine delegates.
When you apply these operators to delegates, you aren't doing a mathematical "sum" or "sum and assign", like my example with ints. Instead you are modifying a list of methods to be called when you invoke the delegate.
From that article:
Delegates can be combined such that when you call the delegate, a whole list of methods are called - potentially with different targets
So when you add/combine delegates, you'll end up calling multiple methods.
If you change your code to:
public static int Add(int a, int b)
{
Console.WriteLine("From Add");
return (a + b);
}
public static int Multiply(int a, int b)
{
Console.WriteLine("From Multiply");
return (a * b);
}
Then you will see this output when you run the program:
From Add
From Multiply
From Add
From Multiply
24
This is because:
You combined the Add and Multiply delegates, so both get called when you call c(x, y)
Multiply is the last delegate you added to that chain of delegates
You are calling c(x, y) twice. This is similar to if you had called: Multiply(3, Multiply(4, 2))
Return values from combined delegates
That point about the last delegate you added to the chain is also mentioned in the article:
If a delegate type is declared to return a value (i.e. it's not declared with a void return type) and a combined delegate instance is called, the value returned from that call is the one returned by the last simple delegate in the list.
The last method you added to the chain was Multiply, so all other return values are thrown out, and only the return value from Multiply is used when you call c(x, y).
You can see this demonstrated in your program. 3 * 4 * 2 is 24, which is your program's output. None of your calls to Add impact the final result.
+= is like appending multiple calls to the delegate object. Since its a multicast delegates, you can append multiple destination calls to the a single delegate. To append to a delegate, you need new delegate objects. And thats whats been doing in the second line.
Its similar to,
CalcDelegate C1, C2;
C1 = new CalcDelegate(Add);
C2 = new CalcDelegate(Multiply);
C1 = C1 + C2;
Its called Combining the delegates.
You can think of delegates as a cross between value types (like int or double) and arrays of method addresses.
You know that if you write this code:
var x = 5;
var y = x + 2;
y += 3;
Then afterwards x == 5 & y == 10 even though y had an intermediate value of 7 this was "thrown away" when the final assignment occurred.
Quite clearly the final value of y isn't 3.
In your code you wrote this:
calc c = new calc(Add);
c += new calc(Multiply);
As with y, the final value of c isn't Multiply. It's really more like this:
c == { Add, Multiply }
When you then call something like c(4, 2) you are effectively calling both Add & Multiply and because the delegate returns a value you only get back the final delegate's value - in this case from Multiply - and that's what makes it appear that the "pointer" changed to the Multiply method.
You could try adding in this code before you call c:
c -= new calc(Multiply);
and this will effectively return c back to this:
c == { Add }
And this is why delegates appear to behave like arrays of method addresses.
Now if you change your Add & Multiply methods to look like this:
public static int Add(int a, int b)
{
Console.WriteLine("Add({0}, {1})", a, b);
return (a + b);
}
public static int Multiply(int a, int b)
{
Console.WriteLine("Multiply({0}, {1})", a, b);
return (a * b);
}
you can then watch the calls as they occur. Your original code runs like this:
Add(4, 2)
Multiply(4, 2)
Add(3, 8)
Multiply(3, 8)
24
I hope this helps.

Categories