I am trying to get my menu to repeat, so after selecting and doing option 1, it will got back to the menu and ask for another option to be chosen
class Program
{
static void Main(string[] args)
{
FootballTeams MyCode = new FootballTeams();
MyCode.ListInit();
MyCode.DisplayMenu();
MyCode.AddTeams();
Console.ReadLine();
MyCode.ListInit();
MyCode.DisplayMenu();
MyCode.DisplayTeams();
Console.ReadLine();
MyCode.ListInit();
MyCode.DisplayMenu();
MyCode.Delete();
Console.ReadLine();
MyCode.ListInit();
MyCode.DisplayMenu();
MyCode.TeamSearch();
Console.ReadLine();
}
}
Here are the methods with the contents taken out:
class FootballTeams
{
public FootballTeams(){ }
List<string> teams;
public void ListInit()
public void DisplayMenu()
{
Console.WriteLine("Football Manager");
Console.WriteLine();
Console.WriteLine("1. Add a Football team");
Console.WriteLine("2. List the Football teams");
Console.WriteLine("3. Search for a Football team");
Console.WriteLine("4. Delete a team");
Console.ReadLine();
}
public void AddTeams()
{
Console.WriteLine("Enter a team to be added: ");
string userinput = Console.ReadLine();
if (teams.Count < 10)
{
if (userinput != "Colchester")
{
teams.Add(userinput);
foreach (var item in teams)
Console.Write(item.ToString() + " ");
}
else
Console.Write("NOT ALLOWED");
}
else
Console.Write("MAXIMUM LIMIT REACHED");
}
public void DisplayTeams()
{
foreach(var item in teams)
Console.Write(item.ToString() + " ");
}
public void TeamSearch()
{
Console.WriteLine("Please enter the team you wish to search for: ");
string userinput = Console.ReadLine();
if (teams.Contains(userinput))
Console.WriteLine("Success, team " + userinput);
}
public void Delete()
{
Console.WriteLine("Enter a team you wish to delete: ");
string userinput = Console.ReadLine();
teams.Remove(userinput);
foreach (var item in teams)
Console.Write(item.ToString() + " ");
}
I know I have worded this poorly, so I hope that someone understands what I'm asking :P
You can use a do while loop for the purpose
Make a little modification to your DispalyMenu() method and return the result like this
static public int DisplayMenu()
{
Console.WriteLine("Football Manager");
Console.WriteLine();
Console.WriteLine("1. Add a Football team");
Console.WriteLine("2. List the Football teams");
Console.WriteLine("3. Search for a Football team");
Console.WriteLine("4. Delete a team");
Console.WriteLine("5. Exit");
var result = Console.ReadLine();
return Convert.ToInt32(result);
}
and write this in your Main() method
int userInput = 0;
do
{
userInput = DisplayMenu();
}while(userInput!=5);
So for the time being the user does not enter '5', the code will execute in the loop.
Hope that helps.
See Console.ReadKey().
Replace your main function with:
static void Main(string[] args) {
FootballTeams MyCode = new FootballTeams();
MyCode.ListInit();
ConsoleKeyInfo cki;
do {
MyCode.DisplayMenu();
cki = Console.ReadKey(false); // show the key as you read it
switch (cki.KeyChar.ToString()) {
case "1":
MyCode.AddTeams();
break;
case "2":
MyCode.DisplayTeams();
break;
// etc..
}
} while (cki.Key != ConsoleKey.Escape);
}
Essentially, you need to loop until they press the Escape key. Each time you read the key, you can execute the action selected.
There is a nuget package for this now
https://github.com/splttingatms/EasyConsole
Example
After adding the nuget package the Menu can be implemented the following way, This is a very Basic option
static void Main(string[] args)
{
var menu = new EasyConsole.Menu()
.Add("foo", () => Console.WriteLine("foo selected"))
.Add("bar", () => Console.WriteLine("bar selected"));
menu.Display();
}
In the action you can place Any Method to run when selected
This will output something like this
foo
bar
Choose an option:
Related
I have this app that I'm writing in C# just for practice purposes, this is the code,
using System;
namespace Stock_Control
{
class Program
{
static void Main(string[] args)
{
int qty, index;
string name, location, code;
Item item = new Item();
ConsoleKeyInfo opt;
do
{
Console.Clear();
Console.WriteLine();
Console.WriteLine("******************** STOCK CONTROL SOFTWARE *********************");
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Chose a option:");
Console.WriteLine("1 - Add item.");
Console.WriteLine("2 - View Stock.");
Console.WriteLine("3 - Remove item.");
Console.WriteLine("4 - Press 'Escape' to exit.");
opt = Console.ReadKey(true);
switch (opt.KeyChar.ToString())
{
case "1":
Console.WriteLine();
Console.Write("Enter the item code:");
code = Console.ReadLine();
Console.Write("Enter the item quantity:");
qty = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the item name:");
name = Console.ReadLine();
Console.Write("Enter the item location:");
location = Console.ReadLine();
item.add(code, qty, name, location);
break;
case "2":
Console.WriteLine("teste");
//item.view();
break;
case "3":
Console.WriteLine();
Console.WriteLine("Enter the index of the item to be removed:");
index = Int32.Parse(Console.ReadLine());
item.remove(index);
break;
}
} while (opt.Key != ConsoleKey.Escape);
}
}
}
It works fine but for some reason, when i wrapped around a loop, the second case in the switch statement stop working, once i remove the loop everything works fine. I can't figured out whats wrong.
Can someone help me with that?
Thanks.
It works still just fine but when you added the loop you do your Console.WriteLine("teste"); item.view(); in case "2" and then immediately start again = clear the console so you do not see anything.
I made a program that calculates the temperature in different ways.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Excercise_7
{
class Program
{
static void Main(string[] args)
{
showBegin();
decide();
secondPlay();
showEnd();
}
// Decide code
static void decide() {
int choice;
string input;
input = Console.ReadLine();
int.TryParse(input, out choice);
if (choice == 1)
{
Console.WriteLine("");
celciusSystem();
}
else if (choice == 2)
{
Console.WriteLine("");
farenheitSystem();
}
else if (choice == 3)
{
Console.WriteLine("");
kelvinSystem();
}
else {
Console.WriteLine("");
Console.WriteLine("Make sure u write a number between 1 and 3! No text!");
Console.WriteLine("");
showBegin();
decide();
}
}
static void secondPlay()
{
int choice2;
string input;
Console.WriteLine("");
Console.WriteLine("Type 1 to play again, type 2 to close the application");
input = Console.ReadLine();
int.TryParse(input, out choice2);
}
// Begin code
static void showBegin()
{
Console.WriteLine("Welcom at the temperature calculator, pick the mode u prefer!");
Console.WriteLine("Press 1 for Celcius mode");
Console.WriteLine("Press 2 for Fahrenheit mode");
Console.WriteLine("Press 3 for Kelvin mode");
Console.WriteLine("Press the correct number and then hit the enter button!");
Console.WriteLine("");
}
// Temperature Calculators
static void celciusSystem()
{
Console.WriteLine("This is the Celsius calculator");
Console.Write("Enter the amount of celsius: ");
int celsius = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("");
Console.WriteLine("The temperature in Kelvin = {0}", celsius + 273);
Console.WriteLine("The temperature in Fahrenheit = {0}", celsius * 18 / 10 + 32);
}
static void farenheitSystem()
{
Console.WriteLine("This is the Fahrenheit calculator");
Console.Write("Enter the amount of Fahrenheit: ");
int Fahrenheit = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("");
Console.WriteLine("The temperature in Kelvin = {0}", (Fahrenheit + 459.67) / 1.8);
Console.WriteLine("The temperature in Celsius = {0}", (Fahrenheit - 32) / 1.8);
}
static void kelvinSystem()
{
Console.WriteLine("This is the Kelvin calculator");
Console.Write("Enter the amount of Kelvin: ");
int Kelvin = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("");
Console.WriteLine("The temperature in Fahrenheit = {0}", Kelvin * 1.8 - 459.67);
Console.WriteLine("The temperature in Celsius = {0}", Kelvin - 273.15);
}
// End code
static void showEnd()
{
Console.WriteLine("");
Console.WriteLine("We hoped u enjoyed our application!");
Console.WriteLine("Press enter to exit...");
Console.ReadLine();
}
}
}
So now my question, I made a class called second play. Within that class i tried to make a kind a statement that would ask the user if he or she wanted to "play" again. So if they write 1 he should loop the game again.
I have tried it with this
if (choice2 == 1)
{
while (choice2 == 1) {
Console.WriteLine("");
showBegin();
decide();
}
}
else {
Console.WriteLine("");
Console.WriteLine("Cheers!!");
}
}
then he actually worked but not the way I wanted to because if the user writes 1 it will loop the first thing all over again. So the user can't quit the game any more.
I want the application to ask after every trail if he or she wants to play again by typing 1 or 2.
You already know how to read lines from the console, you also know how to use if to compare booleans, so why don't you just apply this and check if they wrote a 1 or 2?
private bool playAgain()
{
int number = 2; //Invalid option: close game
Int32.TryParse(Console.ReadLine(), out number);
if (number == 1)
{
return true;
}
else if (number == 2)
{
return false;
}
else
{
Console.WriteLine("Unknown option, quitting!");
return false;
}
}
Then you just have to use that function to determine if they want to play again in a do-loop.
static void Main(string[] args)
{
showBegin(); //Show begin sequence
do
{
decide();
secondPlay();
} while(playAgain()); //Play again if they want to
showEnd(); //Show end sequence when they decided not to play
}
Pro tip: use a switch-case statement instead of multiple if-else statements.
You can use a do while loop, which serves you well in cases like yours, when you want to execute your loop at least once:
do {
Console.WriteLine("");
showBegin();
decide();
//Ask for choice2 here
}
while(choice2 == 1);
Console.WriteLine("");
Console.WriteLine("Cheers!!");
To enter game loop, it is most useful to start with simple while or do-while.
while( conditionToRun )
{
//run the program
if( userWantToExit )
conditionToRun = false;
}
Or
do
{
// run the program
} while ( !userWantToExit )
This code shows the most basic stuff to handle this.
To apply on Your game/program, use:
static void Main(string[] args)
{
bool userWantToEnd = false;
showBegin();
while( !userWantToEnd)
{
decide();
userWantToEnd = IsUserWillingToContinue();
}
showEnd();
}
And adjust the SecondPlay() method into something like IsUserWillingToContinue():
public bool IsUserWillingToContinue()
{
int choice2;
string input;
Console.WriteLine("");
Console.WriteLine("Type 1 to play again, type 2 to close the application");
input = Console.ReadLine();
int.TryParse(input, out choice2);
return choice2 == 1;
}
Adding more info based on comment of #devRicher - You should split up a bit the code so it work in this way
bool runAgain = true;
Console.WriteLine("Begin info: (Hello this is XY game.)");
while(runAgain)
{
Console.WriteLine("You have 3 options: 1, 2, 3");
PickOptionAndRunTheCode();
bool runAgain = DoYouWantToContinue();
Console.Clear(); // clear the Console screen (next time You will see only options, not the text on first run).
}
I would recommend to get more knowledge about games to go to this page -> http://gameprogrammingpatterns.com/ (and read the book)
Check this pattern: Game Loop
I have a project in which users enter a job description, hours needed, and hourly pay for 5 jobs. Once entered they must choose 2 of the jobs they entered to combine into one job. I'm unsure how to retrieve the job number that they enter from the array (jobArray) (job 1 and job2 for example).
So if they enter in job 1 as mowing, and job 2 as trimming they should have the option to combine both to make mowing and trimming.
Here is my code, any help would be appreciated.
namespace DemoJobs
{
class Class2
{
public static Job[] jobArray = new Job[5];
static void Main(string[] args)
{
string option;
do
{
Console.WriteLine("Menu");
Console.WriteLine("\t1. Enter Jobs");
Console.WriteLine("\t2. Combine 2 Jobs");
Console.WriteLine("\t3. Display All Jobs");
Console.WriteLine("\t4. Exit");
option = Console.ReadLine();
switch (option)
{
case "1":
Console.Clear();
EnterJobs();
break;
case "2":
Console.Clear();
//CombineJobs();
break;
case "3": //display jobs
DisplayAllJobs();
break;
case "4":
break;
default:
Console.WriteLine("Option invalid.");
Console.ReadLine();
break;
}
} while (option != "4");
Console.WriteLine("Press enter to exit the window.");
Console.ReadLine();
}
private static void EnterJobs()
{
for (int i = 0; i < jobArray.Length; i++)
{
// int totFee;
Job job = new Job();
Console.WriteLine("Job " + i);
Console.WriteLine("Enter a job description.");
job.Description = Console.ReadLine();
Console.WriteLine("Enter the amount of hours required to complete the job.");
job.hoursToComplete = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the hourly rate for the job.");
job.hourlyRate = Convert.ToDouble(Console.ReadLine());
jobArray[i] = job;
//calcing total fee
job.totalFee = job.hourlyRate * job.hoursToComplete;
}
Console.WriteLine(" ");
} //end of enterjobs
//combining jobs
private static void CombineJobs(Job first, Job second)
{
Console.WriteLine("Which 2 jobs would you like to combine?");
first.Description = Console.ReadLine();
}
private static void DisplayAllJobs()
{
// jobArray.ToList().Sort();
//sorting jobs from totalFee
Array.Sort(jobArray);
//printing array
Console.WriteLine(jobArray[0].ToString());
Console.WriteLine(jobArray[1].ToString());
Console.WriteLine(jobArray[2].ToString());
Console.WriteLine(jobArray[3].ToString());
Console.WriteLine(jobArray[4].ToString());
}
}
}
You can search the array like this.
Job jobToFind = jobArray.FirstOrDefault(s => s.Description.Equals(first.Description));
Job job2ToFind = jobArray.FirstOrDefault(s => s.Description.Equals(second.Description));
and then combine jobs as you see fit.
newJob.Description = jobToFind.Description + job2ToFind.Description;
// newJob.Pay = more combining here etc.
I'm not sure how to explain this but I'll try my best since I'm new to c# programming.
I have created a Menu System
string sChoice;
//Menu
Console.WriteLine("1 - Instructions");
Console.WriteLine("2 - New User");
Console.WriteLine("3 - Record & Score");
Console.WriteLine("4 - Exit System");
Console.Write("Please enter your choice between 1-4: ");
sChoice = Console.ReadLine();
Pressing 1 will then take you to the instructions section of the console application and so on.
//Instructions
if (sChoice == "1")
{
Console.WriteLine();
Console.WriteLine("*Instructions*");
Console.WriteLine();
I have tried an else statement which will repeat the menu and prompt the user of an invalid key, however this will only repeat itself another 3 times before closing. Is there a way for me to block any other keys other than 1-4 being entered or a solution to my problem
Because as it seems, if any key other than 1-4 is pressed then the console application will simply close.
This question remembers me when I was young and started programming.
Maybe you want someting like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
while (true)
{
int mainMenuOption = OptionMenu("Instructions", "New User", "Record & Score", "Exit System");
switch (mainMenuOption)
{
case 1: Instructions(); break;
case 2: NewUser(); break;
case 3: RecordAndScore(); break;
case 4: Console.WriteLine("Goodbye.."); return;
}
}
}
static void Instructions()
{
// Handle Instructions here
Console.WriteLine("Instrucctions done");
}
static void NewUser()
{
// Handle New User here
Console.WriteLine("New user done");
}
static void RecordAndScore()
{
// handle recorde and score here
Console.WriteLine("Record & score done");
}
static int OptionMenu(params string[] optionLabels)
{
Console.WriteLine("Please Choose an option");
for (int optionIndex = 0; optionIndex < optionLabels.Length; optionIndex++)
{
Console.Write(optionIndex + 1);
Console.Write(".- ");
Console.WriteLine(optionLabels[optionIndex]);
}
while (true)
{
var input = Console.ReadLine();
int selectedOption;
if (int.TryParse(input, out selectedOption) && selectedOption > 0 && selectedOption <= optionLabels.Length)
{
return selectedOption;
}
else
{
Console.WriteLine("Invalid option, please try again");
}
}
}
}
}
I have a C# Console application that I would like to write using this code but I have tried a couple of things and seem to run a block. I am trying to make a timer on a game at the top but the only way for me to print to the console and sort of keep it is by eliminating the Console.Clear from this Code. Is there a way that I can keep the Countdown timer at the top while Console.Clear is only active for the timer not everything in the console window?
Additionally, does anyone know how to convert the number to format a timeclock like so: 00:05:00?
using System;
using System.Timers;
namespace TimerExample
{
class Program
{
static Timer timer = new Timer(1000);
static int i = 10;
static void Main(string[] args)
{
timer.Elapsed+=timer_Elapsed;
timer.Start();
Console.Read();
}
private static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
i--;
Console.Clear();//here is where I disable and it prints out all the timer in the widow
// if I leave this console window it wipes out my print?
Console.WriteLine("=================================================");
Console.WriteLine(" First Quarter");
Console.WriteLine("");
Console.WriteLine(" Time Remaining: " + i.ToString());
Console.WriteLine("");
Console.WriteLine("=================================================");
if (i == 0)
{
Console.Clear();
Console.WriteLine("");
Console.WriteLine("==============================================");
Console.WriteLine(" Huddle ! ! ! !");
Console.WriteLine("");
Console.WriteLine(" Timeout");
Console.WriteLine("==============================================");
timer.Close();
timer.Dispose();
}
GC.Collect();
}
}
}
Okay here is the extension of the code
I am having issues trying to keep my game on the bottom of the window and really trying to code the countdown timer to be active as soon as the game starts but also keeping my game selection print for the user any suggestions would help
{}....
++++++++++++++++++++++
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace TimerExample
{
class Program
{
static Timer timer = new Timer(1000);
static int i = 300;
private void Run()
{
Header();
Story();
timer.Elapsed += timer_Elapsed;
timer.Start();
// Console.ReadLine();
bool appRunning = true;
bool playerExists = false;
//bool drinkExists = false;
int userInput = 0;
//loop
while (appRunning)
{
Console.WriteLine("\n\n....................\n");
Console.WriteLine("What would you like to do?\n");
Console.WriteLine("1.)Choose Role 2.)Show Credits 3.)Exit Application");
Console.WriteLine(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
Console.WriteLine("Chose a player: ");
//take user input and ocnvert to string to int data type
userInput = Int16.Parse(Console.ReadLine());
//switch statement o flip through menu options
switch (userInput)
{
case 1:
//intelligence to monitor that we only make one sandwich per customer
if (playerExists == false)
{
Console.WriteLine("Does my sandwich exist? Answer is" + playerExists);
Console.WriteLine("Lets make you a snadwich, then shall we??\n");
//set default sandwich variable values
String Quarterback = "Quarterback";
String Runningback = "Runningback";
String Receiver = "Receiver";
//get type of bread from user
Console.Clear();
Console.WriteLine("What type of play would you like?");
Console.WriteLine("Short, Run, Pass Long");
Quarterback = Console.ReadLine();
//get type of Option from user
Console.Clear();
Console.WriteLine("What type of play would you like?");
Console.WriteLine("Left, Right, or Staight");
Runningback = Console.ReadLine();
//get type of jelly from user
Console.Clear();
Console.WriteLine("What type of play would you like?");
Console.WriteLine("Long, Short, or Mid");
Receiver = Console.ReadLine();
//create an instance of the sandwichclass
Player myPlayer = new Player(Quarterback, Runningback, Receiver);
myPlayer.AboutPlayer();
playerExists = true;
}
{
Console.WriteLine("You've already made your role choice!");
}
break;
case 2:
ShowCredits();
break;
case 3:
appRunning = false;
break;
default:
Console.WriteLine("You have not chosen a valid option.");
Console.WriteLine("Please chose from the menu....");
break;
}//end switch
}//end of while
}//end of private void run
private static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
i--;
// Console.Clear();
Console.WriteLine("=================================================");
Console.WriteLine(" First Quarter");
Console.WriteLine("");
Console.WriteLine(" Time Remaining: " + i.ToString());
Console.WriteLine("");
Console.WriteLine("=================================================");
if (i == 0)
{
Console.Clear();
Console.WriteLine("");
Console.WriteLine("==============================================");
Console.WriteLine(" Time Out ! ! ! !");
Console.WriteLine("");
Console.WriteLine(" Huddle");
Console.WriteLine("==============================================");
timer.Close();
timer.Dispose();
}
GC.Collect();
}//end ofprivatestaticvoidtimer
class Player
{
//set default vaulues for our sandwich type
private String Quarterback = "";
private String Runningback = "";
private String Receiver = "";
//build the constructor for the sandwich class
public Player(String Quarterback, String Runningback, String Receiver)
{
this.Quarterback = Quarterback;
this.Runningback = Runningback;
this.Receiver = Receiver;
}
public void AboutPlayer()
{
Console.WriteLine("You have made your selection!");
Console.WriteLine("As");
Console.WriteLine("Press enter to coninue...");
Console.ReadLine();
}
}
static void Main(string[] args)
{
Console.ReadKey();
Program myProgram = new Program();
myProgram.Run();
Console.ReadLine();
}//endofmain
private void ShowCredits()
{
Console.Clear();
Console.WriteLine("An in-class assigment for Intro to Programming");
Console.WriteLine("Cesar Mojarro");
}
private void Header()
{
Console.WriteLine("++++++++++++++++++++++++++++++++++++++++++++++++++++++");
Console.WriteLine("+++++++1967 Tackle Football Championships v.1.0 ++++++");
Console.WriteLine("++++++++++++++Studded Diamond Cup ++++++++++++++++++++");
Console.WriteLine("++++++++++++++++++++++By IAM!+++++++++++++++++++++++++");
Console.WriteLine("++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
Console.ReadKey();
}
private void Story()
{
Console.WriteLine("It's the year 1967 and in the First Quarter Steve Miller is running Quarterback for the Packs.");
Console.WriteLine("Young Styler is running Quarterback for the Texan Ranchers.");
Console.WriteLine("Your frontline is hung over from the party last nite, ouch! ");
Console.WriteLine("The team owner is ready to collect on the pay day from the Studded Diamond Cup");
Console.WriteLine("Don't let him replace you for a rookie!");
Console.WriteLine("");
Console.WriteLine("");
Console.ReadKey();
Console.WriteLine("The Coin Toss is about to take place,\nyou are nervous and are about to take a chance at this tackle unit.");
Console.WriteLine("Rules are simple keep the ball running yards,\nstay head strong and keep your eye on defense!");
Console.WriteLine("Don't let them tackle you down and\nreturn you all the way to the goal line by allowing your apponent to score");
Console.WriteLine("");
Console.WriteLine("");
Console.WriteLine("");
Console.ReadKey();
}
}//endofProgram
}
Use Console.CursorLeft and Console.CursorTop to move the cursor to the line with the time, you can then overwrite that line with your new value.
private void UpdateTime(int i)
{
//Move to the first column.
Console.CursorLeft = 0;
//Move to the 4th row
Console.CursorTop = 3;
//Write your text. Extra spaces to overwrite old numbers
Console.Write(" Time Remaining: " + i.ToString() + " ");
}
You can be even more efficient by figuring out the column i is written to and just overwrite that.
private string _timeRemainingString = " Time Remaining: ";
private void UpdateTime(int i)
{
//Move to the first column that would have had numbers.
Console.CursorLeft = _timeRemainingString.Length;
//Move to the 4th row
Console.CursorTop = 3;
//overwrite just the number portion.
Console.Write(i.ToString() + " ");
}
Additionally, does anyone know how to convert the number to format a timeclock like so: 00:05:00
If i represents the number of seconds left in the game it the easiest solultion would be convert it in to a TimeSpan then you can use time span's formatting to get the format you want.
private void UpdateTime(int i)
{
Console.CursorLeft = _timeRemainingString.Length;
Console.CursorTop = 3;
var time = TimeSpan.FromSeconds(i);
//the `.ToString("c")` on a TimeSpan will give you a time in the format "00:00:00"
//you don't need the extra spaces anymore because the time will always be 8 digits long.
Console.Write(time.ToString("c"));
}