Issue with object reference being required for the non-static field - c#

I have the below code and my issue is that when I reference the variables it gives me the error: an object reference is required for the non-static field, method, or property for each variable. I know it is something to do with my public int and public double being non static but I am not sure how to fix it. Could someone show me possibly?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace homework3
{
public class Program
{
public int number_of_scores;
public double score, total_score = 0, high_score, low_score, average;
}
class Class1{
static void Main(string[] args){
Console.Write("please enter the number of scores that you
wish to process? ");
Program.number_of_scores = int.Parse(Console.ReadLine());
Console.Write("Please enter score " + 1 + " ");
Program.score = double.Parse(Console.ReadLine());
Program.high_score = Program.score;
Program.low_score = Program.score;
Program.total_score = Program.total_score = Program.score;
for (int i = 2; i <= number_of_scores; i++);
}
}
class class2
{
static void Main(string[] args){
Console.Write("Please enter score " + i + " ");
Program.score = double.Parse(Console.ReadLine());
Program.total_score = Program.total_score + Program.score;
if(Program.score > Program.high_score)
Program.high_score = Program.score;
if(Program.score < Program.low_score)
Program.low_score = Program.score;
}
}
class Class3
{
static void Main(string[] args){
Program.average = Program.total_score / Program.number_of_scores;
Console.WriteLine("you entered " + Program.number_of_scores +
" scores");
Console.WriteLine("The high score is " + Program.high_score);
Console.WriteLine("The low score is " + Program.low_score);
Console.WriteLine("the average score is " + Program.average);
}
}

In the line:
Program.number_of_scores = int.Parse(Console.ReadLine());
you try to reference the instance variable number_of_scores from a static method.
The most trivial way to get that to work is to declare number_of_scores as static:
static public int number_of_scores;
Some of your other fields have the same issue.

You need to declare number_of_scores and score (and the other variables) as static.
public static int number_of_scores;
public static double score, //etc

Related

why is my code not letting me call the var Diceroll?

in VSC first i tried to return the variable uint PlayersDiceRoll but i kept getting a error about not being able to put Random.Next() in a static method or something like that, so i changed it and tried to call the method as a whole and am now getting a error saying the variable DiceRoll isnt in my code, so someone please help me.
using System;
namespace _Test_simplyVideoGame
{
//Change class name to video game title when it is known.
class Program
{
public void Main(string[] args)
{
PlayerDiceRoll(DiceRoll);
}
public uint PlayerDiceRoll(uint DiceRoll)
{
Random Dice = new Random();
uint PlayersDiceRoll = Convert.ToUInt32(Random.Next)(uint.MinValue,uint.MaxValue);
return DiceRoll;
}
}
}
Start by making your functions static
actually use the Random object
and if you only want positive random number I would just use int from 0 to max which is 2b values, if you need 4b possible options you could go from negative to possitive and then add the possitive, but you must make sure not to exceed the bounds of uint
static void Main(string[] args)
{
var playerRolled = PlayerDiceRoll();
Console.WriteLine("Player rolled: " + playerRolled);
Console.ReadLine();
}
public static int PlayerDiceRoll()
{
Random Dice = new Random();
var randomValue = Dice.Next(0, int.MaxValue);
return randomValue;
}
And just for a bit of fun:
You could make general dice if you need it:
static void Main(string[] args)
{
var playerRolled = PlayerDiceRoll();
Console.WriteLine("Player rolled: " + playerRolled);
Console.ReadLine();
Console.WriteLine("Player rolls default die: " + PlayerRoleSidedDie(6));
Console.ReadLine();
Console.WriteLine("Player rolls 64 value die die with 16 sides : " + PlayerRoleSidedDie(16,4));
Console.ReadLine();
Console.WriteLine("Player rolls two 6 sided dice");
var die1 = PlayerRoleSidedDie(6);
var die2 = PlayerRoleSidedDie(6);
Console.WriteLine("die 1 was: " + die1 + " die 2 was: " + die2 + " total roll was: " + (die1 + die2));
Console.ReadLine();
}
public static int PlayerDiceRoll()
{
Random Dice = new Random();
var randomValue = Dice.Next(0, int.MaxValue);
return randomValue;
}
public static int PlayerRoleSidedDie(int size, int multiplyer=1)
{
Random die = new Random();
var selectedSide = die.Next(1, size);
return selectedSide * multiplyer;
}
}

I'm trying to return out of a method but I get a CS0219 warning

I'm trying to return out of a method in C#, but every time I run the program I get a message that I'm creating a variable but never using it, then I get errors that the current variable does not exist in current context.
I am relatively new to C#, and I might be really dumb but if anyone can help me that will be great!
The code:
using System;
class MainClass
{
public static void Main()
{
int health = 3;
int powerCrystals = 0;
int healthCrystals = 0;
int basicEnemyDamage = 1;
int basicEnemyScore = 10;
string basicEnemyDrops = "1 powerCrystal";
int score = 0;
// Basic Enemies Drop 1 powerCrystal.
// Moderate Enemies Drop 1 powerCrystal and 1 healthCrystal.
// Advanced Enemies Drop 2 powerCrystals and 1 healthCrystal.
// Bosses Drop 3 powerCrystals and 3 healthCrystals.
Console.WriteLine("Input your username:");
string userName = Console.ReadLine();
Console.WriteLine("Welcome, " + userName);
Console.WriteLine("To check your stats, write: stats");
TrollFight();
}
static void TrollFight()
{
Console.WriteLine(userName + "! There is a pack of trolls aproaching! Guess the right number to kill them!");
Console.WriteLine("Your current health is = " + health);
Console.WriteLine("Guess the correct number and then you can defeat the trolls! It is between 1-9!");
int guessedNumber = Convert.ToInt32(Console.ReadLine());
if (guessedNumber == 4)
{
Console.WriteLine("You killed the trolls! You gained: " + basicEnemyDrops);
score = score + basicEnemyDamage;
Console.WriteLine("Your score is = " + score);
return;
}
else
{
Console.WriteLine("WRONG! You took damage! Come on, guess again!");
health = health - basicEnemyDamage;
}
int guessedNumber2 = Convert.ToInt32(Console.ReadLine());
if (guessedNumber2 == 4)
{
Console.WriteLine("You killed the trolls! You gained: " + basicEnemyDrops);
score = score + basicEnemyScore;
Console.WriteLine("Your score is = " + score);
return;
}
else
{
Console.WriteLine("WRONG! You took damage! Come on, guess again! Your health is = 2");
health = health - basicEnemyScore;
}
int guessedNumber3 = Convert.ToInt32(Console.ReadLine());
if (guessedNumber3 == 4)
{
Console.WriteLine("You killed the trolls! You gained: " + basicEnemyDrops);
score = score + basicEnemyDamage;
Console.WriteLine("Your score is = " + score);
return;
}
else
{
Console.WriteLine("WRONG! You took damage! Come on, guess again! Your health is = 1");
Console.WriteLine("You are almost dead! You do not have any Health Crystals so you can't heal!");
health = health - basicEnemyScore;
}
int guessedNumber4 = Convert.ToInt32(Console.ReadLine());
if (guessedNumber4 == 4)
{
Console.WriteLine("You killed the trolls! You gained: " + basicEnemyDrops);
score = score + basicEnemyScore;
Console.WriteLine("Your score is = " + score);
return;
}
else
{
Console.WriteLine("WRONG! You died! Your final score = " + score);
health = health - basicEnemyDamage;
}
Console.WriteLine("To check your stats, write: stats");
}
}
I'm trying to return out of a method but it gives me a CS0219 warning
Ok a few things. The difference between a Void/Subroutine and a Function is that a Function returns something. Both your methods are voids, they don't return anything:
public static void Main()
static void TrollFight()
The problem with the variables is that they are out of scope.
Local - visible within the method
Private - visible to the class
Public - visible outside the assembly
One solution is to make the variables Private member variables:
class MainClass {
private int health = 3;
private int powerCrystals = 0;
private int healthCrystals = 0;
private int basicEnemyDamage = 1;
private int basicEnemyScore = 10;
private string basicEnemyDrops = "1 powerCrystal";
private int score = 0;
public static void Main() {
Run the project, this should fix it. The problem with using Private variable scope is it can get messy when multiple methods can change variables (without the other knowing). In this case we can use parameters to pass variables to voids or functions:
TrollFight(basicEnemyDamage);
...
static void TrollFight(string basicEnemyDamage) {
A good design will use all three with local variables:
class MainClass {
private int health = 3;
private string basicEnemyDrops = "1 powerCrystal";
private int score = 0;
public static void Main() {
...
}
static void TrollFight(string basicEnemyDamage) {
int powerCrystals = 0;
int healthCrystals = 0;
int basicEnemyDamage = 1;
int basicEnemyScore = 10;
I'd even change the void to return the Score:
static int TrollFight(string basicEnemyDamage, int score)
{
return score;
}
The Code:
using System;
public class MainClass {
private int health = 3;
private int score = 0;
private int powerCrystals = 0;
private int healthCrystals = 0;
private int basicEnemyDamage = 1;
private int basicEnemyScore = 10;
private string basicEnemyDrops = "1 powerCrystal";
public static void Main() {
//Basic Enemies Drop 1 powerCrystal.
//Moderate Enemies Drop 1 powerCrystal and 1 healthCrystal.
//Advanced Enemies Drop 2 powerCrystals and 1 healthCrystal.
//Bosses Drop 3 powerCrystals and 3 healthCrystals.
Console.WriteLine("Input your username:");
string userName = Console.ReadLine();
Console.WriteLine("Welcome, " + userName);
Console.WriteLine("To check your stats, write: stats");
TrollFight(userName);
}
static void TrollFight(string userName) {
Console.WriteLine(userName + "! There is a pack of trolls approaching! Guess the right number to kill them!");
Console.WriteLine("Your current health is = " + health.ToString());
Console.WriteLine("Guess the correct number and then you can defeat the trolls! It is between 1-9!");
int guessedNumber = Convert.ToInt32(Console.ReadLine());
if (guessedNumber == 4)
{
Console.WriteLine("You killed the trolls! You gained: " + basicEnemyDrops);
score = score + basicEnemyDamage;
Console.WriteLine("Your score is = " + score.ToString());
return;
}
else
{
Console.WriteLine("WRONG! You took damage! Come on, guess again!");
health = health - basicEnemyDamage;
}
int guessedNumber2 = Convert.ToInt32(Console.ReadLine());
if (guessedNumber2 == 4)
{
Console.WriteLine("You killed the trolls! You gained: " + basicEnemyDrops);
score = score + basicEnemyScore;
Console.WriteLine("Your score is = " + score.ToString());
return;
}
else
{
Console.WriteLine("WRONG! You took damage! Come on, guess again! Your health is = 2");
health = health - basicEnemyScore;
}
int guessedNumber3 = Convert.ToInt32(Console.ReadLine());
if (guessedNumber3 == 4)
{
Console.WriteLine("You killed the trolls! You gained: " + basicEnemyDrops);
score = score + basicEnemyDamage;
Console.WriteLine("Your score is = " + score.ToString());
return;
}
else
{
Console.WriteLine("WRONG! You took damage! Come on, guess again! Your health is = 1");
Console.WriteLine("You are almost dead! You do not have any Health Crystals so you can't heal!");
health = health - basicEnemyScore;
}
int guessedNumber4 = Convert.ToInt32(Console.ReadLine());
if (guessedNumber4 == 4)
{
Console.WriteLine("You killed the trolls! You gained: " + basicEnemyDrops);
score = score + basicEnemyScore;
Console.WriteLine("Your score is = " + score.ToString());
return;
}
else
{
Console.WriteLine("WRONG! You died! Your final score = " + score.ToString());
health = health - basicEnemyDamage;
}
Console.WriteLine("To check your stats, write: stats");
}
}

C# Using objects in other classes and displaying them *REVISED

I am having trouble display the object's properties and transferring them between classes. I am also having trouble getting the error message from the set methods. It seems I can enter anything without getting an error. I know the problem might have something in the object because I am just getting blank variable names when I try to display it.
namespace Project
{
class Program
{
static void Main(string[] args)
{
string name;
double strength = 0;
double dexterity = 0;
double hitPoints = 0;
double armor = 0;
Console.WriteLine("--WELCOME TO THE BATTLE--\n");
Console.WriteLine("Please enter the statistics for warrior one.");
Console.WriteLine("Name: ");
name = Console.ReadLine();
Console.WriteLine("Strength: ");
strength = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Dexterity: ");
dexterity = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Hit Points: ");
hitPoints = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Armor: ");
armor = Convert.ToDouble(Console.ReadLine());
Warrior warriorOne = new Warrior(name, strength, dexterity, hitPoints, armor);
Console.WriteLine("\nPlease enter the statistics for warrior two.");
Console.WriteLine("Name: ");
name = Console.ReadLine();
Console.WriteLine("Strength: ");
strength = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Dexterity: ");
dexterity = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Hit Points: ");
hitPoints = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Armor: ");
armor = Convert.ToDouble(Console.ReadLine());
Warrior warriorTwo = new Warrior(name, strength, dexterity, hitPoints, armor);
Console.WriteLine("\nWarriors:\n" + warriorOne.Name + "--" + "Strength " + warriorOne.Strength + ", Dexterity " + warriorOne.Dexterity + ", HitPoints " + warriorOne.HitPoints + ", Armor " + warriorOne.Armor);
Console.WriteLine("\nWarriors:\n" + warriorTwo.Name + "--" + "Strength " + warriorTwo.Strength + ", Dexterity " + warriorTwo.Dexterity + ", HitPoints " + warriorTwo.HitPoints + ", Armor " + warriorTwo.Armor);
Battlefield.Battle(warriorOne, warriorTwo);
}
}
class Warrior
{
private double strength;
private double dexterity;
private double hitPoints;
private double armor;
public Warrior(string name, double strength, double dexterity, double hitPoints, double armor)
{
name = Name;
this.strength = Strength;
this.dexterity = Dexterity;
this.hitPoints = HitPoints;
this.armor = Armor;
}
public string Name { get; set; }
public double Strength
{
get
{
return strength;
}
set
{
while (value < 10 & value > 20)
{
Console.WriteLine("Strength has a range of 10-20. Please re-enter: ");
value = Convert.ToDouble(Console.ReadLine());
}
strength = value;
}
}
public double Dexterity
{
get
{
return dexterity;
}
set
{
while (value < 10 & value > 20)
{
Console.WriteLine("Dexterity has a range of 10-20. Please re-enter: ");
value = Convert.ToDouble(Console.ReadLine());
}
dexterity = value;
}
}
public double HitPoints
{
get
{
return hitPoints;
}
set
{
while (value < 10 & value > 20)
{
Console.WriteLine("Hit points have a range of 10-20. Please re-enter: ");
value = Convert.ToDouble(Console.ReadLine());
}
hitPoints = value;
}
}
public double Armor
{
get
{
return armor;
}
set
{
while (value < 0 & value > 5)
{
Console.WriteLine("Armor has a range of 0-5. Please re-enter: ");
value = Convert.ToDouble(Console.ReadLine());
}
armor = value;
}
}
}
class Battlefield
{
public static void Battle(Warrior warriorOne, Warrior warriorTwo)
{ Console.WriteLine(warriorOne.Name); }
}
One problem is with your Warrior class, in the constructor where you try to set the Name property. You have this (I've only included the relevant bits):
public Warrior(string name)
{
name = Name;
}
public string Name { get; set; }
Notice that you're NOT setting the Name property here. You are setting the argument name to whatever the Name property is (which is probably null).
To fix this, just switch the order around the assignment:
public Warrior(string name)
{
Name = name;
}
You might want to check all your other properties as well (it looks like this was a common mistake, where you have the property you're trying to set on the right side of the = instead of the left).
Remember you should almost always assign to the public accessor (the capitalized one), so your set code runs. Try not to modify the private backing field except from the property set method.

Method being run through twice when it should only run once

class Myclass
{
public string Driver1()
{
string a = "";
Console.Write("Please enter drivers name: ");
a = Console.ReadLine();
return a;
}
public int numberOfTrips()
{
int a = 0;
{
Console.Write("Enter the number of trips: ");
a = Convert.ToInt32(Console.ReadLine());
}
return a;
}
public List<float> Payments()
{
List<float> a = new List<float>();
float input;
for (int i = 0; i<numberOfTrips(); i++)
{
Console.Write("Enter payment {0}: ", (1 + i));
input = float.Parse(Console.ReadLine());
Console.WriteLine("Payment added");
a.Add(input);
}
return a;
}
}
class Program
{
static void Main(string[] args)
{
Myclass a = new Myclass();
string name = a.Driver1();
int trip = a.numberOfTrips();
float total = a.Payments().Sum();
Console.WriteLine("\nDriver: {0}\n" + "Number of trips: {1}\n" + "Total payment: {2}\n", name, trip, total);
}
}
The issue i am having is that the "public int numberOfTrips()" method is running twice before it gets to the method containing the for loop. I think this is to do with the fact i am using it within the for loop to specify when the loop should stop. I am guessing i have done this wrong so how would i correct this? I need the user to be able to set the how many times it will ask for payment.
Any help is appreciated.
Just pass the number from numberOfTrips as a parameter to Payments:
public List<float> Payments(int tripCount)
{
List<float> a = new List<float>();
float input;
for (int i = 0; i < tripCount; i++)
{
Console.Write("Enter payment {0}: ", (1 + i));
input = float.Parse(Console.ReadLine());
Console.WriteLine("Payment added");
a.Add(input);
}
return a;
}
In your Main method:
Myclass a = new Myclass();
string name = a.Driver1();
int trip = a.numberOfTrips();
float total = a.Payments(trip).Sum();
Instead of calling numberOfTrips() in Main() as well as in Payments() you might try creating an instance variable or static variable in MyClass. Then you can fetch the number of trips from that variable after all payments are calculated.
That is correct. The first time it runs is in Main to set the 'trip' variable. The second time it runs is in Payments, inside the for loop declaration.

C# launch a program with mandatory parameters and optional parameters from cmd

I need to call a program from cmd using an array of numbers(mandatory) and an int time(optional). I have never done this so i'm a bit shaky on the details.
The path is D:\Robert\FactorialConsoleApplication\FactorialConsoleApplication\bin\Debug\FactorialConsoleApplication.exe
As you can tell, the program calculates the factorial of the numbers in the array. The int time is used as a delay in order to display the progress of the stack.
How do I call the program with parameters?
Thanks in advance!
P.S. Here is some of the code
class Program
{
public static void Progress(ProgressEventArgs e)
{
int result = e.getPartialResult;
int stack_value = e.getValue ;
double max = System.Convert.ToDouble(numbers[j]);
System.Convert.ToDouble(stack_value);
double percent = (stack_value / max) * 100;
Console.CursorLeft = 18;
Console.Write(result + " ");
Console.CursorLeft = 46;
Console.Write(System.Convert.ToInt32(percent) + "% ");
}
public static void Calculate(int number, int time=0)
{
Factorial Fact = new Factorial();
Fact.Progression += new Factorial.ProgressEventHandler(Progress);
Console.Write("\n" + "Partial results : ");
Console.CursorLeft = 35;
Console.Write("Progress : ");
int Result = Fact.CalculateFactorial(number, time);
Console.WriteLine(" ");
Console.WriteLine("The factorial of " + number + " is : " + Result);
Console.ReadLine();
}
static int j;
static int[] numbers;
public static void Main(string[] args)
{
int i=0;
bool ok = false;
string line = string.Empty;
numbers = new int[10];
Console.Write("Please insert wait time (0,1 or 2) : ");
int time = int.Parse(Console.ReadLine()) * 1000;
Console.Write("Please insert a number : ");
do
{
line = Console.ReadLine();
if (line != "")
{
i++;
numbers[i] = int.Parse(line);
}
else
{
ok = true;
}
}
while (ok == false);
for (j = 1; j <= i; j++)
{
Calculate(numbers[j],time);
}
}
}
In .net you can use Process.Start from System.Diagnostics to launch an application, you can pass parameters too
For example Process.Start("IExplore.exe", "C:\\myPath\\myFile.htm"); will open Internet Explorer and pass the value "C:\\myPath\\myFile.htm" as parameter to it.For more examplles check the MSDN article on Process.Start method
Update
If in case you are looking to take parameters to your application, when launching itself you don't have to do anything, you are already doing that, the parameter args in your Main method will hold the arguments passed to your application, just try and parse those values in the args array to int array and you are good to go.
Ok, so here is the solution.
I used an args parser like this :
static int extra;
public static void Main(string[] args)
{
foreach (string s in args)
{
extra = int.Parse(s);
Calculate(extra);
}
}
And I changed :double max = System.Convert.ToDouble(numbers[j]);
to :double max = System.Convert.ToDouble(extra);
To call it I open cmd in the directory where the exe is and I type :
Program.exe 3 4 5
It will calculate the factorials of 3, 4 and 5 respectively

Categories