Getting data from the user via the command line - c#

I want to have someone input a value for length and width in my code, here is what I got so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Rectangle
{
double length;
double width;
double a;
static double Main(string[] args)
{
length = Console.Read();
width = Console.Read();
}
public void Acceptdetails()
{
}
public double GetArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}
class ExecuteRectangle
{
public void Main()
{
Rectangle r = new Rectangle();
r.Display();
Console.ReadLine();
}
}
}
Is trying to use two Main methods the wrong way to approach this? This is code I was copying from http://www.tutorialspoint.com/csharp/csharp_basic_syntax.htm I'm trying to modify it around to just to get more experience with this programming language.

There are some problem with you code, let's analyse them:
a program must have a unique entry point and it must be a declared as static void, here you have two main but they are wrong
you in your static Main the one in the rectangle class you can't reference the variables length e width because they're not declared as static
console.Read() return an int that represent a character so using if the user inputs 1 you may have a different value in your length variable
your static double Main doesn't return a double
I think that what you want is:
declare the static double Main as void Main()
declare your void Main as static void Main(string[] args)
in your new static void Main call (after you create the rectangle) it's Main method (to do that you have to define it as public)
use ReadLine instead of Read()
ReadLine return a string so to transform that in a double you have to use lenght = double.Parse(Console.ReadLine())
finally call your r.display()
This is a working code that do what you want.
Note before copy pasting, since you're trying and lear read the steps and try to fix it without looking at the code
class Rectangle
{
double length;
double width;
double a;
public void GetValues()
{
length = double.Parse(Console.ReadLine());
width = double.Parse(Console.ReadLine());
}
public void Acceptdetails()
{
}
public double GetArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}
class ExecuteRectangle
{
public static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.GetValues();
r.Display();
Console.ReadLine();
}
}

In this cases you'll have to tell the compiles wich is the class with the entry point.
"If your compilation includes more than one type with a Main method, you can specify which type contains the Main method that you want to use as the entry point into the program."
http://msdn.microsoft.com/en-us/library/x3eht538.aspx
And yes, having two main methods is confusing and senseless.

Related

Creating List from JSON response [duplicate]

I have two classes, one for defining the algorithm parameters and another to implement the algorithm:
Class 1 (algorithm parameters):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace VM_Placement
{
public static class AlgorithmParameters
{
public static int pop_size = 100;
public static double crossover_rate = 0.7;
public static double mutation_rate = 0.001;
public static int chromo_length = 300;
public static int gene_length = 4;
public static int max_allowable_generations = 400;
static Random rand = new Random();
public static double random_num = rand.NextDouble();
}
}
Class 2 (implement algorithm):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace VM_Placement
{
public class Program
{
public struct chromo_typ
{
public string bits;
public float fitness;
//public chromo_typ(){
// bits = "";
// fitness = 0.0f;
//}
chromo_typ(string bts, float ftns)
{
bits = bts;
fitness = ftns;
}
};
public static int GetRandomSeed()
{
byte[] bytes = new byte[4];
System.Security.Cryptography.RNGCryptoServiceProvider rng =
new System.Security.Cryptography.RNGCryptoServiceProvider();
rng.GetBytes(bytes);
return BitConverter.ToInt32(bytes, 0);
}
public string GetRandomBits()
{
string bits="";
for (int i = 0; i < VM_Placement.AlgorithmParameters.chromo_length; i++)
{
if (VM_Placement.AlgorithmParameters.random_num > 0.5f)
bits += "1";
else
bits += "0";
}
return bits;
}
public static void Main(string[] args)
{
Random rnd = new Random(GetRandomSeed());
while (true)
{
chromo_typ[] Population = new chromo_typ[VM_Placement.AlgorithmParameters.pop_size];
double Target;
Console.WriteLine("\n Input a target number");
Target = Convert.ToDouble(Console.ReadLine());
for (int i = 0; i < VM_Placement.AlgorithmParameters.pop_size; i++)
{
Population[i].bits = GetRandomBits();
Population[i].fitness = 0.0f;
}
}
}
}
}
I am getting an error on Population[i].bits = GetRandomBits(); in Main().
Error is:
An object reference is required for the non-static field, method, or property 'VM_Placement.Program.GetRandomBits()'
Am I missing anything?
The Main method is Static. You can not invoke a non-static method from a static method.
GetRandomBits()
is not a static method. Either you have to create an instance of Program
Program p = new Program();
p.GetRandomBits();
or make
GetRandomBits() static.
It looks like you want:
public static string GetRandomBits()
Without static, you would need an object before you can call the GetRandomBits() method. However, since the implementation of GetRandomBits() does not depend on the state of any Program object, it's best to declare it static.
The Main method is static inside the Program class. You can't call an instance method from inside a static method, which is why you're getting the error.
To fix it you just need to make your GetRandomBits() method static as well.

"An object reference is required for the non-static field, method, or property" exception when adding event handler [duplicate]

I have two classes, one for defining the algorithm parameters and another to implement the algorithm:
Class 1 (algorithm parameters):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace VM_Placement
{
public static class AlgorithmParameters
{
public static int pop_size = 100;
public static double crossover_rate = 0.7;
public static double mutation_rate = 0.001;
public static int chromo_length = 300;
public static int gene_length = 4;
public static int max_allowable_generations = 400;
static Random rand = new Random();
public static double random_num = rand.NextDouble();
}
}
Class 2 (implement algorithm):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace VM_Placement
{
public class Program
{
public struct chromo_typ
{
public string bits;
public float fitness;
//public chromo_typ(){
// bits = "";
// fitness = 0.0f;
//}
chromo_typ(string bts, float ftns)
{
bits = bts;
fitness = ftns;
}
};
public static int GetRandomSeed()
{
byte[] bytes = new byte[4];
System.Security.Cryptography.RNGCryptoServiceProvider rng =
new System.Security.Cryptography.RNGCryptoServiceProvider();
rng.GetBytes(bytes);
return BitConverter.ToInt32(bytes, 0);
}
public string GetRandomBits()
{
string bits="";
for (int i = 0; i < VM_Placement.AlgorithmParameters.chromo_length; i++)
{
if (VM_Placement.AlgorithmParameters.random_num > 0.5f)
bits += "1";
else
bits += "0";
}
return bits;
}
public static void Main(string[] args)
{
Random rnd = new Random(GetRandomSeed());
while (true)
{
chromo_typ[] Population = new chromo_typ[VM_Placement.AlgorithmParameters.pop_size];
double Target;
Console.WriteLine("\n Input a target number");
Target = Convert.ToDouble(Console.ReadLine());
for (int i = 0; i < VM_Placement.AlgorithmParameters.pop_size; i++)
{
Population[i].bits = GetRandomBits();
Population[i].fitness = 0.0f;
}
}
}
}
}
I am getting an error on Population[i].bits = GetRandomBits(); in Main().
Error is:
An object reference is required for the non-static field, method, or property 'VM_Placement.Program.GetRandomBits()'
Am I missing anything?
The Main method is Static. You can not invoke a non-static method from a static method.
GetRandomBits()
is not a static method. Either you have to create an instance of Program
Program p = new Program();
p.GetRandomBits();
or make
GetRandomBits() static.
It looks like you want:
public static string GetRandomBits()
Without static, you would need an object before you can call the GetRandomBits() method. However, since the implementation of GetRandomBits() does not depend on the state of any Program object, it's best to declare it static.
The Main method is static inside the Program class. You can't call an instance method from inside a static method, which is why you're getting the error.
To fix it you just need to make your GetRandomBits() method static as well.

Methods not working? [duplicate]

This question already has an answer here:
C# - Why is this variable not being changed after being put through a method [duplicate]
(1 answer)
Closed 5 years ago.
Here is the block of code that I am having a bit of trouble with:
using System;
namespace TestProgram {
class Test {
static void Main() {
int number = 10;
MultiplyByTen(number);
Console.WriteLine(number);
Console.ReadKey(true);
}
static public void MultiplyByTen(int num) {
num *= 10;
}
}
}
When I run this block of code, I got 10 as the output instead of 100. My question is: Why does this happen and how to solve it?
Thanks for the help.
The problem is that when the variable number enters into the method MultiplyByTen the value is copied and the variable you are modifying inside it's in fact the copy, so, the original was not changed.
Try this instead:
public static void MultiplyByTen(ref int num)
{
num *= 10;
}
But remember you will have to call it with the ref keyword as well.
static void Main()
{
int number = 10;
MultiplyByTen(ref number);//Notice the ref keyword here
Console.WriteLine(number);
Console.ReadKey(true);
}
I recommend you to also check this out: Passing Objects By Reference or Value in C#
You need to return the value back to the function also assign the returned value to the number.
static void Main()
{
int number = 10;
number = MultiplyByTen(number);
Console.WriteLine(number);
Console.ReadKey(true);
}
static public int MultiplyByTen(int num)
{
return num *= 10;
}
Using your implementation:
using System;
namespace TestProgram {
class Test {
static void Main() {
int number = 10;
//MultiplyByTen(number);
//Console.WriteLine(number);
Console.WriteLine(MultiplyByTen(number));
Console.ReadKey(true);
}
static public int MultiplyByTen(int num) {
return num *= 10;
}
}
}

A field initializer cannot reference the nonstatic field using delegates

Iam very new to C#. I am learning more about delegates. When I run this code, I get the following error:
A field initializer cannot reference the nonstatic field at the line:
CalArepointer cpointer = CalculateArea;
Here is my program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace calculatearea
{
class Program
{
delegate double CalArepointer(int r);
CalArepointer cpointer = CalculateArea;
static void Main(string[] args)
{
double area = cpointer.Invoke(20);
Console.ReadKey();
}
double CalculateArea(int r)
{
return 3.14 * r * r;
}
}
}
You should initialize the value of cpointer inside the static context of Main method since there you are going to use it:
class Program
{
delegate double CalArepointer(int r);
CalArepointer cpointer;
static void Main(string[] args)
{
cpointer = CalculateArea;
double area = cpointer.Invoke(20);
Console.ReadKey();
}
double CalculateArea(int r)
{
return 3.14 * r * r;
}
}
for the pure sake of initializing the value of cpointer outside of the main method, you want to use Static members
class Program
{
delegate double CalArepointer(int r);
static CalArepointer cpointer = CalculateArea;
static double CalculateArea(int r)
{
return 3.14 * r * r;
}
static void Main(string[] args)
{
double area = cpointer.Invoke(20);
Console.WriteLine(area);
Console.ReadKey();
}
}

C# error: "An object reference is required for the non-static field, method, or property"

I have two classes, one for defining the algorithm parameters and another to implement the algorithm:
Class 1 (algorithm parameters):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace VM_Placement
{
public static class AlgorithmParameters
{
public static int pop_size = 100;
public static double crossover_rate = 0.7;
public static double mutation_rate = 0.001;
public static int chromo_length = 300;
public static int gene_length = 4;
public static int max_allowable_generations = 400;
static Random rand = new Random();
public static double random_num = rand.NextDouble();
}
}
Class 2 (implement algorithm):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace VM_Placement
{
public class Program
{
public struct chromo_typ
{
public string bits;
public float fitness;
//public chromo_typ(){
// bits = "";
// fitness = 0.0f;
//}
chromo_typ(string bts, float ftns)
{
bits = bts;
fitness = ftns;
}
};
public static int GetRandomSeed()
{
byte[] bytes = new byte[4];
System.Security.Cryptography.RNGCryptoServiceProvider rng =
new System.Security.Cryptography.RNGCryptoServiceProvider();
rng.GetBytes(bytes);
return BitConverter.ToInt32(bytes, 0);
}
public string GetRandomBits()
{
string bits="";
for (int i = 0; i < VM_Placement.AlgorithmParameters.chromo_length; i++)
{
if (VM_Placement.AlgorithmParameters.random_num > 0.5f)
bits += "1";
else
bits += "0";
}
return bits;
}
public static void Main(string[] args)
{
Random rnd = new Random(GetRandomSeed());
while (true)
{
chromo_typ[] Population = new chromo_typ[VM_Placement.AlgorithmParameters.pop_size];
double Target;
Console.WriteLine("\n Input a target number");
Target = Convert.ToDouble(Console.ReadLine());
for (int i = 0; i < VM_Placement.AlgorithmParameters.pop_size; i++)
{
Population[i].bits = GetRandomBits();
Population[i].fitness = 0.0f;
}
}
}
}
}
I am getting an error on Population[i].bits = GetRandomBits(); in Main().
Error is:
An object reference is required for the non-static field, method, or property 'VM_Placement.Program.GetRandomBits()'
Am I missing anything?
The Main method is Static. You can not invoke a non-static method from a static method.
GetRandomBits()
is not a static method. Either you have to create an instance of Program
Program p = new Program();
p.GetRandomBits();
or make
GetRandomBits() static.
It looks like you want:
public static string GetRandomBits()
Without static, you would need an object before you can call the GetRandomBits() method. However, since the implementation of GetRandomBits() does not depend on the state of any Program object, it's best to declare it static.
The Main method is static inside the Program class. You can't call an instance method from inside a static method, which is why you're getting the error.
To fix it you just need to make your GetRandomBits() method static as well.

Categories

Resources