I cannot solve this simple exercise in Deitel Visual C# 2010 [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I've been studying Deitel's Visual C# 2010. I'm stuck at an exercise in the chapter about arrays. It's been bugging me for days now, and I've written the code several times now and each times something goes wrong.
The exercise is asking to develop a new reservation system for a small airline company. The capacity of an airplane is 10 seats. So you ask the customer to input 1 for First Class and 2 for Economy. Seats from 1 to 5 are for first class. Seats from 6 to 10 are for economy.
I must use a one-dimensional array of type bool to represent the seating char of the plane. Initialize all elements of the array to false to represent vacant seats (Luckily bool initializes to false anyway, because I do not know how to initialize an array). As each seat is assigned, set the corresponding element in the plane to true.
The app should never assign a seat that's already been seated. When the economy class is full, the app should ask the customer if he wants to fly in first class (and vice versa). If the customer responds with yes, assign him in the economy class (if there's an empty seat there). If there is no empty seats in economy or the customer refuses to fly in first class, then just display to him that "The next flight is after three hours!).
I'm self-studying the book. This is not an assignment or homework. I really do not wish to post the code I've written because I want a completely fresh way to solve the problem, but I'm pretty sure that I will be asked about the code, so here it is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Craps_Game
{
class AirlineReservation
{
private static bool[] seats = new bool[10];
private static void FirstClass(ref bool[] seats)
{
for(int i = 0; i < 5; i++)
{
if (seats[i] == false)
{
seats[i] = true;
Console.WriteLine("Your seat number is " + i);
break;
}
else
{
Console.WriteLine("First Class is full. Would you like to fly Economy?");
if (Console.ReadLine().ToLower() == "y")
Economy(ref seats);
else
Console.WriteLine("The next flight is in three hours!. Good bye");
}
}
}
private static void Economy(ref bool[] seats)
{
for (int i = 5; i < 10; i++)
if (seats[i] == false)
seats[i] = true;
else
{
Console.WriteLine("Economy class is full. Would you like to fly First Class");
if (Console.ReadLine().ToLower() == "y")
FirstClass(ref seats);
else
Console.WriteLine("The next flight is in three hours!. Good Bye");
}
}
public static void Reservation()
{
do
{
Console.WriteLine("Enter 1 to fly First Class");
Console.WriteLine("Enter 2 to fly Economy Class");
if (Convert.ToInt32(Console.ReadLine()) == 1)
FirstClass(ref seats);
else
Economy(ref seats);
} while (true);
}
}
}
Bear in mind that I would prefer a completely different way of solving the problem, instead of fixing this one :)

I don't want to solve the entire problem in code since you are learning, but I will show you the major things I saw in your code that is a bug.
Your Economy method was not exiting the loop if it found that a
seat was available. It needed to break.
Your else when you did not find a seat was not checking if all of the seats were taken. Checking if i == 9 will make it so it will only go to FirstClass if there are no more seats, not before.
private static void Economy(ref bool[] seats)
{
for (int i = 5; i < 10; i++)
{ // <---- Added the brackets
if (seats[i] == false)
{
seats[i] = true;
break; // <----- You forgot to break when you reserved a seat.
}
else if (i == 9) // <---- You weren't checking if all seats are taken.
{
Console.WriteLine("Economy class is full. Would you like to fly First Class");
if (Console.ReadLine().ToLower() == "y")
FirstClass(ref seats);
else
Console.WriteLine("The next flight is in three hours!. Good Bye");
}
}
}

I like the way you approach programming and your task and this site!
Therefore I would hate to write out the code for you - all the fun is getting it done by yourself. But since you are stuck let me give you a few hints:
Starting at the bottom, the first thing that comes to mind is that you are always offering both classes even when one or both are full. Here is a function header that could help to break things down even further than you already have done:
public int getFirstVacantSeatIn(int classType)
// returns 1-5 for classType=1, 6-10 for classType=2, -1 if classType is full
You can use this function to make the prompt dynamic like this:
Console.WriteLine( ( getFirstVacantSeatIn(1) >= 0 ?
"Enter 1 to fly First Class") : "First Class is full");
And you can reuse it when you try to assign the new seats..:
Another point is that you offer switching between classes when one is full without checking if the other one actually isn't full, too. I suspect that is the problem you are facing?
So you should check before offering to up- or downgrade.. The above function will help here as well. If you can re-use something, chances are that it was right to create that thing..
The secret is ever so often to break your problem down further and further until it goes away, always using/creating useful names for the sub-problems..

"I must use a one-dimensional array of type bool to represent the seating char of the plane"
"I want a completely fresh way to solve the problem"
"Bear in mind that I would prefer a completely different way of solving the problem, instead of fixing this one"
So be it! Others have given you really good advice already, but here's "fresh" way to do it.
using System;
namespace FunnyConsoleApplication
{
public class Program
{
static void Main(string[] args)
{
Airplane plane = new Airplane();
bool reserve = true;
while (reserve)
{
Console.Clear();
Console.WriteLine("Enter [1] to fly First Class ({0} vacant)", plane.VacantFirstClassSeats());
Console.WriteLine("Enter [2] to fly Economy Class ({0} vacant)", plane.VacantEconomySeats());
string input = Console.ReadLine();
switch (input)
{
case "1":
if (plane.HasFirstClassSeats)
{
plane.ReserveFirstClassSeat();
}
else if (plane.HasEconomySeats)
{
if (IsOk("No vacancy, enter [y] to fly Economy instead?"))
plane.ReserveEconomySeat();
else
reserve = false;
}
else
{
reserve = false;
}
break;
case "2":
if (plane.HasEconomySeats)
{
plane.ReserveEconomySeat();
}
else if (plane.HasFirstClassSeats)
{
if (IsOk("No vacancy, enter [y] to fly First Class instead?"))
plane.ReserveFirstClassSeat();
else
reserve = false;
}
else
{
reserve = false;
}
break;
}
Console.WriteLine();
}
Console.WriteLine("No can do, good bye!");
Console.ReadLine();
}
private static bool IsOk(string question)
{
Console.WriteLine(question);
return string.Compare(Console.ReadLine(), "y", StringComparison.OrdinalIgnoreCase) == 0;
}
}
public class Airplane
{
private readonly bool[] _seats = new bool[10];
public bool HasFirstClassSeats
{
get { return HasSeats(0); }
}
public bool HasEconomySeats
{
get { return HasSeats(5); }
}
public int VacantFirstClassSeats()
{
return GetVacant(0);
}
public int VacantEconomySeats()
{
return GetVacant(5);
}
public void ReserveFirstClassSeat()
{
Reserve(0);
}
public void ReserveEconomySeat()
{
Reserve(5);
}
private bool HasSeats(int index)
{
for (int i = index; i < index + 5; i++)
{
if (!_seats[i])
return true;
}
return false;
}
private int GetVacant(int index)
{
int count = 0;
for (int i = index; i < index + 5; i++)
{
if (!_seats[i])
count++;
}
return count;
}
private void Reserve(int index)
{
for (int i = index; i < index + 5; i++)
{
if (!_seats[i])
{
_seats[i] = true;
break;
}
}
}
}
}
Which gives you

Related

List resetting when adding new items (Edited title to reflect actual issue)

Original Title: Get-Set to add Object w/multiple properties into a list C#
Edit: I had originally thought the issue was in setting up properties for the list objects, when it was an issue with regards to where I had initialized the list in my main code class.
Original Post:
New to coding, taking a C# course. We're working on encapsulation and get:set/properties.
The assignment says that we have to build a class that creates a die with an input number of sides, and "roll" the die for a random number. Easy!
In a second class, we have to build a function to add or remove any number of dice to the pool, and then roll them all for a result.
I'm assuming they want the dice pool to be a list that is private.
My logic going in was to create the single OneDie class, and then using a xDy notation in the main program prompt to add x number of die with y sides to the list. (ie: add 2d6)
I've built an AddDie function that should do that, but when I check my list count after it's done, the count is 0. The private list (_dicePool) seems to be re-setting to zero every time I try to add a new object to the list. I suspect I'm not building my property DicePool's get/set functionality correctly, but I'm not sure how to call my 2-parameter AddDice function from inside the DicePool{set}, or even if that's the approach I should take.
Assuming the list should be private, am I missing something to permanently add new objects to the list?
Edit to add: OR, would it be better to create a ManyDice object? But how do I build this.Sides and this.Roll from the OneDie object?
Here's my code that's applicable to adding objects (dice) to the list (dicepool).
class ManyDice
{
private List<OneDie> _dicePool = new List<OneDie>();
//What I think I might have to do:
public List<OneDie> DicePool
{
get
{
return this._dicePool;
}
set
{
//???????????? how do I call AddDice, when I need 2 parameters for it?
}
}
public void AddDie(int number, int sides)
{
for (int i = 0; i < number; i++)
{
this.dicePool.Add(new OneDie(sides));
}
}
}
class OneDie
{
private int _sides, _rolledValue;
public int Sides
{
get
{
return this._sides;
}
set
{
this._sides = value;
}
}
public int RollValue
{
get
{
return this._rolledValue;
}
set
{
this._rolledValue = value;
RollIt(value);
}
}
public OneDie()
{
}
public OneDie(int sides)
{
this.Sides = sides;
this.RollValue = sides;
}
private int RollIt (int sides)
{
Random random = new Random((int)DateTime.Now.Ticks);
return random.Next(1, (sides + 1));
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Let's roll some dice!");
Console.WriteLine("Please enter the number of dice you want to roll in the following format:");
Console.WriteLine("xdy, where \"x\" is the number of dice you want and \"y\" is how many sides they have.");
Console.WriteLine("Example: 2d6 is 2 6-sided dice. Perfect for playing Catan! (or Monopoly)");
Console.WriteLine("Please limit your dice to d4, d6, d8, d10, d12, d20");
Console.WriteLine("To add a die, type \"add xdy\" to add x number of y sided dice.");
Console.WriteLine("To remove a die, type \"remove xdy.\" to remove x number of y sided dice.");
Console.WriteLine("Type \"dice\" to see a list of all the dice in the pile.");
Console.WriteLine("Type \"roll\" to roll all the dice and see the results!");
Console.WriteLine("Type \"clear\" to clear all the dice and start agin!");
Console.WriteLine("Type \"exit\" to exit program\n");
PlayDice();
Console.ReadKey();
}
static void PlayDice()
{
do
{
string[] xDy = null;
int numberOfDice = 1;
int numberOfSides=1;
Console.WriteLine("\nEnter your command:");
string option = Console.ReadLine();
option = option.ToLower().Trim();
string[] words = option.Split(' ');
string command = words[0];
//CheckCommand(command);
if (words.Length > 1)
{
xDy = words[1].Split('d');
numberOfDice = int.Parse(xDy[0]);
numberOfSides = int.Parse(xDy[1]);
}
ManyDice die = new ManyDice();
if (command == "exit")
{
Console.WriteLine("Thank you, play again, soon!");
break;
}
else if (command == "add")
{
//numberOfSides=CheckDice(numberOfSides);
die.AddDie(numberOfDice, numberOfSides);
Console.WriteLine("You have {0}ed {1} {2}-sided dice.", command, numberOfDice, numberOfSides);
}
else if (command == "remove")
{
Console.WriteLine("You have {0}d {1} {2}-sided dice.", command, numberOfDice, numberOfSides);
}
else if (command == "dice")
{
Console.WriteLine("These are your dice:");
die.Display();
}
else if (command == "roll")
{
Console.WriteLine("Here is your roll:");
}
else if (command == "clear")
{
Console.WriteLine("All dice have been cleared.");
}
} while (true);
}
static int CheckDice(int sides)
{
List<int> check = new List<int> {4,6,8,10,12,20};
while (!check.Contains(sides))
{
Console.WriteLine("{0}-sided dice are not available.\nPlease enter 4,6,8,10,12 or 20");
sides = int.Parse(Console.ReadLine());
}
return sides;
}
static string CheckCommand(string instructions)
{
List<string> check = new List<string> { "add", "remove", "dice", "roll","clear", "exit" };
while (!check.Contains(instructions))
{
Console.WriteLine("Command not recognized.\nPlease enter \"add\", \"remove\", \"dice\", \"roll\",\"clear\", or \"exit\"");
instructions = Console.ReadLine();
}
return instructions;
}
}
New Answer based on comments and updated question:
The line ManyDice die = new ManyDice(); is wiping your dice list clean every loop through your program. It's replacing your variable with a new instance of the class, with a fresh list and all.
Simply move that line before the start of the loop:
before the line do {
and then every iteration will use the same instance of ManyDice, and will all share the variable die, without overwriting it.
OLD ANSWER: From what I can see, your program only runs once. And then you need to start it again to put in another dice. Your main function only asks for input once. Whenever you start the program again, all the memory used in the program gets cleared. Unless I’m missing something, that is why your list continues to be reset. You’re actually running a completely new program the next time you try to add dice. So it has no knowledge of the previous runs.
One solution is to say (pseudo code)
While (running) {
// what you have now
if (option == “done”) running = false;
if (option == “roll”) // roll all dice.
}
This will keep prompting the user for commands until they type done. And it remains the same program so that you don’t lose the data from earlier commands.
Update based on comment: you’re recreating the ManyDice instance on each iteration, effectively starting from scratch. Save the instance outside the while loop and then reuse it.
Hint:
Your rolling should probably be done by manyDice.RollAll() And maybe should return a List of RollResults.

Refactoring C# code for conversion to a WPF application (Visual Studio)

For this guessing game, I want to refactor this glass cannon of a code for conversion to a WPF application. Any methods I could use to shorten this/successfully convert and tips on VS, in general, would be greatly appreciated.
I'm using the WPF app (core) as a template for this program. As well as using the Microsoft tutorial for it to build it. The UI for this project is mostly done, just need to import this code.
Do note I'm in high school so my scope of knowledge isn't that big.
EDIT: Ok.
Firstly what I want to do with this code is cutoff the needless "IF" and "console.write" statements for a clean solution.
Secoundly I'm seperating the solution into two files, an App.xaml.cs file and a MainWindow.Xaml.cs file. Within App.xaml file I'm putting all my public classes(ex:guess,rnd,etc). While the MainWindow.Xaml file is where I'm putting the "Game Logic".
What I've done so far is; in regards to MainWindow.xaml is two methods. A public method that initializes rnd ccalculations. And a "Button_Click" private method that once the user submits their guess the "game" sees if it matches and displays if they are right or wrong including how long it took them to guess corectly.
class MainClass
{
public static void Main (string[] args)
{
Random rnd = new Random();
int ans = rnd.Next(1,10);
Console.WriteLine("Pick an integer between 1 and 10");
var num1 = Console.ReadLine();
int v1 = Convert.ToInt32(num1);
if(v1 == ans)
{
int count = 1;
Console.WriteLine($"{v1} is correct. You Win!");
Console.WriteLine($"It took you to {count} gues find the number {ans}." );
}
else
{
if(v1<ans){
Console.WriteLine("To high");
}
else
Console.WriteLine("To low");
Console.WriteLine("Pick an interger between 1 and 10");
Console.WriteLine($"{v1} isn't correct. Try again!");
var num2 = Console.ReadLine();
int v2 = Convert.ToInt32(num2);
if(v2 == ans)
{
int count = 2;
Console.WriteLine($"{v2} is correct. You Win!");
Console.WriteLine($"It took you {count} gueses to find the number {ans}" );
}
else
{
if(v1<ans){
Console.WriteLine("To high");
}
else
Console.WriteLine("To low");
Console.WriteLine("Pick an interger between 1 and 10");
Console.WriteLine($"{v2} isn't correct. Try again!");
var num3 = Console.ReadLine();
int v3 = Convert.ToInt32(num3);
if(v3 == ans)
{
int count = 3;
Console.WriteLine($"{v3} is correct. You Win!");
Console.WriteLine($"It took you {count} gueses to find the number {ans}" );
}
else
{
if(v1<ans){
Console.WriteLine("To high");
}
else
Console.WriteLine("To low");
Console.WriteLine("Pick an interger between 1 and 10");
Console.WriteLine($"{v3} isn't correct");
}
Console.WriteLine($"You Lose! The correct number is {ans}. ");
}
}
}
}
So many things happening here, we would need a lot of time to explain.
Let me try to get to the basics. A class in C# is a blueprint of state and behavior.
In that term, you could model your code as a GameRound
public class GameRound {
private int noOfTries;
private int maxNoOfTries;
private int correctNumber;
private bool success;
public bool HasRoundEnded { get {
return maxNoOfTries == noOfTries;
}
}
public bool Success { get {
return success;
}
}
public GameRound() {
Random rnd = new Random();
int ans = rnd.Next(1,10);
correctNumber = ans;
}
public bool GuessSolution(int guess) {
if (guess == correctNumber) {
this.success = true;
} else {
this.success = false;
maxNoOfTries++;
}
return this.success;
}
You can see that most of your logic, was included in a class. I'll leave it to you to figure out how to use it.
You'll notice that there is no dependency on Console.Write or read. You can use that code in a console application or a UI or even a website. This happens because we separate the concerns of the class to only model a game round.
Another piece of advice, is for you to use a while loop with the class provided, to solve your problem in the console application. That way you'll understand how to use repeating structures and objects of classes.

How to implement in console quiz the removal of an option every t2 seconds (t2<T)

I am new to C# and I am trying to build console quiz.
Here is my problem:
For every option removed I have to reduce one option (let's say the total points are 100).
If one option is removed I need to reduce the total points by 25 (i.e now the total points will be 75).
JSON data:
{
"question": [
{
"level": "Easy",
"cat": "sports",
"description": "Who is the Highest run getter in 2019",
"Option1": "Rohit Sharma",
"Option2": "Virat Kohli",
"Option3": "Kl Rahul",
"Option4": "S Dhawan",
"Answer":"1"
}]
}
Program:
using System;
using System.Timers;
namespace CProgram
{
class EasyQuestion
{
private string mLevel;
private string mCat;
private string mDescription;
private string mOption1;
private string mOption2;
private string mOption3;
private string mOption4;
private string mAnswer;
public string MDescription { get => mDescription; }
public string MOption1 { get => mOption1; }
public string MOption2 { get => mOption2; }
public string MOption3 { get => mOption3; }
public string MOption4 { get => mOption4; }
public string MAnswer { get => mAnswer; }
public string MLevel { get => mLevel; }
public string MCat { get => mCat; }
public static int sQcount=1;
public int sPlayerScore=0;
public int mNoOfQuesAnswerd=0;
static Timer questionTimer = new Timer(60000) ;
private static void QuestionTimer_Elapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine("Time up!");
System.Console.WriteLine("Lets Move on to Next Question");
questionTimer.Stop();
}
public EasyQuestion(string level,string cat,string description,string Option1,string Option2,string Option3,string Option4,string Answer)
{
this.mLevel=level;
this.mCat=cat;
this.mDescription=description;
this.mOption1=Option1;
this.mOption2=Option2;
this.mOption3=Option3;
this.mOption4=Option4;
this.mAnswer=Answer;
}
public EasyQuestion()
{
}
public void AskEasyQues(EasyQuestion easyQuestion)
{
System.Console.WriteLine("Here is Your:"+sQcount+" Question:");
System.Console.WriteLine("***********************************");
System.Console.WriteLine("Question is of The Category:"+easyQuestion.MCat);
System.Console.WriteLine("***********************************");
System.Console.WriteLine(easyQuestion.MDescription);
System.Console.WriteLine("--------------------------------------");
System.Console.WriteLine("1:"+easyQuestion.MOption1+" "+"2:"+easyQuestion.MOption2);
System.Console.WriteLine();
System.Console.WriteLine("3:"+easyQuestion.MOption3+" "+"4:"+easyQuestion.MOption4);
System.Console.WriteLine();
questionTimer.Elapsed += QuestionTimer_Elapsed;
questionTimer.Enabled = true;
questionTimer.Start();
System.Console.WriteLine("Enter your Choice:");
/*for (int a = 60; a >= 0; a--)
{
Console.Write("\rGenerating Preview in {0:00}", a);
System.Threading.Thread.Sleep(1000);
} */
string ans=Console.ReadLine();
if(ans==easyQuestion.MAnswer)
{
questionTimer.Stop();
mNoOfQuesAnswerd++;
System.Console.WriteLine();
System.Console.WriteLine("------Well Played Champion!!!!!!-----");
sPlayerScore=sPlayerScore+100;
}
else
{
System.Console.WriteLine();
System.Console.WriteLine("------Wrong Choice Lets Move On--------");
}
System.Console.WriteLine();
System.Console.WriteLine("Press any Key To Continue For Next Question");
Console.ReadLine();
System.Console.WriteLine();
System.Console.WriteLine("----------------------------");
sQcount=sQcount+1;
Console.Clear();
}
}
}
I have a timer of 60 seconds and I have to remove an option every 15 seconds.
Here; I wrote this for you to show you why you can't easily do what you're asking:
static void Main(string[] args)
{
string[] answers = new[] { "answer one", "answer two", "answer three", "answer four" };
Random r = new Random();
int rightAnswer = 2;
Console.Write("\r" + string.Join(", ", answers));
for (int i = 1; i < 60; i++)
{
if (i % 15 == 0)
{
//randomly remove an answer that is not the right one
int a = r.Next(answers.Length);
while (a == rightAnswer || answers[a][0] == ' ') // dont remove the right answer! dont pick an answer that is already blanked
a = r.Next(answers.Length);
answers[a] = new string(' ', answers[a].Length); //replace answer with spaces
//return to the start of the line and overwrite
Console.Write("\r" + string.Join(", ", answers));
}
System.Threading.Thread.Sleep(100);
}
Console.Write("\nQuit");
}
It "works" in that it will remove one option every 1.5 seconds (if you want 15, extend the sleep) but the question cannot be answered on the console. As soon as you put a ReadLine() in there to get the answer, the program will halt waiting at that point until the user puts the answer in. You can take this and work out some other super complicated way of getting the answer in, such as opening a listening port and having the user telnet into the program and submit their answer that way etc...
But truly; have a play and see what me and Chris are saying and then do it in a windows GUI
Timers and consoles do not mix that well. Or really at all. In Console usually you go from one Blocking Input request to the next (ReadLine() and ReadKey()), with the odd phase of processing in between.
It is possible to poll input without blocking in a console, but that is a pretty advanced topic. And if you ever need to do that, chances are you should not have a console programm in the first place.
The rest is just clear+reprint or setting the cursor back and overwriting. Personally I prefer the clean+rewrite method for such a case.
Counting of the time can be done with DateTime.Now and .AddSeconds(). But I can only repeat, that with Windows Forms or another GUI this would be incredibly trivial. Would be just adding a timer and setting one button to hidden.

How to use code from one class in another C# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am trying to link a random seating code to my User Interface class and I am stumped on how I could call upon this at anytime through my user interface. The below is currently kept inside a FirstClassCarriage class.
{
Random rand = new Random();
bool[] seats = new bool[32];
//To keep a separate list of seats taken
List<int> seatsBooked = new List<int>();
bool quit = false;
do
{
Console.Clear();
//int seatAssignFirstClass = rand.Next(0, 32);-> Moved to switch-case 1: block
int seatAssignThirdClass = rand.Next(32);
int seatAssignFirstClass; //Variable moved from main loop
//Are there any seats booked already or this is the first?
if (seatsBooked.Count == 0) //if this is the first seat to be booked...
{
seatAssignFirstClass = rand.Next(0, 32);
seats[seatAssignFirstClass] = true;
seatsBooked.Add(seatAssignFirstClass); //Add seat to the list of booked seats.
}
else
{
do //while there are available seats and current seat has not being assigned before.
{
seatAssignFirstClass = rand.Next(0, 32);
if (!seatsBooked.Contains(seatAssignFirstClass)) //if seatAssignFirstClass is not booked.
{
seats[seatAssignFirstClass] = true;
}
//repeat while the random seat number is already booked and there are avaialable seats
} while (seatsBooked.Contains(seatAssignFirstClass) && seatsBooked.Count < 32);
//IMPORTANT: Number on line bellow needs tos be one bigger than rest
if (seatsBooked.Count < 34) //if seatsBooked list is not full for First Class
{
seatsBooked.Add(seatAssignFirstClass); //Add current random-generated seat to the list.
}
}
//IMPORTANT: Number on line bellow needs tos be one bigger than rest
if (seatsBooked.Count >= 34) //If all seats are booked
{
Console.WriteLine("All seats for First Class are booked");
Console.WriteLine("Press enter to continue...");
}
else //Give customer their seat nmumber
{
Console.WriteLine("Train seat number: {0}", seatAssignFirstClass + 1);
Console.WriteLine("Press enter to continue to the main menu...");
}
} while (!quit);
The smallest unit of code reuse in C# is a function. You need to put this code in a function, and then you can call it from other places. Easiest would be for that to be a public static function, but as you learn more about design you may find that there are better ways of sharing the functionality.
You can add a reference to classes in other files with the using keyword and the desired class' namespace
Example:
namespace MyProject.MyCore {
public class MyClass {
public void MyMethod() { }
}
}
You would then refer to this namespace in the calling class, like so:
using MyProject.MyCore
Which allows you to instantiate the class object, like so:
var myInstantiatedClass = new MyClass();
And call it's method like so:
myInstantiatedClass.MyMethod();
Methods can also be marked static, which removes the need to instantiate the class, and would be called instead using the Type.Method() syntax, like MyClass.MyMethod().
You can also forgo adding a reference by using a fully qualified path.
var myInstantiatedClass = new MyProject.MyCore.MyClass()
Of course, if this code is in a different project, or assembly, you'll have to add a reference to the project or binary to gain access to the types it provides.
This example may be your answer
Or you can use static methods like
namespace MyProject.MyCore {
public class MyClass {
public static void MyMethod() { }
}
}
And you can use this method from another class
MyProject.MyCore.MyClass.MyMethod();

Stop a For Loop and start it at next instance where it stopped

So this loop is my first attempt at changing many things. I'm not sure I'm going about it the right way. This is for a rught/wrong answer game. Each time they answer wrong, the loop is called.
In my head it would go to the if related to numAttempts. So if numAttempts ==4 you would see "Wrong Answer 2 tries left!" But each time until the fifth attempt, when the loop is called it always starts at the top regardless of the numattempts.
To mitigate this I also tried adding numAttempts++ in the message check (wrong) code block.
I like the idea of the four loop, because based on each wrong answer a different image will appear, based on HangmanImage() --not currently defined--
I've tried break and return between the for if statements but it isn't working. Can you help me when the loop is called to start the loop where numAttempts =. EX. start at numAttempts==2? And stop the loop after the specific instance is completed?
I'm new to coding and trying to make it work. I appreciate your Patience if my work is 100% wrong or that I shouldn't have done a four look. reading a book and the web is great, but every now again, especially in the beginning people need guidance. Please take a moment and push me in the right direction.
Thank you for your time.
int numAttempts = (0); // global variable, at the start of the class. This allows the variable to be used anywhere with the current value
int maxAttempts = (5);
static void UpdateImage()
{
for (int numAttempts = 0; numAttempts < 6; numAttempts++)
{
if (numAttempts == (1))
{
MessageBox.Show("Wrong Answer 4 tries left!");
{
// HangmanImage();
}
}
else
if (numAttempts == (2))
{
MessageBox.Show("Wrong Answer 3 tries left!");
{
// HangmanImage();
}
}
else
if (numAttempts == (3))
{
MessageBox.Show("Wrong Answer 2 tries left!");
{
// HangmanImage()
}
}
else
if (numAttempts == (4))
{
MessageBox.Show("Wrong Answer 1 try left!");
{
// HangmanImage()
}
}
else
if (numAttempts == (5))
{
MessageBox.Show("You Lose!");
{
// HangmanImage();
}
}
}
}
Here is a working answer: https://dotnetfiddle.net/Z2BaYs
This is the code. Basically, you use the for loop to keep the game in play until the user either runs out of attempts or answers correctly.
using System;
public class Program
{
public static void Main()
{
var maxAttempts = 5;
var correctAnswer = "Edam";
for(int actualAttempts = 1; actualAttempts <= maxAttempts; ++actualAttempts)
{
Console.WriteLine("What is the only cheese that's made backwards?");
Console.WriteLine("Attempt #" + actualAttempts);
var answer = Console.ReadLine();
if(answer.Equals(correctAnswer))
{
Console.WriteLine("Correct!");
break;
}
switch(actualAttempts)
{
case 1:
Console.WriteLine("Whoa. Nice try.");
break;
case 2:
Console.WriteLine("Nope. Wrong.");
break;
case 3:
Console.WriteLine("Incorrect sir!");
break;
case 4:
Console.WriteLine("Still not the correct answer.");
break;
case 5:
Console.WriteLine("...and your done.");
break;
default :
break;
}
}
}
}
This is some example output/input.
What is the only cheese that's made backwards?
Attempt #1
Cheddar
Whoa. Nice try.
What is the only cheese that's made backwards?
Attempt #2
Mozarella
Nope. Wrong.
What is the only cheese that's made backwards?
Attempt #3
Havarti
Incorrect sir!
What is the only cheese that's made backwards?
Attempt #4
Swiss
Still not the correct answer.
What is the only cheese that's made backwards?
Attempt #5
Edam
Correct!
I can tell that you are doing this for school, so I don't want to give much away. But too your question, you are wanting to keep the same iteration in the loop, if I am understanding you. Just to try and stick to your code, you would need to pass in a variable and return one on the function. Like this
int updateImage(int count)
{
for(count < 6; count++)
{
Do what you need;
}
return count;
}
That way you can pass your iteration in and out of the function. Hope this helps.

Categories

Resources