Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am trying to display an incremented value of an i in a loop of a console. That is, instead of showing "The object 0 has fallen", I want to display "The object 1 has fallen". How do I achieve this?
for(int i = 0; i<6; i++)
{
Debug.Log("The object: " +(i+1)+ " has fallen");
}
Your original sample works perfectly it already '
using System;
public class Program
{
public static void Main()
{
for(int i = 0; i<6; i++)
{
Debug.Log("The object: " +(i+1)+ " has fallen");
}
}
}
public static class Debug
{
public static void Log(string s) => Console.WriteLine(s);
}
https://dotnetfiddle.net/Q1shlY
prints:
The object: 1 has fallen
The object: 2 has fallen
The object: 3 has fallen
The object: 4 has fallen
The object: 5 has fallen
The object: 6 has fallen
You could of course also just start the loop at 1 instead of 0, also notice the change for the condition in the for loop from < to <=:
using System;
public class Program
{
public static void Main()
{
for(int i = 1; i<=6; i++)
{
Debug.Log("The object: " +i+ " has fallen");
}
}
}
public static class Debug
{
public static void Log(string s) => Console.WriteLine(s);
}
https://dotnetfiddle.net/rb76IS
prints:
The object: 1 has fallen
The object: 2 has fallen
The object: 3 has fallen
The object: 4 has fallen
The object: 5 has fallen
The object: 6 has fallen
A for-loop has 3 parts:
for(<initial state, runs once at beginning>; <condition, runs while true>; <iterator, runs after each iteration>
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/for
So this does exactly what you're asking.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int x = 0;
do
{
if (false)
{
Console.WriteLine("hold UP");
}
++x;
Console.WriteLine(x);
} while (false);
}
}
}
That's the compiler warning you that some part of your code will never be executed. In your case it refers to this part.
if (false)
{
Console.WriteLine("hold UP");
}
A similar thing would happen in cases like this:
void Test()
{
return;
// more code here.
}
//or
void Test2()
{
while(true) //loop forever.
{ }
// more code here.
}
Console.WriteLine("hold UP"); is unreachable because if (false) will never be true, thus the code in the following block can never be executed.
Andy is correct. For the code to run inside an If statement the conditions must be true. What you have there is a static condition of False, thus it will not enter into the If statement.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
So I'm currently learning C# and I'm on Recursive Factorials, I followed instructions to create an example of the base case and the recursive case. But the program doesn't seem to be identifying my integer.
using System;
namespace Recursive_factorial
{
class Program
{
static void Main()
{
Factorial(5);
}
public static int Factorial(int n)
{
if (n == 0)
{
return 1; //base case
}
else
{
return n * Factorial(n - 1); //recursive case
}
}
}
}
maybe the problem is that you never show the result, try with
using System;
namespace Recursive_factorial
{
class Program
{
static void Main()
{
Console.WriteLine(Factorial(5));
}
public static int Factorial(int n)
{
if (n == 0)
return 1;
else
return n * Factorial(n - 1);
}
}
}
Also you can add
Console.ReadKey();
Below the Console.WriteLine, to pause the execution before it closes
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();
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
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am making a vault application that requires a code to be entered in a specific order (1 2 3)
Now I have made that the vault will unlock when 1 2 and 3 are pressed, but the order doesn't matter at all.
I want to make that the vault ONLY unlocks when the button 1 is pressed first, 2 second and 3 thirth.
Thanks!
You might be overthinking this.
public bool VaultLock(string key)
{
if(key == "1234")
return true;
return false;
}
Append the numbers to a string and then match the string to the correct PIN.
private static string THECORRECTPIN = "1234";
private string _PinEntered{get;set;}
public void KeyPressed(string number)
{
_PinEntered += number;//here's the important bit
if(_PinEntered == THECORRECTPIN)
{
Unlock();
}
}
Make a statemachine that accepts an input (one letter) causing it to move to another state. 2.
States can be valid (all the input is valid), invalid (more input is needed) or error (valid state can never be reached again).
Give it five states:
1. Start, no input has been given, with a transition on input 1 to state 2.
2. Has a transition on input 2 to state 3.
3. Has a transition on input 3 to state 4.
4. Is a valid state, has no transitions
5. Error state, no transitions.
If an input is given that the current state has no stransitions for go to the error state.
Update, this concept can get very complicated, it forms the basics for search engines. This implementation is extremely basic:
namespace Algorithms
{
public class Automaat
{
public const char Epsilon = default(char);
private Graph current, valid;
public Automaat(string text)
{
Graph start = new Graph();
valid = new Graph();
current = start;
foreach (var letter in text)
{
var next = new Graph();
current.SetTransition(next, letter);
current = next;
}
valid = current;
current = start;
}
public void Input(char symbol)
{
if (current != null)
current = current.Next(symbol);
}
public bool IsValid()
{
return current == valid;
}
/// <summary>
/// Holds connections to other graphs, the position of that graph in the array relative to the alphabet determines what symbol that link uses.
/// </summary>
private class Graph
{
private static char[] alphabet;
Graph[] nodes;
public Graph()
{
nodes = new Graph[26];
}
public void SetTransition(Graph graph, char symbol)
{
nodes[ConvertToIndex(symbol)] = graph;
}
public Graph Next(char symbol)
{
return nodes[ConvertToIndex(symbol)];
}
private int ConvertToIndex(char symbol)
{
return symbol - 'a';
}
}
}
}