I want choice == 1 to only be able to be selected five times, so I initialized a variable firstClass = 0, then set up a do-while for firstClass < 5. I included firstClass++ in my do-while to act as a counter. However, I think firstClass is re-initializing every time I call the method CheckIn(). How can I prevent this from happening? Thanks in advance.
using System;
namespace Assignment7
{
class Plane
{
public static void Main(string[] args)
{
Console.WriteLine("Welcome to the Airline Reservation System.");
Console.WriteLine("Where would you like to sit?\n");
Console.WriteLine("Enter 1 for First Class.");
Console.WriteLine("Enter 2 for Economy.");
CheckIn();
}
public static void CheckIn()
{
int choice = Convert.ToInt32(Console.ReadLine());
int firstClass = 0;
int economy = 0;
if (choice == 1)
{
do
{
Console.WriteLine("You have chosen a First Class seat.");
firstClass++;
CheckIn();
} while (firstClass < 5);
}
else if (choice == 2)
{
do
{
Console.WriteLine("You have chosen an Economy seat.");
economy++;
CheckIn();
} while (economy < 5);
}
else
{
Console.WriteLine("That does not compute.");
CheckIn();
}
}
}
}
That is entirely normal. If you want the variable to exist outside the method, you must declare it outside a method, as a "field". Simply move the:
int firstClass = 0;
outside the method, adding the static modifier (in this case):
static int firstClass = 0;
Note also that this by itself is not thread-safe; if threading is an issue (for example, ASP.NET) then use int newValue = Interlocked.Increment(ref firstClass);. I only mention this because in the general case static data should consider threading, but I suspect it isn't an issue in your case (a console exe).
The firstClass variable is method scoped. Every time the method is called the variable is reinitialized. To have firstClass become an ongoing counter it needs to be outside the method, within the class.
You need to take any exit condition out of your method and put it outside, either by making a new method or putting it in the one that's calling it already.
For example you could do something like:
using System;
namespace Assignment7
{
class Plane
{
public static void Main(string[] args)
{
Console.WriteLine("Welcome to the Airline Reservation System.");
Console.WriteLine("Where would you like to sit?\n");
Console.WriteLine("Enter 1 for First Class.");
Console.WriteLine("Enter 2 for Economy.");
CheckIn(0, 0);
}
public static void CheckIn(int firstClassSeatsTaken, int economySeatsTaken)
{
int choice = Convert.ToInt32(Console.ReadLine());
if (choice == 1)
{
do
{
Console.WriteLine("You have chosen a First Class seat.");
firstClass++;
CheckIn(firstClassSeatsTaken, economySeatsTaken);
} while (firstClass < 5);
}
else if (choice == 2)
{
do
{
Console.WriteLine("You have chosen an Economy seat.");
economy++;
CheckIn(firstClassSeatsTaken, economySeatsTaken);
} while (economy < 5);
}
else
{
Console.WriteLine("That does not compute.");
CheckIn(firstClassSeatsTaken, economySeatsTaken);
}
}
}
}
Related
i am a C# beginner, so for now most of my code is inside the Main() method. I want to make my Program more object oriented so I want to move code from Main method to another class reliably(so i can do it with other programs as well).
static void Main()
{
int xLentgh = 20;
int yLength = 20;
Map.MapBuilder(xLentgh,yLength);
int oldPositionX = 0;
int oldPositionY = 0;
int newPositionX = 0;
int newPositionY = 0;
if (oldPositionX == 0)
{
Map.WriteAt(".",newPositionX, newPositionY);
}
for (int i = 0; i < 100; i++)
{
ConsoleKeyInfo KeyStroke;
KeyStroke = Console.ReadKey();
switch (KeyStroke.Key)
{
case ConsoleKey.RightArrow:
{
if (newPositionX < xLentgh-1)
{
oldPositionX = newPositionX;
oldPositionY = newPositionY;
newPositionX++;
}
break;
}
case ConsoleKey.LeftArrow:
{
if (newPositionX > 0)
{
oldPositionX = newPositionX;
oldPositionY = newPositionY;
newPositionX--;
}
break;
}
case ConsoleKey.UpArrow:
{
if (newPositionY > 0)
{
oldPositionX = newPositionX;
oldPositionY = newPositionY;
newPositionY--;
}
break;
}
case ConsoleKey.DownArrow:
{
if (newPositionY < yLength-1)
{
oldPositionX = newPositionX;
oldPositionY = newPositionY;
newPositionY++;
}
break;
}
default: break;
}
Map.WriteAt(".",newPositionX, newPositionY);
Map.WriteAt(" ",oldPositionX, oldPositionY);
}
}
In this code I create a "map" and using the switch statement in the for loop to "track" the position of the cursor. How do I write this code in a new class? I dont know where to start
You can try to create a class named as you want (we will call it RandomNameClass) by declaring it outside of the bloc class Program {}.
You should have something like this :
namespace NameYouGaveToProject
{
class RandomNameClass
{
}
class Program
{
static void Main(string[] args)
{
// Your actual code here
}
}
}
Above or under is fine but prefer having the class Program at the bottom if you write all your code in one file.
There you have your first custom class! Now try to add some functions in it. If you haven't learn about instantiating a class yet, just don't forget to add public static before the returning type of your function.
Example of what you could have :
namespace NameYouGaveToProject
{
class RandomNameClass
{
// Function that doesn't return anything, returns "void"
public static void SayHi()
{
Console.WriteLine("Hi!");
}
// Function that returns a string
public static string ReturnHi()
{
return "Hi!";
}
}
class Program
{
static void Main(string[] args)
{
// Your actual code here
}
}
}
And then you can call them by typing the name of the class, followed by a point and then the name of the function and "()" if there are no parameters to this function (there aren't in my example).
The syntax would be :
// Call the void function
RandomNameClass.SayHi();
// Call the function returning a string
string testVariable = RandomNameClass.ReturnHi();
Note that you can call as often as you want every function
And voilĂ ! You know the basics of creating a class and call functions from this class! Next thing you should learn is how to make functions properly, and then instantiating a class and manage it's content
This question already has answers here:
How to fix "No overload for method ' ' takes 0 arguments"?
(5 answers)
Closed 5 years ago.
Hello im trying to call a method in a different class so when the user selects the button 1 it will call the
It says no overload for method myMethod takes 0 arguments
using System;
namespace crap
{
class firstClass
{
public static void Main (string[] args)
{
int choice = 0;
while (choice != 1 || choice != 2) {
Console.WriteLine ("Press 1 for choice 1 or 2 for choice for choice 2");
choice = Convert.ToInt32 (Console.ReadLine ());
if (choice == 1) {
crap.secondClass.myMethod();
}
if (choice == 2) {
}
}
}
}
public class secondClass{
public static void myMethod(int later, int later2)
{
Console.WriteLine("You chose option 1");
}
}
}
using System;
namespace crap
{
class firstClass
{
public static void Main (string[] args)
{
int choice = 0;
while (choice != 1 && choice != 2)
{
Console.WriteLine ("Press 1 for choice 1 or 2 for choice for choice 2");
choice = Convert.ToInt32 (Console.ReadLine ());
if (choice == 1) {
crap.secondClass.myMethod();
}
if (choice == 2) {
}
}
}
}
public class secondClass{
public static void myMethod()
{
Console.WriteLine("You chose option 1");
}
}
}
I'm trying to improve my program for Fibonacci numbers using of memoization:
public class MyGlobals
{
public long TotNum { get; set; }
public long[] MyNumbers { get; set; }
public void GetParam()
{
Console.Write("n = ");
this.TotNum = long.Parse(Console.ReadLine());
this.MyNumbers = new long[this.TotNum + 1];
// set all numbers to -1
for (int i = 0; i < this.MyNumbers.Length; i++)
{
this.MyNumbers[i] = -1;
}
}
}
class Program
{
static void Main(string[] args)
{
MyGlobals globVariable = new MyGlobals();
globVariable.GetParam();
long n = globVariable.TotNum;
Console.WriteLine("Fib ({0}) = {1}", n, Fibonacci(n));
Console.ReadKey();
}
static long Fibonacci(long n)
{
MyGlobals globVariable = new MyGlobals();
if (n <= 1)
{
return 1;
}
if (globVariable.MyNumbers[n] != -1)
{
return globVariable.MyNumbers[n];
}
else
{
globVariable.MyNumbers[n] = Fibonacci(n - 1) + Fibonacci(n - 2);
}
return globVariable.MyNumbers[n];
}
}
I'm trying to do something like feed an array by -1 in MyGlobals class for further using MyNumbers array in Fibonacci static method.
Until line where I'm starting to call recursive fibonacci method it holds MyNumbers array in memory. But in Fibonacci method, when I create new instance of MyGlobals class for calling MyNumbers array is this array empty... What I'm doing wrong. Can you anybody help me on this, please. Thank you very much in forward.
Declare globVariable as a static member of the Program class like so:
class Program
{
static MyGlobals globVariable = new MyGlobals();
static void Main(string[] args)
{
globVariable.GetParam();
long n = globVariable.TotNum;
Console.WriteLine("Fib ({0}) = {1}", n, Fibonacci(n));
Console.ReadKey();
}
static long Fibonacci(long n)
{
if (n <= 1)
{
return 1;
}
if (globVariable.MyNumbers[n] != -1)
{
return globVariable.MyNumbers[n];
}
else
{
globVariable.MyNumbers[n] = Fibonacci(n - 1) + Fibonacci(n - 2);
}
return globVariable.MyNumbers[n];
}
}
There is no such thing as global variables in C#. The problem you're having relates to instances of nonstatic classes.
You effectively have three separate units in your code:
One class that asks for input, holds this input and holds an array of result variables (MyGlobals). This is in fact way too much for a single class and should ultimately be split up.
One method that calculates Fibonacci numbers and stores them into the previous class (Fibonacci).
A Program class and Main() method which host your console application.
Now your problem is that you don't know how to access the array of inputs stored in 1 from method 2. There are various ways to solve that, each with their own cons and pros. The most obvious one is to pass a reference.
But before that, clean up your code: give classes and methods meaningful names, and extract logic into separate classes.
Here you'll remain with three classes:
public class FibonacciInput
{
public void GetParam()
{
// Your "MyGlobals" logic
}
}
Then the calculation logic:
public class FibonacciCalculator
{
public long Fibonacci(long index, long[] range)
{
// Your "Fibonacci()" logic
}
}
And the program:
class Program
{
static void Main(string[] args)
{
FibonacciInput input = new FibonacciInput();
FibonacciCalculator calculator = new FibonacciCalculator();
input.GetParam();
long n = input.TotNum;
Console.WriteLine("Fib ({0}) = {1}", n, calculator.Fibonacci(n, input.MyNumbers));
Console.ReadKey();
}
}
Now your calculator doesn't know anything about your input, and the need for "global variables" goes away.
The point is that the Fibonacci() method needs two things: the index (the Nth Fibonacci number it should calculate) and an array to work with (which you initialized on beforehand).
So by calling calculator.Fibonacci(n, input.MyNumbers), you solve all problems at once.
Well, may be it's not really answers your question but i'd refactor your code dividing it to logical parts where each part is only responsible for one thing :
UI
Global variables
Class that knows how to work with fibo sequence
Program (entry point)
Refactored code may look something among the lines of :
// Globals should be static
public static class MyGlobals
{
public static long TotNum { get; private set; }
public static long[] MyNumbers { get; private set; }
public static void SetNum(long num)
{
TotNum = num;
MyNumbers = new long[TotNum + 1];
}
}
// interacts with UI
public static class UIHelper
{
public static long GetParam()
{
Console.Write("n = ");
var number = long.Parse(Console.ReadLine());
return number;
}
}
// Knows how to calc fibo
static class Fibo
{
static long Calc(long[] nums, long n)
{
... calc fibonacci logic
}
}
class Program
{
static void Main(string[] args)
{
// now we can use them all
// first lets get value from console
var num = UIHelper.GetParam();
// set global variables with this value
MyGlobals.SetNum(num);
// output result :
Console.WriteLine("Fib ({0}) = {1}", n, Fibo.Calc(MyGlobals.MyNumbers, MyGlobals.TotalNum));
Console.ReadKey();
}
}
P.S.
Whether to send global values as parameters to Fibo.Calc() method or to access them directly from inside of it it's up to you. I vote for first option because it makes it easier to test this method by passing mock data.
Please take note that this is uncompleted code, but just facing some small issue, as i using a lot of c++ OOP concept. i might have some issue when trying to change from another platform.
I get error when compiled and stated nonstatic method/property error
using System;
public class People
{
string name;
int age;
int height;
public virtual void insertDetail(People stu)
{
Console.Write("Please enter name : ");
stu.name = Console.ReadLine();
Console.Write("Please enter age : ");
while(!int.TryParse(Console.ReadLine(), out stu.age))
{
Console.WriteLine("You enter characters! Please re-insert");
}
Console.Write("Please enter height: ");
while(!int.TryParse(Console.ReadLine(), out stu.height))
{
Console.WriteLine("You enter characters! Please re-insert");
}
}
}
public class Class : People
{
static People[] students = new People[5];
public override void insertDetail(People stu)
{
Console.WriteLine("==================================");
base.insertDetail(stu);
}
public static void Main(string[] args)
{
for (int i = 0; i < students.Length; i++)
{
students[i] = new People();
insertDetail(students[i]);
}
Console.ReadKey();
}
}
As said in comments, you need an instance to use instance method.
Create an instance for Class inside Main
public class Class : People
{
static People[] students = new People[5];
public override void insertDetail(People stu)
{
Console.WriteLine("==================================");
base.insertDetail(stu);
}
public static void Main(string[] args)
{
Class c = new Class(); // this is required to access insertDetail
for (int i = 0; i < students.Length; i++)
{
students[i] = new People();
c.insertDetail(students[i]);
}
Console.ReadKey();
}
}
Check this Demo
You get that error when you make a static call to an instance method like Object.ToString() using the type name as the qualifier when you really need an instance.
First of all never use Class as your class name.
As for the error you need to give more information about what are you trying to do. You have to add static modifier to your method:
public static void insertDetail(People stu)
Or if you want for it to be override than:
public virtual void insertDetail()
{
this.name = "Some name";
//...
}
using System;
namespace UnaryOperators
{
class UnaryOperators
{
//pre and post incerment checking and examples
public int a=0;
public int PreIncrement()
//shows error here(not all code paths return value)
{
//what i am trying to do here is i want to create 2 methods
//one for pre increment and other for post increment
//but when i am typing program i stuck with above error so
//i didn't complete the code
//i want to know how pre increment and post incerment work
for(a = 0; a < 10; a++)
{
Console.WriteLine("PreIncrement value of a is "+a);
return a;
}
}
public static void Main(string[]args)
{
/*
//if any one gives me a program as an example i will be really thankful
//please give me an example to understand pre and post increments
// if you can understand anything of my code help me solve it
// (but honestly think my code is shit)
*/
}
}
}
This little program shows how pre and post increments works.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("After pre {0}", PreInc());
Console.WriteLine();
Console.WriteLine("After post {0}", PostInc());
Console.ReadLine();
}
public static int PreInc()
{
int a = 0;
do {
Console.WriteLine("PreIncrement value of a is {0}", ++a);
} while (a < 10);
return a;
}
public static int PostInc()
{
int a = 0;
do {
Console.WriteLine("PostIncrement value of a is {0}", a++);
} while (a < 10);
return a;
}
}