I have made a programm in c#.
In the code I've made an int called: Paying
but when I try to give it a value, it says the following error:
An object reference is required for the non-static field, method or
property
'Mc_Donalds.Program.Paying'
any suggestions on what I should do?
public int Paying;
// Select what meal you want
Console.WriteLine("To order please type the number infront of the item.");
int Keuze = Convert.ToInt32(Console.ReadLine());
if (Keuze == 1)
{
Paying = 5;
}
else if (Keuze == 2)
{
Paying = 3.50;
}
else if (Keuze == 3)
{
Paying = 1;
}
else if (Keuze == 4)
{
Paying = 6;
}
I'd think your method that does this is static while your int (Paying is not)
There are two ways with which you can access a variable in object oriented world
You should create an object for the class where you declare this variable or make this Field a static field.
The variable in question is Paying.
try to change the declaration of Paying from public int Paying; to something like this
public static int Paying;
Then use it as Program.Paying = 5 or Program.Paying = 3.5 etc assuming your class name in Program
Related
This question already has an answer here:
c# calling method with array parameters [closed]
(1 answer)
Closed 1 year ago.
My code looks like this:
void Update()
{
if (Input.GetKeyDown(KeyCode.G) && questCount == 6)
{
Score(sumFinal);
}
}
public int Score(int sumFinal)
{
sumFinal = dCount - rCount;
return sumFinal;
}
Visual Studio tells me sumFinal doesn't exist in the current context.
How can I return sumFinal within Update() successfully? Am I understanding parameters correctly?
Additional Question:
Below further down the Score() function, I set text to certain values:
public int Score(int sumFinal)
{
sumFinal = dCount - rCount;
return sumFinal;
if (sumFinal == 5 && questCount >= 5)
{
labelText.text = "results";
}
}
When calling this function in Update(), is there a way I can run both the if statement and the sumFinal subtraction equation separately? In short, how do I segment the function, and call only specific parts of it? Should the return type be set to void?
Visual Studio tells me sumFinal doesn't exist in the current context. How can I return sumFinal within Update() successfully? Am I understanding parameters correctly?
The method Score looks great! However, when you call it Score(sumFinal); you need to make sure that you're passing a value to the method. In your case you may have forgotten to have a field with the value at the top of the class.
is there a way I can run both the if statement and the sumFinal subtraction equation separately?
Sure! What you could do, since you don't actually give Score any value when you call it, you can remove that parameter and just return the value that it calculates.
The we could separate updating the text to another method called UpdateTextBox() that takes the result of Score() to determine if it should change the text or not
public class YourUnityClass : MOnoBehaviour
{
int questCount = 0;
int sumFinal = 0; // make sure that if you need to access this variable between methods that this field exists
int dCount = 0;
int rCount = 0;
public TextMesh labelText;
void Update()
{
if (Input.GetKeyDown(KeyCode.G) && questCount == 6)
{
// calculate and save the score
sumFinal = Score();
// check the score, and update the text if necessary
UpdateTextBox(sumFinal);
}
}
public int Score()
{
// calculate the score
return dCount - rCount;
}
public void UpdateTextBox(int sumFinal)
{
// check to see if the score is high enough to change
// the text
if (sumFinal == 5 && questCount >= 5)
{
labelText.text = "results";
}
}
}
I'm new and struggling with object orientated programming. I want to use only the return value in my third method 'tableinfo' however i don't know how to transfer only this value to the other methods, without running the first two methods again. All i want to do is transfer only the value that the user enters over to the third method and not have to put in the values two times each, this is the only way i know to get the value across and i would really appreciate if anyone could help me to just get the return value. This code is a tiny snippet of what i'm trying to do and it's purpose is not important, i just wanted to create an example to try and allow people to understand what i mean.
Thank you in advance!
class Program
{
static void Main(string[] args)
{
TableOrder TO = new TableOrder();
TO.TableNumber();
TO.NumberOfPartons();
TO.tableinfo();
}
}
class TableOrder
{
int tablenumber;
string inputtablenumber;
int numberAtTable;
string inputNumberAtTable;
public int TableNumber()
{
Console.Write("please enter the table number:");
inputtablenumber = Console.ReadLine();
tablenumber = int.Parse(inputtablenumber);
return tablenumber;
}
public int NumberOfPartons()
{
Console.Write("please enter how many people are seated: ");
inputNumberAtTable = Console.ReadLine();
numberAtTable = int.Parse(inputNumberAtTable);
return numberAtTable;
}
public void tableinfo()
{
int tablenum = TableNumber();
Console.Write(tablenumber + 1);
int patrons = NumberOfPartons();
Console.WriteLine(numberAtTable + 1);
}
}
It looks like you might be confused on the difference between methods, properties, and fields. Your function TableNumber() might be more accurately called AskUserForTableNumber() or GetTableNumberFromInput(). Something like that. You are also both setting a member field and returning the value. So there are a bunch of ways you could store and retrieve that value. If the member field tablenumber was marked as public, you could access it. Or in your main function you could do this:
int tablenum=TO.TableNumber();
and then reuse that value.
Another odd thing you are doing is storing the input string as a member field. If you don't need to reference that string again, then there's no reason for that to be a member of the TableOrder object, it could be a local variable to the function that is doing the input.
But it seems like you are trying to use TableOrder.TableNumber like a property. And that very well may be the right thing to do, but not in the way that you are doing it. Here is a (sort of fancy) way of doing something similar, which also uses a concept of lazy-loading...
class TableOrder
{
private int? _tablenumber;
public int TableNumber
{
get
{
return _tablenumber ?? (_tablenumber=GetTableNumberFromInput());
}
set
{
_tablenumber = value;
}
}
private static int GetTableNumberFromInput()
{
Console.Write("please enter the table number:");
string inputtablenumber = Console.ReadLine();
return int.Parse(inputtablenumber);
}
//(and so on for other member properties)
}
This way, the first time you try to access table number, it will ask the user for the value. Afterward, you will already have the value, so it will not ask again. Note that this type of approach is not really necessary, and is mainly useful for waiting to load a value until you need to use that value. Instead you could just do something like: TableOrder.TableNumber = GetTableNumberFromInput();
First of all, you can remove the calls in your main since the method tableinfo() will call them:
class Program
{
static void Main(string[] args)
{
TableOrder TO = new TableOrder();
TO.tableinfo();
}
}
Second, you want to use the class variables that you already declared,
The returned value of the two functions are stored inside those and you can output them with Write.
public void tableinfo()
{
tablenumber = TableNumber();
Console.Write(tablenumber + 1);
numberAtTable = NumberOfPartons();
Console.WriteLine(numberAtTable + 1);
}
In the scope of this function, the return values (return numberAtTable and return tablenumber) don't exist anymore, they are stored in whats left of the called functions.
Hello I need some help in my library. I'm trying to implement a binary search from my List<> but its not working so well.
This is my Library class.
private class Library
{
List<object> library = new List<object>();
public void AddBook(string bookName, string bookAuthor, int bookIDNum)
{
//Add books to the library.
string bookEntry = bookName + " " + bookAuthor + " " + bookIDNum;
library.Add(bookEntry);
library.TrimExcess();
}
public void SearchLibrary(string bookName)
{
//Searches the library by title
library.Sort();
int low = 0;
int high = library.Count;
int mid = 0;
int steps = 0;
while(!bookName)
{
steps++;
mid = (low + high)/2;
if(bookName == library[mid])
{
return true;
}
else if(bookName < library[mid])
{
high = mid;
}
else
{
low = mid;
}
if(low > high-1 || high < low+1)
{
return false;
}
}
}
}
}
If there's a better way I can make a search method I would appreciate it, thank you.
Without commenting on the details of your algorithm, there are some issues with your code. You could've found all these issues by looking at the compiler's error messages.
You return true and false, yet your method specifies it returns void. Change that to bool instead.
public bool SearchLibrary(string bookName)
You do !bookName, where I presume you want to check whether it is null or not. You must do that explicitly in C#.
while (bookName != null)
You compare two strings, but the < operator is not overloaded for strings. Use CompareTo instead:
else if (bookName.CompareTo(library[mid]) < 0)
Not all code paths return a value. You'll have to return a value no matter what execution path it takes. For example, end your method with this:
return false;
Then there is an issue with your algorithm: it will run forever when there is no match. As I suspect this may be homework, I'll leave it an an exercise for the OP to solve this issue.
And if this isn't a homework exercise, you could've saved yourself some trouble:
The List<T> class has a method BinarySearch that uses the default comparer to compare the objects in the list.
library.Sort();
bool found = (library.BinarySearch(bookName) >= 0);
I've been trying to write a program which can scan a raw data file and normalize it for data mining processes, I've trying to read the data from the file and store it in a list this way:
public static List<Normalize> NF()
{
//Regex r = new Regex(#"^\d+$");
List<Normalize> N = new List<Normalize>();
StreamReader ss = new StreamReader(#"C:\Users\User\Desktop\NN.txt");
String Line = null;
while (!ss.EndOfStream) {
Line = ss.ReadLine();
var L = Line.Split(',').ToList();
N.Add(new Normalize { age = Convert.ToInt16(L[0]),
Sex = L[1],
T3 = Convert.ToDouble(L[2]),
TT4 = Convert.ToDouble(L[3]),
TFU = Convert.ToDouble(L[4]),
FTI = Convert.ToDouble(L[5]),
RC = L[6],
R = L[7]
});
}
return N;
}
}
struct Normalize {
public int age;
public String Sex;
public double T3;
public double TT4;
public double TFU;
public double FTI;
public String RC;
public String R;
}
At this moment I want to go through the list that I've made and categorize the data , similar to this :
var X= NF();
for (int i = 0; i < X.Count; i++) {
if (X[i].age > 0 && X[i].age <= 5) { // Change the X[i].age value to 1 }
else if (X[i].age > 5 && X[i].age <= 10) { // Change the X[i].age value to 2 }
...
}
But the compiler says X[i].[variable name] is not a variable and cannot be modified in this way. My question is, what would be an efficient way to perform this operation.
struct Normalize is a value type, not a reference type, therefore you cannot change its fields like that. Change it to class Normalize
Change struct Normalize to class Normalize and iterate with foreach loop. It's way cleaner.
You could also set variables to private and use getters/setters to check/set variable.
foreach (Normalize x in X)
{
if (x.getAge() > 0 && x.getAge() <= 5)
x.setAge(1)
...
}
Edit:
just saw you already got your answer
Modifying struct field is fine as long as it's a single entity (Given its a mutable struct). This is possible -
var obj = new Normalize();
obh.Age = 10;
But in your case you are accessing the struct using indexer from the list.
Indexer will return copy of your struct and modifying the value won't reflect it back to the list which ain't you want.
Hence compiler is throwing error to stop you from writing this out.
As Alex mentioned, you should go for creating class instead of struct if you want to modify it.
On a side note, its always advisable to have immutable structs instead of mutable structs.
I'm not quite sure how to ask my question in C# terms, so please bear with the long-winded explanation.
I'm writing a stock trading algorithm. When the algo starts, it checks to see what kind of instrument it is applied to (in this case, either stock or futures), and then depending on the instrument, assigns a value to "double x".
If its a future instrument, then the assignment is a simple, flat value (in this case, "double x = 5;). However, if its a stock, I'd like "x" to be assigned to a value from another object - lets call the object "Algo2" and the value "y". So, in my script the assignment is as follows: "double x = Algo2.y" (note: that's the convention in the editor I'm using). This block of code is run only once when the algorithm begins.
What I'm trying to achieve here is to tell my algorithm to get the latest value of "Algo2.y" whenever "x" is used in a formula such as "EntryValue = Price + x". However, whats happening is that "x" is permanently assigned the value of "Algo2.y" at the start of the program, and since that block is never run again, remains that constant value throughout.
Can anyone help with the syntax so that instead of assigning a value to "x", it simply points to get the latest value of "Algo2.y" whevever it's called?
Thanks!
Make 'x' a property, so that it fetches the value each time you ask for x.
class StockInstrument
{
public double Value //x isn't a good name, I'll use "Value"
{
get
{
if(...) return 5.0;
else return Algo2.y;
}
}
}
Write a function for it:
double getAlgo2YValue()
{
return Algo2.y; // or Algo2.getY(), another function if you can't access it
}
In your main algorithm, now call:
x = getAlgo2YValue();
To update X.
I would use a method to return your latest value
public double GetXValue()
{
if (AlgoType == Algos.Futures)
{
return 5.0;
}
else if (AlgoType == Algos.Stock)
{
return Algo2.y;
}
//else
throw new Exception("unknown algo type");
}
This is quite hard coded, but it could be cleaned up using delegates and encapsulation of the algorithms, but at a low level - this is the idea. Also, some people prefer to use properties for this - Just don't use properties when the get has modifying affects
public double X
{
get
{
if (AlgoType == Algos.Futures)
{
return 5.0;
}
else if (AlgoType == Algos.Stock)
{
return Algo2.y;
}
//else
throw new Exception("unknown algo type");
}
}
May use something like:
double X {
get {
if(isStock())
return Algo2.y;
else
return 5;
}
}
Func<int> getX;
if(isFuture)
getX = () => 5;
else
getX = () => Algo.y;
// using getX() will always return the current value of Algo.y,
// in case it's a stock.
int xval = getX();
Give Algo2 a reference to Algo so that no 'double X' copy is needed. Algo can then dereference the actual value in Algo2 at any time, (thread-safety an issue?).
Value data types, such as int are always going to be copied by value, not as a reference. However, what you can do is architect your solution a little differently, and then it will provide the right value. For example:
public class ValueContainer
{
protected Algo2 _reference = null;
protected double _staticValue = 0;
public double CurrentValue
{
get
{
if(_reference == null)
return _staticValue;
return _reference.y;
}
}
public ValueContainer(Algo2 reference)
{
_reference = reference;
}
public ValueContainer(double value)
{
_staticValue = value;
}
}
Then, you replace your x with the ValueContainer instance wherever needed and use the CurrentValue property to get the value. You create each version with a different constructor then:
ValueContainer container = null;
if(stock)
container = new ValueContainer(5);
else
container = new ValueContainer(Algo2);
What you need is a property wrapper for x to control the value that's returned, based on the instrument type. Here's an example, which will require some significant adaptation for your app.
public class Instrument
{
// an example enum holding types
public InstrumentType Type {get; set;}
// x is not a great name, but following your question's convention...
public double X
{
get
{
if(type == InstrumentType.Stock)
return Algo2.y();
// note that I changed this to be a method rather than a property
// Algo2.y() should be static so it can be called without an instance
else if(type == InstrumentType.Future)
return 5.0;
else
// return some default value here
}
}
}