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.
Related
I can't enter in the case 2 of the switch statement and I don't know why. If I remove the do while loop the code runs perfectly. It's about something with the memory of the structure array? Here is the code:
class Notebook {
struct Student
{
public String id;
public String name;
public void showInfo(Student x) {
Console.WriteLine("\t ID: " + x.id);
Console.WriteLine("\t Name: " + x.name);
}
}
static void Main(string[] args){
bool display = true;
int studentNum = int.Parse(Console.ReadLine());
Student[] students = new Student[studentNum];
do {
Console.Clear();
Console.WriteLine("1.- Insert register");
Console.WriteLine("2.- Show register");
Console.WriteLine("3.- Exit");
String opc = Console.ReadLine();
switch (opc) {
case "1":
Console.Clear();
for(int i = 0; i < students.Length; ++i){
Console.WriteLine("Name of the student " + (i+1));
students[i].name = Console.ReadLine();
Console.WriteLine("ID of the student " + (i+1));
students[i].id = Console.ReadLine();
}
break;
case "2":
Console.Clear();
for(int i = 0; i < students.Length; ++i){
students[i].showInfo(students[i]);
}
break;
case "3":
Console.Clear();
Console.WriteLine("bye");
display = false;
break;
}
}while(display);
}
}
I think that is "something" in the memory of opc string that avoids the case 2.
Your problem is the Console.Clear statement that you run at start of do while loop. Comment that line and you will see that your code is going to case "2".
Its going to case "2" even in your original code, but console is every time being cleared at start of do while loop and so you don't see the statements written by case "2" logic.
There is no memory problem as you suspected.
The do while loop should have Console.Clear commented as in code below.
do {
//Console.Clear();
Console.WriteLine("1.- Insert register");
Console.WriteLine("2.- Show register");
Console.WriteLine("3.- Exit");
add a Console.ReadLine(); before break case "2".
case "2":
Console.Clear();
for (int i = 0; i < students.Length; ++i)
{
students[i].showInfo(students[i]);
}
Console.ReadLine();
break;
You write students informations and Call Console.Clear() after that
I am fairly new to C# and currently building a simple ATM app. I am attempting to write code to return the user to the main menu according to his/her entry of the letter M. The break, continue, goto or return keywords do not seem to work in my scenario; perhaps I used them incorrectly. The statement directly below is where I would like to jump to.
Console.WriteLine("Select an option? \n VIEW BALANCE (B1) checking, (B2) saving \n DEPOSIT (C1) checking, (C2) saving \n WITHDRAW (W1) checking, (W2) saving");
I would like to jump from the line JUMP (below) within the else if statement nested within the switch statement into the section of code above. How can I achieve this? any help is appreciated...thanks!
switch (response)
{
case "C1":
Console.WriteLine("How much would you like to deposit to your checking account?");
string depositEntry = Console.ReadLine();
double checkingBalance = Convert.ToInt32(depositEntry) + currentCheckingBalance;
currentCheckingBalance += checkingBalance;
Console.WriteLine("Your current checking balance is " + checkingBalance + "\n (X) Exit, (M) Main Menu" );
string selection = Console.ReadLine().ToUpper();
if (selection == "X")
{
return;
}
else if (selection == "M")
{
***JUMP***
}
else
{
Console.WriteLine("Your entry was invalid");
}
break;
case "C2":
break;
case "W1":
Using a jump statement usually indicates the flow of logic is jumbled. I try to avoid any kind of jumps if necessary. The code below prints out a main menu and if the user types “x” the program will quit. If the user selects one of the other options, a message is simply printed out indicating what the user selected. After the user presses any key, the console clears and the main menu is re-displayed.
In the main menu, if the user does not type one of the selections, then the selection is ignored, the console is cleared, and the menu is reprinted. No error is displayed indicating invalid selections.
This does not require the user to type “m” to go back to the main menu. After a selection is made for Deposit/withdraw/… after the method is finished the code will automatically return to the main menu.
I am guessing this may be what you are looking for. Hope this helps.
static void Main(string[] args) {
string userInput = "";
while ((userInput = GetMainSelection()) != "x") {
switch (userInput) {
case "c1":
Console.WriteLine("C1 Deposit Checking method");
break;
case "c2":
Console.WriteLine("C2 Deposit Savings method");
break;
case "b1":
Console.WriteLine("B1 View Balance Checking method");
break;
case "b2":
Console.WriteLine("B2 View Balance Savings method");
break;
case "w1":
Console.WriteLine("W1 Withdraw Checking method");
break;
case "w2":
Console.WriteLine("W2 withdraw Savings method");
break;
}
Console.WriteLine("Press Any Key to continue"); // <-- show what method was just used
Console.ReadKey();
Console.Clear();
}
Console.Write("Press any key to exit the program");
Console.ReadKey();
}
private static string GetMainSelection() {
string userInput = "";
while (true) {
Console.WriteLine("Select an option? \n VIEW BALANCE (B1) checking, (B2) saving \n DEPOSIT (C1) checking, (C2) saving \n WITHDRAW (W1) checking, (W2) saving. (X) to EXit");
userInput = Console.ReadLine().ToLower();
if (userInput == "b1" || userInput == "b2" || userInput == "c1" || userInput == "c2" || userInput == "w1" || userInput == "w2" || userInput == "x") {
return userInput;
}
else {
Console.Clear();
}
}
}
Put the JUMP code in a function and return.
public void MainMenu() {
// Show the main menu
}
public void Response(string response) {
switch (response)
{
case "C1":
Console.WriteLine("How much would you like to deposit to your checking account?");
string depositEntry = Console.ReadLine();
double checkingBalance = Convert.ToInt32(depositEntry) + currentCheckingBalance;
currentCheckingBalance += checkingBalance;
Console.WriteLine("Your current checking balance is " + checkingBalance + "\n (X) Exit, (M) Main Menu" );
string selection = Console.ReadLine().ToUpper();
if (selection == "X")
{
return;
}
else if (selection == "M")
{
***JUMP***
MainMenu();
return;
}
else
{
Console.WriteLine("Your entry was invalid");
}
break;
case "C2":
break;
case "W1":
}
}
Similar to the already given answer, I suggest breaking this out. Here's an example:
The Main method:
static void Main(string[] args) {
string input = null;
do {
input = Console.ReadLine();
ParseInput(input);
} while (input != "X");
}
ParseInput:
static void ParseInput(string input) {
switch (input) {
case "X": //from Main(), this will close the app
return;
case "M":
MainMenu();
break;
case "C1":
ShowAccount("C1"); //move your deposit/withdraw logic into a method and call with the selected account
return;
//other accounts
default:
break; //error message?
}
}
and MainMenu:
static void MainMenu() {
Console.WriteLine("Select an option? \n VIEW BALANCE (B1) checking, (B2) saving \n DEPOSIT (C1) checking, (C2) saving \n WITHDRAW (W1) checking, (W2) saving");
}
This should let you read the input in a loop and the ParseInput function can handle your individual cases. You may also want to call MainMenu() at the start, so it shows from the beginning.
It works like this:
Get input from the user
Pass the input to ParseInput() which decides where to go next.
Any functions hit in ParseInput() will execute, writing to the console or asking for further input
Once that function returns, while (input != "X") evaluates. If input != "X", goto 1, else exit.
I suggest you use goto C# reference.
static void Main()
{
int x = 200, y = 4;
int count = 0;
string[,] array = new string[x, y];
// Initialize the array:
for (int i = 0; i < x; i++)
for (int j = 0; j < y; j++)
array[i, j] = (++count).ToString();
// Read input:
Console.Write("Enter the number to search for: ");
// Input a string:
string myNumber = Console.ReadLine();
// Search:
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
if (array[i, j].Equals(myNumber))
{
goto Found;
}
}
}
Console.WriteLine("The number {0} was not found.", myNumber);
goto Finish;
Found:
Console.WriteLine("The number {0} is found.", myNumber);
Finish:
Console.WriteLine("End of search.");
// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
Output for the Input 44 would be:
Enter the number to search for: 44
The number 44 is found.
End of search.
See here for the MSDN reference.
I'm beginner in programming and I'm trying this simple program of getting user name and sorting it and so on.
class Program
{
static void Main(string[] args)
{
int number;
dynamic y;
string[] answer = new string[10];
cases:
Console.WriteLine("Enter the options given below 1.Add students\n 2.View all details\n 3.Sorting\n 4.Exit\n");
int input = Convert.ToInt16(Console.ReadLine());
switch (input)
{
case 1:
Console.WriteLine("Enter the Number of Students to be added to the List");
number = Convert.ToInt16(Console.ReadLine());
for (int i = 0; i < number; i++)
{
answer[i] = Console.ReadLine();
}
case 2:
foreach (var item in answer)
{
Console.WriteLine(item.ToString());
}
break;
case 3:
Array.Sort(answer);
foreach (var item in answer)
{
Console.WriteLine(item.ToString());
}
break;
case 4:
Console.WriteLine("Are you sure you want to exit");
Console.WriteLine("1 for Yes and N for No");
y = (char)Console.Read();
if ((y == 1))
{
goto cases;
}
else
{
goto thankyou;
}
thankyou:
Console.WriteLine("thank you");
break;
}
Console.WriteLine("Are you sure you want to exit");
Console.WriteLine("Y for Yes and 1 for No");
y = (char)Console.Read();
if ((y == 1))
{
goto cases;
}
else
{
goto thankyou;
}
}
}
My problem is that after every operation I have ask whether it should continue or not. I have added go-to statements but when pressed No its shows an exception for input variable that I have declared.
Can I use the go-to method or Is there any way we can do this ?
Any suggestions what is wrong here??
If you want a loop in your program you should use one of the loop constructs in C#. In this case a while loop would work:
bool keepPrompting = true;
while(keepPrompting) {
Console.WriteLine("Enter the options given below 1.Add students\n 2.View all details\n 3.Sorting\n 4.Exit\n");
int input = Convert.ToInt16(Console.ReadLine());
// The case statement on input goes here
Console.WriteLine("Are you sure you want to exit");
Console.WriteLine("Y for Yes and 1 for No");
var y = (char)Console.Read();
if (y != 'y')
keepPrompting = false;
}
Console.WriteLine("thank you");
goto is almost never used in C# (or any other language) for that matter because it's hard to follow a program that can jump around to almost any location while a loop has a defined flow.
You shouldn't do this with goto. You should always avoid goto entirely. If you think for some reason that you need to use goto, you should find a way to do it without goto. Here's an example of how to do this while avoiding goto.
class Program
{
static void Main(string[] args)
{
int number;
dynamic y;
string[] answer = new string[10];
bool result = false;
while(!result) {
Console.WriteLine("Enter the options given below 1.Add students\n 2.View all details\n 3.Sorting\n 4.Exit\n");
int input = Convert.ToInt16(Console.ReadLine());
switch (input)
{
case 1:
Console.WriteLine("Enter the Number of Students to be added to the List");
number = Convert.ToInt16(Console.ReadLine());
for (int i = 0; i < number; i++)
{
answer[i] = Console.ReadLine();
}
break;
case 2:
foreach (var item in answer)
{
Console.WriteLine(item.ToString());
}
break;
case 3:
Array.Sort(answer);
foreach (var item in answer)
{
Console.WriteLine(item.ToString());
}
break;
case 4:
Console.WriteLine("Are you sure you want to exit");
Console.WriteLine("1 for Yes and N for No");
result = ((char)Console.Read()) == 'y';
break;
}
}
Console.WriteLine("thank you");
}
}
}
static void Main(string[] args)
{
// First you need a few loops, avoid goto's at all costs they make code much harder to read
// There are better ways to do this but this will get it done
// List<string> answer = new List<string>(); would be better here because it resizes automatically when adding
// I left it like this because it looks like a school project
List<string> answer = new List<string>(); // create variable before loops so it is not recreated on each iteration
bool exit = false; // create bool variable and use it to exit infinite loop by setting it to true when user chooses option 4
for (;;) // create outer infinit loop to so the code will execute until you want you break; when option 4 is entered
{
int option;
for (;;)// create infinite loop to get user input for which option they want
{
Console.Clear();
Console.WriteLine("Enter the options given below\n1.Add students\n2.View all details\n3.Sorting\n4.Exit\n");
if (int.TryParse(Console.ReadLine(), out option) && option >= 1 && option <= 4)
{ break; /*user entered valid option so we break from this infinit loop*/ }
else
{ Console.Clear(); /*User did not enter a valid option so clear the console window*/ }
}
switch (option) // switch cases to handle each of the possible options entered
{
case 1:
// user chose option 1
int number = 0;
while (number <= 0)
{
Console.Clear();
Console.WriteLine("Enter the number of students to add.");
int.TryParse(Console.ReadLine(), out number);
// Because "answer" is now a list it does not have to be sized
for(int i=0;i<number;i++)
{
Console.Clear();
Console.WriteLine("Enter Name: ");
// with a list, the previous list of students are not wiped out
// we also don't have to be carefull about writing outside array bounds because of the add method
answer.Add(Console.ReadLine());
}
}
break; // break out of case 1
case 2:
// user chose option 2
break;// break out of case 2
case 3:
// user chose option 3
if (answer.Count > 0)
{
Console.Clear();
Console.WriteLine("Sorted student names:");
answer.Sort(); // List<string> have a Sort member method
Console.WriteLine(string.Join("\n", answer));
}
else
{ Console.WriteLine("No students exist to sort or list."); }
Console.ReadLine(); // pause screen for reading
break;// break out of case 3
case 4:
// user chose option 4
while (true) // loop until a Y or 1 is entered
{
Console.WriteLine("Are you sure you want to exit\nY for YES and 1 for NO");
char y = (char)Console.Read();
if (y == 'Y' || y == 'y')
{ exit = true; break; /*user is sure they want to exit*/ }
else if (y == '1')
{ Console.Clear(); break; /*user decided not to exit*/ }
else
{ Console.Clear(); }
}
break; // break out of case 4
}
if (exit) break; // if exit variable true then break out of outer infinite loop
}
}
static void Main(string[] args)
{
// First you need a few loops, avoid goto's at all costs they make code much harder to read
// There are better ways to do this but this will get it done
// List<string> answer = new List<string>(); would be better here because it resizes automatically when adding
// I left it like this because it looks like a school project
string[] answer = new string[0]; // create variable before loops so it is not recreated on each iteration
bool exit = false; // create bool variable and use it to exit infinite loop by setting it to true when user chooses option 4
for (;;) // create outer infinit loop to so the code will execute until you want you break; when option 4 is entered
{
int option;
for (;;)// create infinite loop to get user input for which option they want
{
Console.Clear();
Console.WriteLine("Enter the options given below\n1.Add students\n2.View all details\n3.Sorting\n4.Exit\n");
if (int.TryParse(Console.ReadLine(), out option) && option >= 1 && option <= 4)
{ break; /*user entered valid option so we break from this infinit loop*/ }
else
{ Console.Clear(); /*User did not enter a valid option so clear the console window*/ }
}
switch (option) // switch cases to handle each of the possible options entered
{
case 1:
// user chose option 1
int number = 0;
while (number <= 0)
{
Console.Clear();
Console.WriteLine("Enter the number of students to add.");
int.TryParse(Console.ReadLine(), out number);
answer = new string[number]; // re-initize number of students to add
for(int i=0;i<number;i++)
{
Console.Clear();
Console.WriteLine("Enter Name: ");
answer[i] = Console.ReadLine();
}
}
break; // break out of case 1
case 2:
// user chose option 2
break;// break out of case 2
case 3:
// user chose option 3
if (answer.Length > 0)
{
Console.Clear();
Console.WriteLine("Sorted student names:");
Array.Sort(answer);
Console.WriteLine(string.Join("\n", answer));
Console.ReadLine(); // pause screen for reading
}
break;// break out of case 3
case 4:
// user chose option 4
while (true) // loop until a Y or 1 is entered
{
Console.WriteLine("Are you sure you want to exit\nY for YES and 1 for NO");
char y = (char)Console.Read();
if (y == 'Y' || y == 'y')
{ exit = true; break; /*user is sure they want to exit*/ }
else if (y == '1')
{ Console.Clear(); break; /*user decided not to exit*/ }
else
{ Console.Clear(); }
}
break; // break out of case 4
}
if (exit) break; // if exit variable true then break out of outer infinite loop
}
}
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"));
}
I have 2 codes that I want to combine into 1 and am having a lot of trouble doing it. The code should ask for the group number then their donation amount and loop back until they press 0. Once they press 0 it should show the total for all groups. Here are the 2 different codes
code 1
using System;
public class TotalPurchase
{
public static void Main()
{
double donation;
double total = 0;
string inputString;
const double QUIT = 0;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString = Console.ReadLine();
donation = Convert.ToDouble(inputString);
while(donation != QUIT)
{
total += donation;
Console.WriteLine("Enter next donation amount, or " +
QUIT + " to quit ");
inputString = Console.ReadLine();
donation = Convert.ToDouble(inputString);
}
Console.WriteLine("Your total is {0}", total.ToString("C"));
}
}
code 2
using System;
namespace donate
{
class donate
{
public static void Main()
{
begin:
string group;
int myint;
Console.WriteLine("Please enter group number (4, 5, or 6)");
Console.WriteLine("(0 to quit): ");
group = Console.ReadLine();
myint = Int32.Parse(group);
switch (myint)
{
case 0:
Console.WriteLine("Bye.");
break;
case 4:
case 5:
case 6:
double donation;
string inputString;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString = Console.ReadLine();
donation = Convert.ToDouble(inputString);
goto begin;
default:
Console.WriteLine("Incorrect grade number.", myint);
goto begin;
}
}
}
}
So basically I want to find the total for each group using the 2nd code.
Any help would be greatly appreciated.
Don't use goto like that. Just use another while loop like you did in the first code segement.
It would be much more concise to say:
if (myInt > 3 && myInt < 7) { ... }
instead of using that switch statement.
Basically your code for summing up the donation amount does the trick, so just stick that inside a similar loop that handles what the group number is. If you do this you're going to want to use a different input to signify the end of donations vs the end of input altogether. It would be confusing if the application said "Enter 0 to quit input", followed by "Enter 0 to quit donation input".
You are very close with Code 2. If you put Code 2 inside while loop it works!
The only code I have written for you here is declared myint outside the while loop and initialised it to a non-zero value.
double total = 0;
int myint = -1;
while (myint != 0)
{
string group;
Console.WriteLine("Please enter group number (4, 5, or 6)");
Console.WriteLine("(0 to quit): ");
group = Console.ReadLine();
myint = Int32.Parse(group);
switch (myint)
{
case 0:
Console.WriteLine("Bye.");
break;
case 4:
case 5:
case 6:
double donation;
string inputString;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString = Console.ReadLine();
donation = Convert.ToDouble(inputString);
total += donation;
break;
default:
Console.WriteLine("Incorrect grade number.", myint);
break;
}
}
Console.WriteLine("Your total is {0}", total.ToString("C"));