i am making a simple game of rover, in which i am having a simple problem which i can't figured out
This is my Main Function which is making One rover object in which rover can handle multiple device, there is one device which extract the specimen
Rover rov = new Rover();
string input;
//Device d = new Device();
//Specimen spec = new Specimen();
Console.WriteLine("Welcome to Planetary Rover");
Console.WriteLine("Enter y to start the game or n to exit");
string selection = Console.ReadLine();
if (selection == "y")
{
Console.WriteLine("Enter the rover Default Location X: ");
rov.X =
do
{
Console.WriteLine("Write the device nname to operate ");
input = Console.ReadLine();
rov.Handle(input);
//d.Operate();
} while (input != "end");
}
if (selection == "n")
{
Console.Clear();
}
else
{
Console.WriteLine("Wrong Input!");
}
THe drill is the device which extraxt the specimen whenever it is operated, it only extract if the specimen x and y is equals to rover x and y
I have done these thing but in my drill class there is operate functionwhich is doing the above thing, but problems occurs whenever drill is operating it is again making a new rover, so the rover x and y get null that time, so any can give me a potential fixes for that how can i use the existing rover in the drill function
public override void Operate(string ids)
{
Rover rov = new Rover();
if (specim.X == rov.X && specim.Y == rov.Y)
{
_wearfactor += 5;
Console.WriteLine("specimen extracted and wearfaction of drill is incresed by 5%");
Console.WriteLine(_wearfactor);
_spec. = 0;
}
if(specim.X != rov.X && specim.Y != rov.Y)
{
_wearfactor += 10;
Console.WriteLine("wear factor increased by 10%");
Console.WriteLine(_wearfactor);
}
if (_wearfactor == 100)
{
Console.WriteLine("Drill Destroyed");
Console.WriteLine("syart your program again");
Console.WriteLine("You can not drill specimen now");
this.Name = "";
}
}
You could change your Operate method's signature to:
public override void Operate(Rover rov, string ids)
then when you create Rover rov = new Rover(); you can pass it through for Operate to use.
Operate(rov, "ids");
Another option would be to make a public Rover object and directly reference it through Operate:
// assuming your main class is MainFunction
public class MainFunction()
{
public Rover rov { get; private set; }
public static void Main(string[] args)
{
// Establish the reusable rover
rov = new Rover();
// ...
}
}
Then in Operate, change all rov to MainFunction.rov
Related
I have to create a function that enables me to enter data for every customer in a hardware store. The data that I should enter for every customer is: first name, last name, product bought and its price. This data should be stored in an array. Have this function declare a 1D container, have the user initialise this 1D container with the above data, and have the function return this 1D container back to MAIN. In MAIN, invoke this function three times to create data for 3 customers.
Afterwards, I need to create another function that takes all three 1D containers of customer data from MAIN as parameters and adds up all the prices of the products they bought. Have this function return the total cost back to MAIN. (This is where I'm stuck.)
Lastly, I need to create a procedure that takes the total cost returned to MAIN as parameter and figures out if this total price(set to a simple integer) is a prime number:
if the value is prime, print: "Customers win the Price"
otherwise, print: "Customers won't get the price"
I am stuck on the second function, I tried to do a C-style for loop, but it doesn't work.
I tried to add these three prices as array positions with indices but nothing.
This is the code I have:
using System;
namespace ghghh
{
class Program
{
public static string [] inputData()
{
Console.WriteLine("Please enter your first name: ");
string FirstName = Console.ReadLine();
Console.WriteLine("Please enter your last name: ");
string LastName = Console.ReadLine();
Console.WriteLine("Please enter the product you ahve bought: ");
string product = Console.ReadLine();
Console.WriteLine("Please enter the price: ");
string price = Console.ReadLine();
string[] info = new string[4] { FirstName, LastName, product, price };
return info;
}
public static void sumOfPrice(string[] arr)
{
for(int i = 0; i<arr.Length; i++)
{
string sum = arr[i] + arr[i] + arr[i];
}
}
public static void isTotalCostPrime(int n)
{
if(n %2 == 0)
{
Console.WriteLine("Customers wont get get the prize.");
}
else
{
Console.WriteLine("Customers win the prize");
}
}
public static void Main (string[] args)
{
string[] final = inputData();
sumOfPrice(final);
}
}
}
Here you go with a partial solution to your problem. I made the prices decimal numbers (because most currencies are decimalized). That precludes your prime test at the end.
I also included a quantity. I was tempted to take out the first and last names for each item (since it requires a lot of typing). All in all, though, this should give you enough to get started.
I start with a POCO class to hold the purchased items (POCO stands for "Plain Old CLR Object"; it's a class that consists purely of properties. It's a bit like an old-fashioned C struct.
public class PurchasedItem
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string ProductName { get; set; }
public int Quantity { get; set; }
public decimal Price { get; set; }
}
I separated the user interface out into a separate class (for reasons of separation of concerns). You could easily collapse this into a single class:
public class ItemUserInterface
{
public static PurchasedItem PromptForItem()
{
var purchasedItem = new PurchasedItem();
Console.Write("What is your First Name (or type \"exit\" if complete)? > ");
var firstName = Console.ReadLine();
if (firstName.Equals("exit", StringComparison.OrdinalIgnoreCase))
{
return null;
}
purchasedItem.FirstName = firstName;
Console.Write("What is your Last Name? > ");
purchasedItem.LastName = Console.ReadLine();
Console.Write("What did you purchase? > ");
purchasedItem.ProductName = Console.ReadLine();
purchasedItem.Quantity = PromptForInteger("How many did you buy");
purchasedItem.Price = PromptForDecimal("What was the price");
Console.WriteLine(""); //empty line
return purchasedItem;
}
public static void ShowPurchase (PurchasedItem item)
{
Console.WriteLine($"{item.FirstName} {item.LastName} bought {item.Quantity} of {item.ProductName} at {item.Price} each");
}
public static int PromptForInteger(string prompt)
{
while (true)
{
Console.Write(prompt + " > ");
var entered = Console.ReadLine();
if (int.TryParse(entered, out var result))
{
return result;
}
//otherwise error
Console.WriteLine("Sorry, you must enter a proper integer value");
}
}
public static decimal PromptForDecimal(string prompt)
{
while (true)
{
Console.Write(prompt + " > ");
var entered = Console.ReadLine();
if (decimal.TryParse(entered, out var result))
{
return result;
}
//otherwise error
Console.WriteLine("Sorry, you must enter a proper decimal value");
}
}
}
By the way, while (true) will loop forever unless you do something like return or break out of the loop. Notice that I prompt the user over and over again until he/she enters a correctly formatted number (for the number entries).
Finally, here's my Main routine:
var itemsList = new List<PurchasedItem>();
while (true)
{
var item = ItemUserInterface.PromptForItem();
if (item == null)
{
break;
}
itemsList.Add(item);
}
// at this point, everything is entered
var totalPurchasePrice = 0.00m;
var totalItemsCount = 0;
foreach (var item in itemsList)
{
ItemUserInterface.ShowPurchase(item);
totalPurchasePrice += (item.Quantity * item.Price);
totalItemsCount += item.Quantity;
}
Console.WriteLine($"Purchase Summary: {itemsList.Count} different items ({totalItemsCount} total items) for {totalPurchasePrice:C}");
Console.ReadLine(); //pause
}
If I run this program the output looks like:
What is your First Name (or type "exit" if complete)? > Fly
What is your Last Name? > Dog57
What did you purchase? > Cabbage
How many did you buy > 2
What was the price > 1.99
What is your First Name (or type "exit" if complete)? > Fly
What is your Last Name? > Dog57
What did you purchase? > Hammer
How many did you buy > 6
What was the price > abc
Sorry, you must enter a proper decimal value
What was the price > 10.55
What is your First Name (or type "exit" if complete)? > exit
Fly Dog57 bought 2 of Cabbage at 1.99 each
Fly Dog57 bought 6 of Hammer at 10.55 each
Purchase Summary: 2 different items (8 total items) for $67.28
I want user to select from two options which will dictate what a single string says.
Eventually I will construct a sentence with the variables.
It may not make sense much and I'm totally new and doing this for my own enrichment. I know there is probably a lot better ways to construct this but I want to do most of it on my own as I can and have someone look at my finished project and explain what I could do and guide me at that point. First things first though.
I have a working version of this but it doesn't have IF statements with dual conditions. Also I have a class under the project for the construction of the variables and the main class program will generate the output.
class foodReport
{
public void appleSauce()
{
//apple sauce prompt
Console.WriteLine("Did you have apple sauce:");
Console.WriteLine("1. Yes");
Console.WriteLine("2. No");
//capture key
var KP = Console.ReadKey();
Console.Clear();
//yes no if statement
if (KP.Key == ConsoleKey.NumPad1)
{
int hr = 1;
}
if (KP.Key == ConsoleKey.NumPad2)
{
int hr = 2;
}
}
public void whatEaten()
{
//food prompt
Console.WriteLine("What did you eat:");
Console.WriteLine("1. Sandwich");
Console.WriteLine("2. Candy");
//capture key
var KP = Console.ReadKey();
Console.Clear();
//selection if statement
if (KP.Key == ConsoleKey.NumPad1)
{
string food = "A sandwich.";
}
if (KP.Key == ConsoleKey.NumPad2)
{
string food = "Some candy.";
}
}
public void outPut()
{
//WHERE IM HAVING TROUBLE
Console.WriteLine("Desert:");
Console.WriteLine("1. Cookie");
Console.WriteLine("2. Pie");
//capture key
var KP = Console.ReadKey();
Console.Clear();
//selection if statement
if (KP.Key == ConsoleKey.NumPad1 && hr = 1)
{
string report = "You had apple sauce. " + food + " Also, a cookie'";
}
if (KP.Key == ConsoleKey.NumPad2)
{
string report = "You did not have apple sauce. " + food + " Also, a pie'";
}
}
The if (KP.Key == ConsoleKey.NumPad1 && hr = 1) throws error
Operator && cannot be applied to operands of type bool and int
the if (KP.Key == ConsoleKey.NumPad1 && hr = 1) throws error Operator
&& cannot be applied to operands of type bool and int
try "==": if (KP.Key == ConsoleKey.NumPad1 && hr == 1)
So I want to make a list of names. I want this list to go on until user inputs 0 to quit, after user types 0 I want all names to be displayed. You probably see what I'm trying to do from the code below...that "typedName" is there just so you see what I'm trying to do.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<string> names = new List<string>();
Console.WriteLine("Type in 0 to end.");
bool over = false;
while (over != true)
{
names.Add(Console.ReadLine());
if(typedName == "0")
{
over = true;
}
}
Console.WriteLine("Entered names : ");
names.ForEach(Console.WriteLine);
Console.ReadLine();
}
}
}
First you need the typedName to be captured and then check if it is equal to 0.
if it is not add it to the list
List<string> names = new List<string>();
Console.WriteLine("Type in 0 to end.");
while (true)
{
var typedName = Console.ReadLine();
if (typedName.Equals("0"))
{
break;
}
names.Add(typedName);
}
Console.WriteLine("Entered names : ");
foreach(var name in names)
{
Console.WriteLine(name);
}
Console.ReadLine();
if(typedName == "0")
Well, what is typedName? Or what should it be? I suspect it should be the input entered by the user, something like this:
var typedName = Console.ReadLine();
You can then add it to the list by using that variable:
names.Add(typedName);
And compare it with "0" as you already do, etc.
your code is not complete that is why is not working...
you are missing the most important part:
populate the list if and only if typedName != "0"
while (!over)
{
var typedName =Console.ReadLine();
if(typedName == "0")
{
over = true;
}else
{
Console.WriteLine("Enter a name... ");
names.Add(Console.ReadLine());
}
...
}
I don't understand why I am getting an out of range error. Is my code set up improperly to have the array increase in size with each word entered? Note: I have some classes not shown here. Please tell me what I have to do in order to make the array increase by one every time a new word is entered.
class Program
{
static String[] Parse(String commandLine)
{
string[] stringSeparators = new string[] { "" };
String[] localList = new String[commandLine.Count((char f) => f == ' ') + 1];
localList = commandLine.Split(stringSeparators, StringSplitOptions.None);
return localList;
}
static void Main(string[] args)
{
Verb cVerb = new Verb(); //constructors begin here
Noun cNoun = new Noun();
Item itemName = new Item();
Player myPlayer = new Player();
String commandLine;
Room northRoom = new Room();
Room southRoom = new Room();
northRoom.setRoomDesccription("You stand in the center of the northern room. It smells musty");
southRoom.setRoomDesccription("You stand in the center of the southern room. It is made of crumbling stone");
myPlayer.setRoom(northRoom);
Console.WriteLine("Welcome young hero, to the world of Argandia");
while (cVerb.getName() != "Exit") // continue playing as long as verb entered =/ "exit"
{
//Room Description
myPlayer.getRoom().printDesc();
//Player Input
Console.WriteLine("You can now type a verb then a noun");
commandLine = Console.ReadLine();
int numWords = commandLine.Count((char f) => f == ' ') + 1;
String[] verbNounList = new String[numWords];
verbNounList = Parse(commandLine);
//process input
if (numWords > 0)
{
cVerb.setName(verbNounList[0]);
if (cVerb.getName() == "Exit")
{
Console.WriteLine("Thanks for playing\nSee you next time\nPress any key to exit...");
Console.ReadKey();
Environment.Exit(0);
}
if (numWords > 1)
{
cNoun.setName(verbNounList[1]);
}
if (numWords == 2)
{
}
else
{
Console.WriteLine("We are only able to support 2 words at this time, sorry\nPress any key to continue...");
}
}
}
}
}
Perhaps you should use a collection like List<string>. A dynamic alternative to an array:
public static IEnumerable<string> Parse(string commandLine)
{
foreach (var word in commandLine.Split(' '))
yield return word;
}
static void Main(string[] args)
{
string testCommandLine = "Hello World";
var passedArgs = Parse(testCommandLine);
foreach (var word in passedArgs)
{
//do some work
Console.WriteLine(word);
}
Console.Read();
}
I am creating an applicaiton that requires the use of recursive aggregation in one of the classes. The class at hand is entitiled "component" and a component may be made up of sub components stored within a list. The following code shows this.
public class Component {
//vars for class
public String componentName;
public String componentShape;
public String componentColour;
public String componentMaterial;
public int numChildComps;
//list to store child components of component
public List<Component> childComponents;
public Component(string _componentName, string _componentShape, string _componentColour, string _componentMaterial, int _numChildComps)
{
componentName = _componentName;
componentShape = _componentShape;
componentColour = _componentColour;
componentMaterial = _componentMaterial;
numChildComps = _numChildComps;
//if component has no child components set list to null
if (numChildComps == 0)
{
//instatiate new list
childComponents = new List<Component>();
childComponents = null;
}
else if(numChildComps != 0)//if not null then create child components for the amount stated above.
{
childComponents = new List<Component>();
for (int i = 0; i < numChildComps; i++)
{
Console.WriteLine("Add details for child component " + (i+1));
Console.WriteLine("Enter component Name: ");
string name = Console.ReadLine();
Console.WriteLine("Enter shape: ");
string shape = Console.ReadLine();
Console.WriteLine("Enter Colour: ");
string colour = Console.ReadLine();
Console.WriteLine("Enter Material: ");
string material = Console.ReadLine();
Console.WriteLine("Enter num child components: ");
string num = Console.ReadLine();
childComponents.Add(new Component(name, shape, colour, material, Int16.Parse(num)));//instatiate new child component with params and add to the list.
}
}
}
This will instaiated a class and if the parameter for number fo child components is more than 0 then it will create the object and store it in the list "childComponents". This works fine. My question is how would I go about retrieving the items within the list. Take the following as an example, I have a model which is made up of one component but that component has 2 components and one of those has another 2 and one of those has one component:
Model
-component
-childComponent
-childComponent
-childComponent
-childComponent
-childComponent
Obviously this could go on forever and I have tried creating a piece of code to retireve all the components and sub components but it has not worked as you need to know the total amount of components a model has and then that components childComponents and so on.
Code that I have tried(does not model the above example)
IEnumerable<SEModel> modelres = from SEModel sm in database
select sm;
foreach (SEModel item in modelres)
{
Console.WriteLine(item.getSetModelName);
Console.WriteLine(item.componentList.First().componentName);
foreach (SEComponent citem in item.componentList)
{
Console.WriteLine(citem.childComponents.First().componentName);
foreach (SEComponent scitem in citem.childComponents)
{
Console.WriteLine(scitem.componentName);
}
}
Like stated above you would have to know the amount of components with childcomponents and then their childcomponents and so on.
public IEnumerable<Component> GetComponents()
{
yield return this;
foreach( var childComp in childComponents )
{
foreach( var comp in childComp.GetComponents() )
{
yield return comp;
}
}
}
If you're not sure what yield return is all about, read this
If you need to retrieve the components as a flat list you can do it this way:
public List<Component> GetAllComponents(List<Component> components)
{
var result = new List<Component>();
result.AddRange(components);
foreach (var component in components)
result.AddRange(GetAllComponents(component.childComponents));
return result;
}
var allComponents = GetAllComponents(Model.Components);
Though I am not sure from your question what exactly you want to do.