I haven't any errors, but the program always generates 0 for AnimalAge. It should generate numbers from 1-20. This is a simple game where a player should find Age of Animal. Corrected, still get 0.
public class losowaniez
{
public int AnimalAge;
public static Random AnimalAge1 = new Random();
public int Age2
{
get
{
return AnimalAge1.Next(20);
}
}
}
public class Animal
{
public void Fish()
{
Console.WriteLine("Zwierze moze miec maksymalnie 10 lat, zgadnij ile ma lat");
int x = Convert.ToInt32(Console.ReadLine());
}
public int zwierze(losowaniez c)
{
int AnimalAge = c.Age2;
Console.WriteLine("Zwierze moze miec maksymalnie 20 lat zgadnij ile ma lat");
int x = Convert.ToInt32(Console.ReadLine());
if (x == AnimalAge)
{
Console.WriteLine("Wygrales gre");
Console.ReadKey();
}
else if (x > AnimalAge)
{
Console.WriteLine("Celuj nizej!");
zwierze();
}
else
{
Console.WriteLine("Celuj wyzej!");
zwierze();
}
}
}
add a constructor to the class losowaniez and do the assigning of Age2 in the Constructor.
Your class would be
public class losowaniez
{
public int AnimalAge;
public int Age2;
public losowaniez()
{
int AnimalAge;
Random RandomObj = new Random();
AnimalAge = RandomObj.Next(20);
Age2 = AnimalAge;
}
}
you should do something like this
Change your losowanie() method as below method
public int losowanie()
{
Random RandomObj = new Random();
Age2 = RandomObj.Next(20);
return Age2;
}
Call above function inside zwierze() like this
losowaniez MyAnimal = new losowaniez();
int AnimalAge = MyAnimal.losowanie();
Alternatively You can Create Public Property in your losowaniez class
public int Age2
{
get {
Random RandomObj = new Random();
return RandomObj.Next(20);
}
}
after creating property your this code will work
losowaniez MyAnimal = new losowaniez();
int AnimalAge = MyAnimal.Age2;
Related
I am creating a console app in c#. The apps purpose is to create robots, randomly assign 5 tasks once the robot is created, then display the robots total time etc. I have a class for BotTask and for Robot.
Having trouble with the following:
I am initializing each individual BotTask then attempting to load them into a list, to randomize them and return 5 BotTask's that can be assigned to a Robot.
I was thinking if each BotTask has an index property: I can randomize an integer then use that index property to select which BotTask is called by random.
When I try this I am receiving error code CS1503 (Arguement 1: cannot convert from 'int' to 'BotOMat.BotTask') and am unsure if I am trying to complete this process the correct way.
Here is the code I have written for the BotTask class:
public class BotTask
{
//initialize bot tasks
public static readonly BotTask DISHES = new BotTask("Dishes", "Do the dishes", 1000, 1);
public static readonly BotTask SWEEP = new BotTask("Sweep", "Sweep the house", 3000, 2);
public static readonly BotTask LAUNDRY = new BotTask("Laundry", "Do the laundry", 10000, 3);
public static readonly BotTask RECYCLING = new BotTask("Recycling", "Take out the recycling", 4000, 4);
public static readonly BotTask SAMMICH = new BotTask("Sammich", "Make a sammich", 7000, 5);
public static readonly BotTask LAWN = new BotTask("Lawn", "Mow the lawn", 20000, 6);
public static readonly BotTask RAKE = new BotTask("Rake", "Rake the leaves", 18000, 7);
public static readonly BotTask BATH = new BotTask("Bath", "Give the dog a bath", 14500, 8);
public static readonly BotTask BAKE = new BotTask("Bake", "Bake some cookies", 8000, 9);
public static readonly BotTask WASH = new BotTask("Wash", "Wash the car", 20000, 10);
public string Name { get; private set; }
public string Description { get; private set; }
public int Duration { get; private set; }
public int Index { get; private set; }
private BotTask(string name, string description, int duration, int index)
{
Name = name;
Description = description;
Duration = duration;
Index = index;
}
public static List<BotTask> randomizeBotTasks()
{
var loadBotTasks = new List<BotTask> { DISHES, SWEEP, LAUNDRY, RECYCLING, SAMMICH, LAWN, RAKE, BATH, BAKE, WASH };
int i = 1;
List<BotTask> randomizedBotTasks = new List<BotTask>();
while (i <= 5)
{
var random = new Random();
int index = random.Next(loadBotTasks.Count);
randomizedBotTasks.Add(index);
i++;
}
return randomizedBotTasks;
}
Without intentionally adding a second question here I would like to return this list of BotTasks to my Robot Class. So after user creates a Robot, 5 randomized BotTasks will be assigned to it.
Here is how I am trying to achieve this in my Robot class:
public class Robot
{
public string BotName { get; set; }
public RobotType BotType { get; set; }
public string BotTypeDescription => BotType.GetDescription();
public TimeSpan TimeElapsed { get; set; }
private readonly List<BotTask> _tasks = new List<BotTask>();
//public IEnumerable<BotTask> Tasks => _tasks;
public Robot(string botName, RobotType botType, TimeSpan timeElapsed = default)
{
this.BotName = botName;
this.BotType = botType;
TimeElapsed = timeElapsed;
}
public static void CreateRobot()
{
var robotsList = new List<Robot>();
//loop until there are no more robots
while (true)
{
Console.Write("Enter robot name: ");
var robotName = Console.ReadLine();
if (string.IsNullOrEmpty(robotName))
{
break; //empty robot, time to list things out
}
//RobotType? robotType = null;
RobotType? robotType = null;
while (!robotType.HasValue)
{
robotType = GetResponseUsingEnum<RobotType>("Robots");
}
var robot = new Robot(robotName, robotType.Value);
robotsList.Add(robot);
}
//At this point, we have a fully populated list of robots, each with some tasks
foreach (var robot in robotsList)
{
robot.Show();
}
}
public static T? GetResponseUsingEnum<T>(string prompt) where T : struct, Enum
{
//Loop until a good answer (or no answer)
while (true)
{
Console.WriteLine($"{prompt}: Please enter one of:");
var values = (T[])Enum.GetValues(typeof(T));
foreach (var enumValue in values)
{
var description = enumValue.GetDescription<T>();
var intValue = Convert.ToInt32(enumValue);
Console.WriteLine($"{intValue}: {description}");
}
Console.Write(">> ");
var response = Console.ReadLine();
if (string.IsNullOrEmpty(response))
{
return (T?)null;
}
if (Enum.TryParse<T>(response, out var val))
{
if (values.Contains(val))
{
Console.WriteLine($"You answered: {val}");
return val;
}
}
}
}
Appreciate any help in advance - thank you.
You can't add integer value to List<BotTask>
Use this:
public static List<BotTask> randomizeBotTasks()
{
var loadBotTasks = new List<BotTask> { DISHES, SWEEP, LAUNDRY, RECYCLING, SAMMICH, LAWN, RAKE, BATH, BAKE, WASH };
int i = 1;
List<BotTask> randomizedBotTasks = new List<BotTask>();
while (i <= 5)
{
var random = new Random();
int index = random.Next(loadBotTasks.Count);
randomizedBotTasks.Add(loadBotTasks[index]);
i++;
}
return randomizedBotTasks;
}
I have code like this:
class First
{
public int a { get; set; }
public int b { get; set; }
public int c = 2;
public _second;
public First()
{
_second = new Second(c);
this.a = _second.a;
this.b = _second.b;
}
}
class Second
{
public int a;
public int b;
public Second(int c)
{
if(c == 0)
{
a = 1;
b = 2;
}
else
{
a = -1;
b = -2;
}
}
}
How can I pass a and b from First class into second class and then directly from second class set their values withohut using static as declaration in First class.
I have tried this:
class First
{
public int a;
public int b;
public int c = 2;
public _second;
public First()
{
_second = new Second(a, b, c);
}
}
class Second
{
public Second(int a, int b, int c)
{
if(c == 0)
{
a = 1;
b = 2;
}
else
{
a = -1;
b = -2;
}
}
}
but it is not doing the job.
You can simply add a constructor in the Second class that receives the instance of First and updates the public variables of the instance passed
public class Second
{
public Second(int a, int b, int c)
{
// old constructor if still needed
...
}
public Second(First f)
{
int sign = f.c == 0 ? 1 : -1;
f.a = 1 * sign;
f.b = 2 * sign;
}
}
By the way, I suggest to use properties instead of public fieds.
public class First
{
public int a {get;set;}
public int b {get;set;}
public int c {get;set;} = 2;
public Second _second {get;set;}
public First()
{
_second = new Second(this);
}
}
UPDATE
Looking at your image it is clear what is the source of your problem. You are receiving a Form class instance in your Forma constructor. You need to receive a Main instance like
public Forma(Main form, int modulID)
{
.....
}
The base class Form has no knowledge of methods defined in custom form classes. In alternative you can still receive a Form instance but you need to add something like this
public Forma(Form form, int modulID)
{
Main m = form as Main;
if(m != null)
m.helpWindow = new Help(modulID);
}
.....
}
You can pass the fields as ref meaning that you pass a reference to the field passed as parameter not the value. This means changes to the fields inside the Second constructor will be reflected in the First class
class First
{
public int a;
public int b;
public int c = 2;
public Second _second;
public First()
{
_second = new Second(ref a, ref b, c);
}
}
class Second
{
public Second(ref int a, ref int b, int c)
{
if (c == 0)
{
a = 1;
b = 2;
}
else
{
a = -1;
b = -2;
}
}
}
You can pass by ref to any method not just a constructor. You should read more about this topic, here for example
I accomplished it with Interface.
public interface IClass
{
int a { get; set; }
int b { get; set; }
}
class First : IClass
{
public int a { get; set; }
public int b { get; set; }
public int c = 2;
public _second;
public First()
{
_second = new Second(this, c);
}
}
class Second
{
public Second(IClass ic, int c)
{
if(c == 0)
{
ic.a = 1;
ic.b = 2;
}
else
{
ic.a = -1;
ic.b = -2;
}
}
}
I have created a class named Card and a class named CardDeck.
In class CardDeck I've declared an array named deck( of type Card ) whose elements are objects of class Card.
Its Card object has its own number and shape.
How can I compare for example deck[0] with deck[1] to see if these obects have the same number or the same shape?
Class CardDeck
using System;
public Class CardDeck
{
private int number_of_elements = 30;
public CardDeck()//constructor
{
int[] arrayNumber = {0,1,2,3,4,5,6,7,8,9};
string[] arrayShape = { "oval" , "diamond", "square" };
deck = new Card[number_of elements];
InitialiseDeck(arrauNumber, arrayShape);
}
private void InitialiseDeck(int[] num, string[] sha)
{
int count = 0;
for( int i = 0; i < 10; i++)
{
for(int j = 0; j < 3; j++)
{
deck[count] = new Card(num[i],sha[j]);
count++;
}
}
}
}
Class Card
using System;
public class Card
{
private int number;
private string shape;
public Card( int cardNumber, string cardShape)
{
number = cardNumber;
shape = cardShape;
}
}
You'll want to make public attributes on the Card class that expose the number and shape variables. Then in code outside the Card class reference those attributes.
For example:
public class Card
{
private int number;
private string shape;
public Card( int cardNumber, string cardShape)
{
number = cardNumber;
shape = cardShape;
}
public int Number { get { return this.number; } }
public string Shape { get { return this.shape; } }
}
Usage:
var card1 = new Card(13, "diamond");
var card2 = new Card(13, "heart");
if (card1.Number == card2.Number && card2.Shape == card2.Shape)
{
// The cards are the same
}
If all you want to do is check for equality of cards, then you can just declare what the == operator will do for the Card class: https://msdn.microsoft.com/en-us/library/8edha89s.aspx
So I have the following set-up.
A sensor that detects the temperature of a room a controller then checks if it is below or above a set temperature and if it is below it starts a heater.
Now how do I get the method GetCurTemp() to get the temperature I have set?
public class TempSensor
{
public int Temp { get; set; }
}
public class Control
{
private int threshold;
public Control(TempSensor t, Heater h, int thr)
{
threshold = thr;
}
public void SetThreshold(int thr)
{
threshold = thr;
}
public int GetThreshold()
{
return threshold;
}
public int GetCurTemp()
{
return ???;
}
}
class Test
{
static void Main(string[] args)
{
var tempSensor = new TempSensor();
var heater = new Heater();
var uut = new Control(tempSensor, heater, 25);
Console.WriteLine("Set the current temperatur");
int n= int.Parse(Console.ReadLine());
tempSensor.Temp = n;
}
}
You need to keep a reference to the TempSensor in your Control class. Then you can access the temperature from that reference.
public class Control
{
private int threshold;
private TempSensor sensor;
public Control(TempSensor t, Heater h, int thr)
{
threshold = thr;
sensor = t;
}
public void SetThreshold(int thr)
{
threshold = thr;
}
public int GetThreshold()
{
return threshold;
}
public int GetCurTemp()
{
return sensor.Temp;
}
}
You aren't doing anything with the TempSensor object you're passing into the Control constructor. You should set up a field like sensorTemp in your Control class to hold this value.
public class Control
{
private int threshold;
private int sensorTemp;
public Control(TempSensor t, Heater h, int thr)
{
threshold = thr;
sensorTemp = t.Temp;
}
public void SetThreshold(int thr)
{
threshold = thr;
}
public int GetThreshold()
{
return threshold;
}
public int GetCurTemp()
{
return sensorTemp;
}
}
using System;
namespace Matrix_Algebra
{
public struct S_Matrix_size
{
public int size_R, size_C;
public S_Matrix_size(int r, int c)
{
this.size_R = r;
this.size_C = c;
}
}
public class C_Matrix_entries
{
public C_Matrix_entries()
{
int r, c;
Console.WriteLine("Enter number of rows and columns ");
r = Convert.ToInt32(Console.ReadLine());
c = Convert.ToInt32(Console.ReadLine());
S_Matrix_size size = new S_Matrix_size(r,c);
double[,] entry = new double [size.size_R,size.size_C];
Console.WriteLine("Enter the entries from first row [left to right] to the last row ");
for (int i = 0; i<size.size_R; i++)
{
Console.WriteLine("Enter the {0} row", i + 1);
for (int j = 0; j<size.size_C;j++)
{
entry[i, j] = Convert.ToDouble(Console.ReadLine());
}
}
}
}
}
namespace Row_Reduce_Algebra
{
using Matrix_Algebra;
public class TEST
{
static void Main()
{
C_Matrix_entries matrix_no1 = new C_Matrix_entries();
for (int i = 0; i < **matrix_no1.size**; i++)
{
}
}
}
}
As the title says, I'm trying to access a variable from a class instance, but don't know how to do it properly.
You can't access matrix_no1.size because size is inaccessible.
Add a public property to your C_Matrix_entries class, and reference it in Main().
public class C_Matrix_entries
{
public S_Matrix_size size { get; private set; }
public C_Matrix_entries()
{
...
size = new S_Matrix_size(r,c);
As #GrantWinney rightfully pointed out (as I was shaping up a working reply for you), you cannot access matrix_no1.size because it is inaccessible. (It is also out of scope being that matrix_no1 is a local variable declared in the default C_Matrix_entries constructor.)
Based on your code, here is an end-to-end working example of how to fix the problem using a somewhat different public property added to C_Matrix_entries. Beyond the flavor of the new S_Matrix_size public property you add to C_Matrix_entries (i.e. Grant Winney's will work too), you will need to compute the product of its size_R and size_C properties in your loop's setup.
using System;
namespace Matrix_Algebra
{
public struct S_Matrix_size
{
public int size_R, size_C;
public S_Matrix_size(int r, int c)
{
this.size_R = r;
this.size_C = c;
}
}
public class C_Matrix_entries
{
private S_Matrix_size _size;
public C_Matrix_entries()
{
int r, c;
Console.WriteLine("Enter number of rows and columns ");
r = Convert.ToInt32(Console.ReadLine());
c = Convert.ToInt32(Console.ReadLine());
_size = new S_Matrix_size(r,c);
double[,] entry = new double [_size.size_R,_size.size_C];
Console.WriteLine("Enter the entries from first row [left to right] to the last row ");
for (int i = 0; i<_size.size_R; i++)
{
Console.WriteLine("Enter the {0} row", i + 1);
for (int j = 0; j<_size.size_C;j++)
{
entry[i, j] = Convert.ToDouble(Console.ReadLine());
}
}
}
public S_Matrix_size Size { get { return _size; } }
}
}
namespace Row_Reduce_Algebra
{
using Matrix_Algebra;
public class TEST
{
static void Main()
{
C_Matrix_entries matrix_no1 = new C_Matrix_entries();
for (int i = 0; i < matrix_no1.Size.size_R * matrix_no1.Size.size_C; i++)
{
// TODO: something useful
Console.WriteLine(i); // FORNOW
}
}
}
}