I'm working on an assignment for school that consists of both a Program.cs file and a separate class called Car. I have written all code for the Car class and pasted already provided code into the program.cs file. The resulting output is
2010 Ford Focus is going 20 MPH.
2018 Chevy Cruze is going 0 MPH.
The assignment calls for an expected output of
2010 Ford Focus is going 28 MPH.
2018 Chevy Cruze is going 18 MPH.
I need to know how to get the window to output the expected speed of 28 for Car 1 and 18 for car 2. I'm assuming that I'm not supposed to alter the code that was provided for program.cs to accomplish the right output for the application/assignment.
public class Car
{
private int Speed;
private string Make;
private string Model;
private int Year;
public Car (string make, string model, int year, int speed)
{
this.Make = make;
this.Model = model;
this.Year = year;
this.Speed = speed;
}
public Car(string make, string model, int year)
{
this.Make = make;
this.Model = model;
this.Year = year;
this.Speed = 0;
}
public int SpeedUp()
{
this.Speed = Speed++;
return (Speed);
}
public int SlowDown()
{
if (Speed > 0)
{
this.Speed = Speed--;
}
return (Speed);
}
public void Display()
{
Console.WriteLine(Year + " " + Make + " " + Model + " is going " + Speed + " MPH.");
Convert.ToString(Console.ReadLine());
}
}
and here is the given code that goes in program.cs
class Program
{
static void Main(string[] args)
{
int car1Speed = 20;
int car2Speed = 0;
Car car1 = new Car("Ford", "Focus", 2010, car1Speed);
Car car2 = new Car("Chevy", "Cruze", 2018, car2Speed);
for (int i = 0; i < 60; i++)
{
if (i % 2 == 0)
{
car2Speed = car2.SpeedUp();
}
if (i % 3 == 0)
{
car1Speed = car1.SpeedUp();
}
if (i % 5 == 0)
{
car1Speed = car1.SlowDown();
car2Speed = car2.SlowDown();
}
}
car1.Display();
car2.Display();
}
}
The line of code
this.Speed = Speed++;
Has no effect on the value of this.Speed.
The line of code is roughly equivalent to
int temp = this.Speed; // We store the original value of Speed.
this.Speed = Speed + 1; // We add one to Speed and assign it back to Speed.
this.Speed = temp; // We immediately replace Speed with the original value of Speed.
This is the due to the behavior of the '++' operator which, when appended to the end of a variable will add 1 to its current value and then assigns the result back to the variable. This operator however temporarily stores the original value and uses that as the result of the expression. This temporary result of the ++ operator is ultimately what you are assigning to this.Speed due to the '=' operator you're using in the same expression, this in turn is what is causing the variable to not actually be modified.
The correct usage would be to simply call
Speed++;
This will perform the addition of 1 and assignment back to Speed, and also discard the temporary variable, as it is not being assigned anywhere.
This issue also exists in your SpeedDown method with the '--' operator.
In your Car.cs class, here is a better way to increment the speed without modifying the Program.cs file:
public int SpeedUp()
{
this.Speed += 1;
return (Speed);
}
public int SlowDown()
{
if (Speed > 0)
{
this.Speed -= 1;
}
return (Speed);
}
That produces the output that you're after.
Related
I am working on a school project and I am stuck. I am trying to get some info from the user and calculate a few things with the inputted information from the user.
I had my code running, but my teacher told me I needed to replace the calculations to my logic layer (they were in my controller). I am trying to do that, but I am stuck.
This is my controller:
public class CalculatorController : Controller
{
// GET: Calculator
public ActionResult PackCalculator()
{
return View(new CalculatorModel());
}
[HttpPost]
public ActionResult PackCalculator(CalculatorModel calculator)
{
CalculatorLogic x = new CalculatorLogic();
int Y = x.calculator(new CalculatorModel());
return View(calculator);
}
And this is the class in the logic layer:
namespace ApexLogic
{
public class CalculatorLogic
{
public int calculator(CalculatorModel calculator)
{
if (calculator.CurrentLevel < 21)
{
calculator.CurrentPack = calculator.CurrentPack + (calculator.CurrentLevel - 1);
int seizoenPacks = calculator.PlayedSeasons * 5;
int BattlepassPacks = calculator.Battlepass * 12;
int CurrentPack = calculator.CurrentPack + seizoenPacks + BattlepassPacks + calculator.BoughtPacks;
return CurrentPack;
}
else if (calculator.CurrentLevel > 21 && calculator.CurrentLevel < 301)
{
int CurrentLevelPack = calculator.CurrentLevel - 20;
int PackCalculator2 = (calculator.CurrentLevel / 2);
int CurrentLevelPack2 = PackCalculator2 + 19;
int seizoenPacks = calculator.PlayedSeasons * 5;
int BattlepassPacks = calculator.Battlepass * 12;
calculator.CurrentPack = calculator.CurrentPack + seizoenPacks + BattlepassPacks +
calculator.BoughtPacks + CurrentLevelPack2;
return calculator.CurrentPack;
}
else if (calculator.CurrentLevel > 300 && calculator.CurrentLevel <= 500)
{
int CurrentLevelPack = calculator.CurrentLevel - 300;
int PackCalculator2 = (CurrentLevelPack / 5);
int CurrentLevelPack2 = PackCalculator2 + 159;
int seizoenPacks = calculator.PlayedSeasons * 5;
int BattlepassPacks = calculator.Battlepass * 12;
calculator.CurrentPack = calculator.CurrentPack + seizoenPacks + BattlepassPacks +
calculator.BoughtPacks + CurrentLevelPack2;
return calculator.CurrentPack;
}
else
{
return 0;
}
}
}
When I try and use the breakpoint to see where it goes wrong I can see that the input from the user is being directed correctly to the class, but my calculations are not being done and I always get 0 returned back. I have no idea what to do now (usually I get it fixed with breakpoints, but they are not helping me)
The user input
It is handled correctly as you can see
But my Y in the controller always stays zero.
It makes no difference if I use the way of return like in the first If statements or if I use the way of return in the second or third if statement.
Can someone help me?
You are passing a new CalculatorModel into your call to your application logic class:
int Y = x.calculator(new CalculatorModel()); //This is what is messing you up
Change it to this:
int Y = x.calculator(calculator); //Use the model parameter which is passed into your Post method
Your model was null , First you must fill your model. Change your code like this,
[HttpPost]
public ActionResult PackCalculator(CalculatorModel calculator)
{
CalculatorLogic x = new CalculatorLogic();
int Y = x.calculator(new CalculatorModel());
return View(calculator);
}
[HttpPost]
public ActionResult PackCalculator(CalculatorModel calculator)
{
CalculatorLogic x = new CalculatorLogic();
var model = new CalculatorModel(){
CurrentLevel = 12,
CurrentLevelPack = 10 .....
};
int Y = x.calculator(model);
return View(calculator);
}
I have a timer that runs in the background and at the end of the level i want to show the leaderboard. i want to take this timer and convert it to 00:00 format 00 (Minutes) : 00 (Seconds) (i.e 01:40). How is that possible? I just need to do the calculations and the convertion when the Level ends.
This is what i have now. i start the timer normally
void Update()
{
if(timerIsRunning)
{
mainGameTimer += Time.deltaTime;
}
}
and now to add the timer in the 00:00 format i need to pass it as float but read it as string in the leaderboard
public void ShowResult()
{
int min = Mathf.FloorToInt(mainGameTimer / 60);
int sec = Mathf.FloorToInt(mainGameTimer % 60);
users.Add(new User(userName, score , timeScore));
users.Sort(delegate (User us1, User us2)
{ return us2.GetScore().CompareTo(us1.GetScore()); });
int max = users.Count <= 10 ? users.Count : 10;
for (int i = 0; i < max; i++)
{
//leaderListName[i].text = users[i].GetName() + "- " + users[i].GetScore() + "-" + Mathf.RoundToInt(users[i].GetTimeScore()) + "Sec";
leaderListName[i].text = users[i].GetName();
leaderListscore[i].text = users[i].GetScore().ToString();
leaderListtime[i].text = users[i].GetTimeScore().ToString();
}
}
class User
{
string name;
int score;
float timeScore;
public User(string _name, int _score , float _timeScore)
{
name = _name;
score = _score;
timeScore = _timeScore;
}
public string GetName() { return name; }
public int GetScore() { return score; }
public float GetTimeScore() { return timeScore; }
}
Instead of doing your own calculations you can use TimeSpan to convert to a time format. Input will need to be of type double:
double mainGameTimerd = (double)mainGameTimer;
TimeSpan time = TimeSpan.FromSeconds(mainGameTimerd);
string displayTime = time.ToString('mm':'ss");
This is the piece of code I usually use
//Calculate the time in minutes and seconds.
int minutes = (int)levelDuration / 60;
int seconds = (int)levelDuration % 60;
//Update the duration text.
durationText.text = minutes.ToString() + ":" + ((seconds < 10) ? ("0") : ("")) + seconds.ToString();
I have a very simple C# program, with several switch cases.
Every case uses the same function with the only difference variable value - that is, everything is hard-coded. Not pretty but it works.
Instead of repeating the same function, i tried to define classes/methods which is called instead. But it does not work as intended.
First, in my program I declare the following variables;
int hp = 100;
int gold = 10;
Then I have a switch/cases with the following (part of) function;
int monster2 = 10;
gold = gold - 2;
while (monster2 > 0 && hp > 0)
{
int dmgdone = rnd.Next(5, 15);
Console.WriteLine("You deal " + dmgdone);
monster2 = monster2 - dmgdone;
int dmg = rnd.Next(1, 10);
Console.WriteLine("You take " + dmg);
hp = hp - dmg;
if (monster2 <= 0)
{
Console.WriteLine("Monster is slain");
gold = gold + 1;
}
if (hp <= 0)
{
Console.WriteLine("You where killed");
}
}
Console.ResetColor();
break;
Point is that the function adjust the variables hp and gold, and when the function ends, the user gets back to the beginning of the switch function with "correct" value of hp and gold.
I did try to write class/methods with the same function for every switch cases with the correct parameter value for the methods. However, the variable value of hp and gold is constantly 100 and 10 when using this method, it doesnt get changed in the main method. How do I change the variables in the main method, from the functions/methods in a different class?
Here is how I did the new solution;
I called the method with;
loc.goToLocation1();
and here is the class for the above;
class location1
{
public void useYourSword(int hp, int gold, string name, string age)
{
Random rnd = new Random();
int monster = 10;
gold = gold - 1;
while (monster > 0 && hp > 0)
{
int dmgdone = rnd.Next(1, 10);
Console.WriteLine("You deal " + dmgdone);
monster = monster - dmgdone;
int dmg = rnd.Next(1, 10);
Console.WriteLine("You take " + dmg);
hp = hp - dmg;
if (monster <= 0)
{
Console.WriteLine("Monster is slain");
gold = gold + 1;
}
if (hp <= 0)
{
Console.WriteLine("You where killed");
}
}
Console.ResetColor();
}
}
primitive variables of the type int or float are what are called value types, which means that the variable refers to the value of those items, and if you copy the variable, or pass it to a function, you copy the data it contains.
There are also reference types, like instances of classes(AKA objects) where the variable refers to an address, and that address points to the data. In these cases, there is only one set of data per object, and when you copy the variable or pass it to a function, you only copy the address which points to the same data.
So, if you had a class for Player, and you passed the player to your method, and you changed it's HP, you would be able to observe that change from your caller method
Example:
public class Player
{
public int HP{get; set;}
public Player()
{
HP = 100;
}
}
...
public static void Main(string[] args)
{
Player player = new Player();
reduceHP(player);
Console.WriteLine("HP: {0}, player.HP);
}
public static void reduceHP(Player player)
{
player.HP -= 10;
}
of course, you can also use the ref and out keywords, but it's not a very good design to use them unless they're really needed
Even though you definetely shouldn't use OOP (i.e. working with classes and objects) like that, you could use references. It would work like that:
internal static class P
{
private static void Main ()
{
int hp = 100;
int gold = 10;
Console.WriteLine("Before:");
Console.WriteLine($"\tHP: {hp}\n\tGold: {gold}\n");
location1 loc1 = new location1();
loc1.useYourSword(ref hp, ref gold, "", "");
Console.WriteLine("After:");
Console.WriteLine ($"\tHP: {hp}\n\tGold: {gold}");
Console.ReadLine ();
}
}
class location1
{
public void useYourSword (ref int hp, ref int gold, string name, string age)
{
Random rnd = new Random ();
int monster = 10;
gold = gold - 1;
while (monster > 0 && hp > 0)
{
int dmgdone = rnd.Next (1, 10);
Console.WriteLine ("You deal " + dmgdone);
monster = monster - dmgdone;
int dmg = rnd.Next (1, 10);
Console.WriteLine ("You take " + dmg);
hp = hp - dmg;
if (monster <= 0)
{
Console.WriteLine ("Monster is slain");
gold = gold + 1;
}
if (hp <= 0)
{
Console.WriteLine ("You where killed");
}
}
Console.ResetColor ();
}
}
Which results in:
Before:
HP: 100
Gold: 10
You deal 5
You take 8
You deal 4
You take 2
You deal 5
You take 1
Monster is slain
After:
HP: 89
Gold: 10
I'm very new to C# and have a very limited understanding of the "proper code" to use. I had the goal to imitate the old Pokemon battle systems as best I could with what I know and am having a hard time linking a stored int value for HP between two methods (assuming that's the right word), to calculate new Hp when the second method interacts with the main method. Had a hard time finding an answer for that in searches so here is the code:
" static void Main(string[] args)
{
Random Gen = new Random();
int enemyhealth = (150);
int playerhealth = (100); //the line i need to use
int edefense = (20);
int pattack = (30);
int rate = Gen.Next(1,5);
int critical = 0; "
static void enemyattack()
{
Random Gen1 = new Random();
int pdefense = (20);
int eattack = (20);
int erate = Gen1.Next(1, 5);
int ratattack = Gen1.Next(1,3);
int critical1 = 0;
Console.WriteLine("Enemy Ratta gets ready!");
Console.ReadKey();
Console.WriteLine("----------------------------------------------------------------------------");
Console.WriteLine("\nEnemy Ratta attacks!\n");
Console.WriteLine("----------------------------------------------------------------------------");
ratattack = Gen1.Next(1,3);
if (ratattack = 1)
{
Console.WriteLine("Enemy Ratta used Tail Whip!");
pdefense = (pdefense - erate);
Console.ReadKey();
Console.WriteLine("----------------------------------------------------------------------------");
erate = Gen1.Next(1, 5);
if (erate <= 3)
{
Console.WriteLine("\nIt wasn't very effective!");
}
else
{
Console.WriteLine("\nIt was super effective!");
}
Console.WriteLine("Squirtle's Defense decreased by " + erate + "");
Console.WriteLine("----------------------------------------------------------------------------");
}
else if (ratattack == 2)
{
Console.WriteLine("\nRatta used Tackle");
erate = Gen1.Next(1, 5);
if (erate >= 5)
{
Console.WriteLine("----------------------------------------------------------------------------");
Console.WriteLine("----------------------------------------------------------------------------");
Console.WriteLine("\nCRITICAL HIT!!!!");
Console.WriteLine("----------------------------------------------------------------------------");
Console.WriteLine("----------------------------------------------------------------------------\n");
Console.ReadKey();
Console.WriteLine("It was super effective!");
Console.ReadKey();
eattack = eattack + 10;
}
else
{
critical1 = Gen1.Next(1, 5);
eattack = critical1 + eattack;
}
phealth = Math.Abs((eattack - pdefense) - playerhealth); ***//This Line is where I'm having trouble because phealth is used in my first method as a stored integer and the new calculation for phealth won't interact with the phealth in the origional main, i simply belive I haven't learned that part of c#, I only have 5 hours of youtube tutorials.***
Console.WriteLine("Ratta dealt " + Math.Abs(eattack - pdefense) + " damage!");
eattack = 30;
Console.WriteLine("\n----------------------------------------------------------------------------");
Console.ReadKey();
Console.ReadKey();
}
}
}
}
Make Static method , or simply add your variable in the main Class (where Main method Stored)
Here example
class Program
{
int HP;
int Main()
{
HP=0; //Now you HP is 0;
Method();
}
void Method()
{
HP+=50; //Now you HP is 50
}
}
I would break things down into separate classes. For example you should have a Player class that contains all the information for the player. You can't have methods like that in your main program. You need to keep everything separate. Make a class for each object you need.
public class Player
{
int currentHp = 100;
int maxHp = 100;
int atkPower = 20;
int defense = 20;
string playerName = "Ashe"
public Player() {}
public void TakeDamage(int damage)
{
currentHp = currentHp - damage;
}
}
public class Enemy
{
int currentHp = 100;
int maxHp = 100;
int atkPower = 20;
int defense = 20;
string enemyName= "Rattata"
public Enemy(){}
public int AttackPlayer(Player player)
{
// all of your attack logic, pass in the player here
player.TakeDamage(someAmountofDamage);
}
}
Then in your main program:
static void Main(string[] args)
{
Player myPlayer = new Player();
Enemy myEnemy = new Enemy();
myEnemy.AttackPlayer(player);
}
I have this in my main:
static void Main(string[] args)
{
Money m1 = new Money(2315.99);
Money m2 = new Money(4000, 25);
Console.WriteLine(m1);
Console.WriteLine(m2);
Console.WriteLine(m1.IncrementMoney(m2));
}
public void IncrementMoney(Money x)
{
//what do I put in here?
}
So
Money m1 = new Money(2315.99); is supposed to turn 2315.99 into "$2315.99"
and
Money m2 = new Money(4000, 25); forms "$4000.25"
I have all that done in Money class and it works fine.
Now what I'm supposed to do is add those two together using
m1.IncrementMoney(m2);
This is my "Money" class
class Money
{
//instance variables
private int dollars;
private int cents;
double amount;
public int Dollars
{
get { return dollars; }
set
{
if (value > 0)
dollars = value;
}
}
public int Cents
{
get { return cents; }
set
{
if (value > 0)
cents = value;
}
}
public Money(int Dol, int Cen)
{
Dollars = Dol;
Cents = Cen;
double Dollar = Convert.ToDouble(Dollars);
double Cent = Convert.ToDouble(Cents);
amount = Dollar + (Cent / 100);
}
public Money(double am)
{
int dol = Convert.ToInt32(am);
if (dol > am)
Dollars = dol - 1;
else if (dol < am)
Dollars = dol;
//Dollars
double cen = am % 1;
cen = cen * 100;
Cents = Convert.ToInt32(cen);
//Cents
double Dollar = Convert.ToDouble(Dollars);
double Cent = Convert.ToDouble(Cents);
amount = Dollar + (Cent / 100);
}
//override ToString()
public override string ToString()
{
return string.Format("{0:c}", amount);
}
}//end class Money
But I have no idea what to put into the IncrementMoney method. Please help?
and if not too much trouble, maybe a little insight to how it works? I'd really like to know.
Sorry if I didn't give enough info,
If anything else is required please let me know.
and thanks!
Since IncrementMoney is supposed to add the two money values together, your usage looks like it should instead be an extension method of the Money type. Which is fine, because extension methods are pretty awesome. A common joke on this site is that they're the solution to everything.
Your code should look similar to:
public static Money IncrementMoney(this Money x, Money y)
{
var totalCents = x.Cents + y.Cents;
var retCents = totalCents / 100;
var retDollars = x.Dollars + y.Dollars + (totalCents % 100)
return new Money(retDollars, retCents);
}
As for a quick explanation...
By adding this to the first argument, we are telling C# that we want to write an extension method. This will mean that this method we're writing will hang off the type of the this argument (in this case, Money) and allow us to use it exactly like it was always in the .NET framework. Extension methods have to be static, so you can't not use that modifier. Beyond that, you just write a method to do whatever you have in mind, exactly like you normally would!
I would suggest you name it something other than IncrementMoney, though. That's not very descriptive. AddMoney would be better.
You may also look into operator overloading, by the way. You could adapt what I just wrote to simply use the + operator to do exactly the same thing, like so:
public static Money operator +(Money x, Money y)
{
var totalCents = x.Cents + y.Cents;
var retCents = totalCents / 100;
var retDollars = x.Dollars + y.Dollars + (totalCents % 100)
return new Money(retDollars, retCents);
}
With this defined, you can simply go m1 + m2 and add them together.
public void IncrementMoney(Money x)
{
this.Dollars += x.Dollars;
var newCents = this.Cents + x.Cents;
this.Cents = newCents % 100;
this.Dollars += newCents / 100;
}
And I would actually name the function Add since you are taking the current value and adding the provided value, and no need for the Money modifier as it should be on the Money class and takes a Money object
Well first of all this line:
Console.WriteLine(m1.IncrementMoney(m2));
indicates that IncrementMoney should return something, but right now it returns void.
So it looks like it should be something like:
public void IncrementMoney(ClassA x)
{
this.Value += x.Value;
}
And then display it with:
ClassA m1 = new ClassA(2315.99);
ClassA m2 = new ClassA(4000, 25);
Console.WriteLine(m1);
Console.WriteLine(m2);
m1.IncrementMoney(m2);
Console.WriteLine(m1);