Creating List from JSON response [duplicate] - c#

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.

Related

"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.

How to import specified class (or varaibles from this class) to another class? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have 3 classes:
First and second class - have variables as listed below:
First class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_1
{
class First_class
{
int variable_1 = 1;
int variable_2 = 1;
int variable_3 = 3;
string variable_4 = "test1"
}
}
Second class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_1
{
class Second_class
{
int variable_5 = 5;
int variable_6 = 6;
int variable_7 = 7;
string varaible_8 = "test_2"
}
}
Third class is empty::
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_1
{
class Program
{
static void Main(string[] args)
{
}
}
}
What should I do to have possibility to use all variables from First class - in Third Class ?
What should I do to have possibility to use only some variables from First class and only some variables from Second class - in Third Class ?
If you want to use those variables outside of First_class, they must be declared as public variables.
class First_class
{
public static int variable_1 = 1; // This can be accessed from outside
public int variable_2 = 1; // This can be accessed from outside too
int variable_3 = 3; // This can not be accessed from outside
string variable_4 = "test1"; // This also can not be accessed from outside
}
class Program
{
static void Main(string[] args)
{
var o = new First_class();
Console.Writeline(First_class.variable_1);
Console.Writeline(o.variable_2);
Console.Writeline(o.variable_3); // Error: variable_3 is private
}
}
1.Here you have two possibilities:
a) To use all variables from First class in Third Class you have to make all of them public.
b) You can make all of them static and public or protected but in such case, the Program class needs to inherit
from the First class so it would look like:
public class First_class
{
protected static int variable_1 = 1;
protected static int variable_2 = 1;
protected static int variable_3 = 3;
protected static string variable_4 = "test1";
}
class Program: First_class
{
static void Main(string[] args)
{
Console.WriteLine(variable_1);
Console.WriteLine(variable_2);
Console.WriteLine(variable_3);
Console.WriteLine(variable_4);
}
}
2.The example:
class Second_class
{
int variable_5 = 5;
int variable_6 = 6;
int variable_7 = 7;
public string varaible_8 = "test_2"; //only this field can be accessed
}
public class First_class
{
public int variable_1 = 1;
public int variable_2 = 1;
protected int variable_3 = 3; // can be accessed via inheritance
private string variable_4 = "test1"; // cannot be accessed due to privacy level
}
class Program
{
static void Main(string[] args)
{
var obj1 = new First_class();
Console.WriteLine(obj1.variable_1);
Console.WriteLine(obj1.variable_2);
var obj2 = new Second_class();
Console.WriteLine(obj2.varaible_8);
}
}

Creating a Random number(in Class) for later extensive use in program C#

I have to create a program where the player has 6 choices, between 2 pets, he must decide either to feed, talk or play with each one, however he can only do one at a time and each time he chooses an option the option chosen (except when talking) makes the other options increase while the former one decreases.
Im having trouble in all aspects, inside the program and inside the class.
I can't seem to define the random numbers inside the Class, and that makes the program not work.
This is the code for the Class so far, here is where the problem must be happening:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tamagochi
{
class Tamagochi
{
private string tamagochi;
private double hungerLvl;
private double boredomLvl;
private double totalLevels;
private static int time;
private static int RandomNumberGenerator;
private static int ranNum1;
private static int ranNum2;
private static int ranNum3;
private static int ranNum4;
public Tamagochi (string tamagochi)
{
this.tamagochi = tamagochi;
}
public Tamagochi (string tamagochi, double hungerLvl, double boredomLvl, double randomNumbers, int RandomNumberGenerator)
{
this.tamagochi = tamagochi;
this.hungerLvl = hungerLvl;
this.boredomLvl = boredomLvl;
this.RandomNumberGenerator = RandomNumberGenerator;
}
public static void IncreaseTime()
{
++time;
}
public static void IncreaseBoredomLvl(double boredomLvl, int random)
{
boredomLvl += // randomnumber
}
public static void IncreaseHungerLvl(double hungerLvl)
{
hungerLvl += //randomnumber
}
public static void randomNumber(int min, int max)
{
Random RandomNumberGenerator = new Random();
ranNum1 = RandomNumberGenerator.Next(1, 6);
ranNum2 = RandomNumberGenerator.Next(1, 6);
ranNum3 = RandomNumberGenerator.Next(1, 6);
ranNum4 = RandomNumberGenerator.Next(1, 6);
}
//return section
public string GetTamagochi()
{
return tamagochi;
}
public double GetBoredomLvl()
{
return boredomLvl;
}
public double GetHungerLvl()
{
return hungerLvl;
}
public static int GetTime()
{
return time;
}
public static int GetRandomNum()
{
return ranNum1;
}
}
}
Any help on trying to make this work?
The Random number should be declared outside the function.
The seed should be effective.
If you want a number between 1 and 6 (both including) you should put in the Next() function from 1 to 7 (because 7 is not included)
So, Your code should look like this:
class Tamagochi
{
private int ranNum1;
private int ranNum2;
private int ranNum3;
private int ranNum4;
Random RandomNumberGenerator;
public Tamagochi()
{
RandomNumberGenerator = new Random(Guid.NewGuid().GetHashCode());
}
public void GetRandomNumber()
{
ranNum1 = RandomNumberGenerator.Next(1,7);
ranNum2 = RandomNumberGenerator.Next(1,7);
ranNum3 = RandomNumberGenerator.Next(1,7);
ranNum4 = RandomNumberGenerator.Next(1,7);
}
}

Im referencing a constant class static variables, but when i do the values somehow change

Here is my constant class that i reference from.
Below that is the class that is trying to use the reference.
Here is the error message im getting.
The Type initializer for ConstantClass threw an exception ---> System.OverflowException: Value was either too large or too small for a Decimal.
Any ideas about it?
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UnitTests
{
[TestClass]
public static class ConstantClass
{
public static int positiveInt = 10;
public static int negativeInt = -10;
public static long positivePastLimitInt = unchecked((int)2147483648);
public static long negativePastLimitInt = unchecked((int)-2147483649);
public static int zeroInt = 0;
public static char lowerChar = 'c';
public static char spaceChar = ' ';
public static char symbolChar = '#';
public static char numberChar = '1';
public static char upperChar = 'D';
public static string lowerString = "hello";
public static string upperString = "HELLO";
public static string emptyString = "";
public static string spaceString = " ";
public static string tabString = " ";
public static string symbolString = "!^&";
public static string nullString = null;
public static short positiveShort = 10;
public static short negativeShort = -10;
public static short zeroShort = 0;
public static int positivePastLimitShort = unchecked((short)32768);
public static int negativePastLimitShort = unchecked((short)-32769);
public static long positiveLong = 10;
public static long negativeLong = -10;
public static long zeroLong = 0;
public static Int64 positivePastLimitLong = (long)2147483648;
public static Int64 negativePastLimitLong = (long)-2147483649;
public static double positiveDouble = 10.0;
public static double negativeDouble = -10.0;
public static double zeroDouble = 0.0;
public static double positiveLimitDouble = double.MaxValue;
public static double negativeLimitDouble = double.MinValue;
public static float positiveFloat = 10.0F;
public static float negativeFloat = -10.0F;
public static float zeroFloat = 0.0F;
public static double positivePastLimitFloat = (float)float.MaxValue + 1;
public static double negativePastLimitFloat = (float)float.MinValue - 1;
public static bool positiveBool = true;
public static bool negativeBool = false;
//Here is the variable im trying to use.
public static decimal positiveDecimal = 10.0m;
public static decimal negativeDecimal = -10.0m;
public static decimal zeroDecimal = 0.0m;
public static decimal positivePastLimitDecimal = Convert.ToDecimal(80000000000000E+40);
public static decimal negativePastLimitDecimal = Convert.ToDecimal(-8000000000000E-40);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTests
{
[TestClass]
public class ByteDecimalTests
{
/// <summary>
///
/// </summary>
[TestMethod]
public void DecimalToBytes_WhenDecimalIsPositive()
{
//This is where i reference the constant class
Decimal positiveDecimal = ConstantClass.positiveDecimal;
//Decimal positiveDecimal = 12.98m;
String positiveDecimalString = positiveDecimal.ToString();
byte[] positiveDecimalArray = Encoding.ASCII.GetBytes(positiveDecimalString);
byte[] array = ByteDecimal.DecimalToBytes(positiveDecimal);
System.Diagnostics.Debug.WriteLine(Encoding.Default.GetString(positiveDecimalArray));
System.Diagnostics.Debug.WriteLine(Encoding.Default.GetString(array));
Assert.AreEqual(array, positiveDecimalArray);
}
}
}
Your problem is here:
public static decimal positivePastLimitDecimal = Convert.ToDecimal(80000000000000E+40)
public static decimal negativePastLimitDecimal = Convert.ToDecimal(-8000000000000E-40);
You cannot store such big numbers on a decimal. Use float or double for that.
The maximum value you can store in a decimal is: 79,228,162,514,264,337,593,543,950,335.
Maybe this helps you to understand what you are doing, and so you could decide how to solve it. I'll take the short as the easier case to study, but the same can be said for every other case.
From your code:
public static int positivePastLimitShort = unchecked((short)32768);
A short is internally stored as a 16 bits value, 15 bits for data and 1 bit for the sign.
sign b14 b13 b12 b11 b10 b09 b08 b07 b06 b05 b04 b03 b02 b01 b00
When you try to use a value that needs more than 15 bits to be represented, an overflow will occur.
32768 in binary form is 1000000000000000
but you cannot use the bit15, which is reserved for the sign in shorts (in ushort you can use all 16 bits, as no bit is reserved for sign).
You could even supress the cast and the unchecked, and just do:
public static int positivePastLimitShort = 32768;
as an int uses internally 32 bits, 1 for sign and 31 for data.
This is working as you have a value type that can store bigger numbers.
So, using an int for shorts passing the limit, using long for ints passing the limits, and so on. The problem would be to handle numbers passing the limits of the bigger capacity types, as long, double or decimal. For these cases you need a different way.

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