Getting user inputs to be used in an array - c#

In this code I am attempting to write requires that I make a small menu, and for A to take 5 integers, and B to display them, C and D are // out because I don't have to code those sections yet, but for some reason I can't get the integers to input right, and for them to be displayed with B. My main question is how can I get 5 user inputs inside of loadarray and then use that array in displayarray?
static void Main(string[] args)
{
char choice;
int[] Num = new interger[5];
do
{
Console.Clear();
Choice = Menu();
switch (choice)
{
case 'A':
case 'a':
lArray(Num);
Console.ReadLine();
break;
case 'B':
case 'b':
dArray(Num);
Console.ReadLine();
break;
case 'C':
case 'c':
// Console.WriteLine("Sum: {0}", cSum(Num));
Console.ReadLine();
break;
case 'D':
case 'd':
// Console.WriteLine("Average: {0}", cAverage(Num));
Console.ReadLine();
break;
case 'Z':
case 'z':
break;
default:
Console.WriteLine("Invalid number!");
break;
}
}
while (choice != 'Z' && choice != 'z');
}
static char Menu()
{
char Input;
string[] strOptions = new string[] {
"A. Add num",
"B. Display num",
"C. Output sum ",
"D. Output average",
"z. Exit"
};
Console.WriteLine("What would you like to do?");
foreach(string strValue in strOptions)
{
Console.WriteLine(strValue);
}
do
{
Console.Write("Please select from A to Z: ");
Input = Console.ReadKey().KeyChar;
Console.WriteLine();
}
while ((Input < 'A' || Input > 'Z') && (Input < 'a' || Input > 'z'));
return Input;
}
static int lArray(int[] array)
{
int[] newArray = new int[5];
for (int i = 0; i < newArray.Length; i++)
{
newArray[i] = Convert.ToInt32(Console.ReadLine());
}
}
static int dArray(int[] array)
{
return loadArray;
}
}
}
}

Related

C# -value getiing reset to 0 after the loop

I have a coffee ordering program. The issue is that the total bill gets reset after this loop.
Note: I didn't add the entire code so it doesn't get too much, but if
you want to get the reference then please tell me.
invalidChoice = true;
while (invalidChoice)
{
Console.WriteLine(" ");
Console.WriteLine(" Can i bring you the bill: y or n (yes or no)");
Console.Write(" ");
string Anything = Console.ReadLine();
string UpperCaseAnything = Anything.ToUpper();
if (UpperCaseAnything == "Y" || UpperCaseAnything == "YES")
{
invalidChoice = false;
}
else if (UpperCaseAnything == "N" || UpperCaseAnything == "NO")
{
return;
}
else
{
Console.WriteLine("");
Console.WriteLine(" Please enter a valid choice");
}
}
What's happening is that if I enter "no," it will bring the menu up again, but I don't want to reset the added total value. But in this, the total amount that was getting added up until here gets reset if I enter "no." I don't know what's wrong—why the amount is getting reset here.
Here's the amount method.
private int askForCoffee()
{
int totalCoffeeCost = 0;
bool invalidChoice = true;
while (invalidChoice)
{
Console.WriteLine("");
Console.WriteLine(" Please enter your coffee size : 1 - small, 2 - medium, 3 - large");
Console.Write(" ");
int CoffeeChoice = int.Parse(Console.ReadLine());
switch (CoffeeChoice)
{
case 1:
totalCoffeeCost += 2;
invalidChoice = false;
break;
case 2:
totalCoffeeCost += 5;
invalidChoice = false;
break;
case 3:
totalCoffeeCost += 7;
invalidChoice = false;
break;
default:
Console.WriteLine("");
Console.WriteLine(" Please enter a valid choice");
break;
}
}
return totalCoffeeCost;
}
Update
Here is the whole code
using System;
/* A simple coffee ordering program
* used switch,if else and lable*/
class Program
{
public static void Main()
{
var exiting = false;
while (!exiting)
{
Program p = new Program();
p.programLoop();
}
}
private int askForCoffee()
{
int totalCoffeeCost = 0;
bool invalidChoice = true;
while (invalidChoice)
{
Console.WriteLine("");
Console.WriteLine(" Please enter your coffee size : 1 - small, 2 - medium, 3 - large");
Console.Write(" ");
int CoffeeChoice = int.Parse(Console.ReadLine());
switch (CoffeeChoice)
{
case 1:
totalCoffeeCost += 2;
invalidChoice = false;
break;
case 2:
totalCoffeeCost += 5;
invalidChoice = false;
break;
case 3:
totalCoffeeCost += 7;
invalidChoice = false;
break;
default:
Console.WriteLine("");
Console.WriteLine(" Please enter a valid choice");
break;
}
}
return totalCoffeeCost;
}
private void programLoop()
{
int TotalCoffeeCost = 0;
TotalCoffeeCost += askForCoffee();
var invalidChoice = true;
while (invalidChoice)
{
Console.WriteLine("");
Console.WriteLine(" Do you want have another coffee : Y or N (Yes or No) ?");
Console.Write(" ");
string UserChoice = Console.ReadLine();
string upperCaseChoice = UserChoice.ToUpper();
if (upperCaseChoice == "Y" || upperCaseChoice == "YES")
{
TotalCoffeeCost += askForCoffee(); //Note here that we did not set invalidChoice to false, meaning it will loop again
}
else if (upperCaseChoice == "N" || upperCaseChoice == "NO")
{
invalidChoice = false;
}
else
{
Console.WriteLine("");
Console.WriteLine(" Please enter a valid choice");
}
}
invalidChoice = true;
while (invalidChoice)
{
Console.WriteLine(" ");
Console.WriteLine(" Can i bring you the bill: y or n (yes or no)");
Console.Write(" ");
string Anything = Console.ReadLine();
string UpperCaseAnything = Anything.ToUpper();
if (UpperCaseAnything == "Y" || UpperCaseAnything == "YES")
{
invalidChoice = false;
}
else if (UpperCaseAnything == "N" || UpperCaseAnything == "NO")
{
return;
}
else
{
Console.WriteLine("");
Console.WriteLine(" Please enter a valid choice");
}
}
invalidChoice = true;
while (invalidChoice)
{
Console.WriteLine("");
Console.WriteLine(" Your total bill amount is = {0}$", TotalCoffeeCost);
Console.WriteLine("");
Console.WriteLine(" Please pay the amount by entering the amount bellow");
Console.Write(" ");
int EnterdAmt = int.Parse(Console.ReadLine());
if (EnterdAmt != TotalCoffeeCost)
{
Console.WriteLine("");
Console.WriteLine(" Please pay the correct amount");
}
else
{
invalidChoice = false;
}
}
Console.WriteLine("");
Console.WriteLine(" Thank for buying coffee, Hope you got a amazing experience");
}
}
Update askForCoffee() to pass through the existing total:
private int askForCoffee(int totalCoffeeCost)
{
bool invalidChoice = true;
while (invalidChoice)
//...
}
then call it like this:
TotalCoffeeCost = askForCoffee(TotalCoffeeCost);
You also need to do a similar thing with programLoop:
private int programLoop(int TotalCoffeeCost)
{
TotalCoffeeCost = askForCoffee(TotalCoffeeCost);
//...
}
Update - adding the whole code to help the OP:
using System;
/* A simple coffee ordering program
* used switch,if else and lable*/
class Program
{
public static void Main()
{
int totalCoffeeCost = 0;
var exiting = false;
while (!exiting)
{
Program p = new Program();
totalCoffeeCost = p.programLoop(totalCoffeeCost);
}
}
private int askForCoffee(int totalCoffeeCost)
{
bool invalidChoice = true;
while (invalidChoice)
{
Console.WriteLine("");
Console.WriteLine(" Please enter your coffee size : 1 - small, 2 - medium, 3 - large");
Console.Write(" ");
int CoffeeChoice = int.Parse(Console.ReadLine());
switch (CoffeeChoice)
{
case 1:
totalCoffeeCost += 2;
invalidChoice = false;
break;
case 2:
totalCoffeeCost += 5;
invalidChoice = false;
break;
case 3:
totalCoffeeCost += 7;
invalidChoice = false;
break;
default:
Console.WriteLine("");
Console.WriteLine(" Please enter a valid choice");
break;
}
}
return totalCoffeeCost;
}
private int programLoop(int TotalCoffeeCost)
{
TotalCoffeeCost = askForCoffee(TotalCoffeeCost);
var invalidChoice = true;
while (invalidChoice)
{
Console.WriteLine("");
Console.WriteLine(" Do you want have another coffee : Y or N (Yes or No) ?");
Console.Write(" ");
string UserChoice = Console.ReadLine();
string upperCaseChoice = UserChoice.ToUpper();
if (upperCaseChoice == "Y" || upperCaseChoice == "YES")
{
TotalCoffeeCost = askForCoffee(TotalCoffeeCost); //Note here that we did not set invalidChoice to false, meaning it will loop again
}
else if (upperCaseChoice == "N" || upperCaseChoice == "NO")
{
invalidChoice = false;
}
else
{
Console.WriteLine("");
Console.WriteLine(" Please enter a valid choice");
}
}
invalidChoice = true;
while (invalidChoice)
{
Console.WriteLine(" ");
Console.WriteLine(" Can i bring you the bill: y or n (yes or no)");
Console.Write(" ");
string Anything = Console.ReadLine();
string UpperCaseAnything = Anything.ToUpper();
if (UpperCaseAnything == "Y" || UpperCaseAnything == "YES")
{
invalidChoice = false;
}
else if (UpperCaseAnything == "N" || UpperCaseAnything == "NO")
{
return TotalCoffeeCost;
}
else
{
Console.WriteLine("");
Console.WriteLine(" Please enter a valid choice");
}
}
invalidChoice = true;
while (invalidChoice)
{
Console.WriteLine("");
Console.WriteLine(" Your total bill amount is = {0}$", TotalCoffeeCost);
Console.WriteLine("");
Console.WriteLine(" Please pay the amount by entering the amount bellow");
Console.Write(" ");
int EnterdAmt = int.Parse(Console.ReadLine());
if (EnterdAmt != TotalCoffeeCost)
{
Console.WriteLine("");
Console.WriteLine(" Please pay the correct amount");
}
else
{
invalidChoice = false;
}
}
Console.WriteLine("");
Console.WriteLine(" Thank for buying coffee, Hope you got a amazing experience");
return TotalCoffeeCost;
}
}
It's because you set the totalCoffeCost to 0 when entering another programLoop. What you can do, is making the totalCoffeCost to a class variable, so you don't need to set the totalCoffeCost inside the Loop methode.
This should work fine:
using System;
/* A simple coffee ordering program
* used switch,if else and lable*/
class Program
{
private int totalCoffeCost = 0;
public static void Main()
{
var exiting = false;
while (!exiting)
{
Program p = new Program();
p.programLoop();
}
}
private int askForCoffee()
{
int CoffeeCost = 0;
bool invalidChoice = true;
while (invalidChoice)
{
Console.WriteLine("");
Console.WriteLine(" Please enter your coffee size : 1 - small, 2 - medium, 3 - large");
Console.Write(" ");
int CoffeeChoice = int.Parse(Console.ReadLine());
switch (CoffeeChoice)
{
case 1:
CoffeeCost += 2;
invalidChoice = false;
break;
case 2:
CoffeeCost += 5;
invalidChoice = false;
break;
case 3:
CoffeeCost += 7;
invalidChoice = false;
break;
default:
Console.WriteLine("");
Console.WriteLine(" Please enter a valid choice");
break;
}
}
return CoffeeCost;
}
private void programLoop()
{
totalCoffeeCost += askForCoffee();
var invalidChoice = true;
while (invalidChoice)
{
Console.WriteLine("");
Console.WriteLine(" Do you want have another coffee : Y or N (Yes or No) ?");
Console.Write(" ");
string UserChoice = Console.ReadLine();
string upperCaseChoice = UserChoice.ToUpper();
if (upperCaseChoice == "Y" || upperCaseChoice == "YES")
{
totalCoffeeCost += askForCoffee(); //Note here that we did not set invalidChoice to false, meaning it will loop again
}
else if (upperCaseChoice == "N" || upperCaseChoice == "NO")
{
invalidChoice = false;
}
else
{
Console.WriteLine("");
Console.WriteLine(" Please enter a valid choice");
}
}
invalidChoice = true;
while (invalidChoice)
{
Console.WriteLine(" ");
Console.WriteLine(" Can i bring you the bill: y or n (yes or no)");
Console.Write(" ");
string Anything = Console.ReadLine();
string UpperCaseAnything = Anything.ToUpper();
if (UpperCaseAnything == "Y" || UpperCaseAnything == "YES")
{
invalidChoice = false;
}
else if (UpperCaseAnything == "N" || UpperCaseAnything == "NO")
{
return;
}
else
{
Console.WriteLine("");
Console.WriteLine(" Please enter a valid choice");
}
}
invalidChoice = true;
while (invalidChoice)
{
Console.WriteLine("");
Console.WriteLine(" Your total bill amount is = {0}$", totalCoffeeCost);
Console.WriteLine("");
Console.WriteLine(" Please pay the amount by entering the amount bellow");
Console.Write(" ");
int EnterdAmt = int.Parse(Console.ReadLine());
if (EnterdAmt != totalCoffeeCost)
{
Console.WriteLine("");
Console.WriteLine(" Please pay the correct amount");
}
else
{
invalidChoice = false;
}
}
Console.WriteLine("");
Console.WriteLine(" Thank for buying coffee, Hope you got a amazing experience");
totalCoffeCost = 0;
}
}
Well, every method should do its work (say, provide an interface for a cup of coffee) and
doesn't interfere in other activity (computing total etc. ``)
First of all, let's extract model (don not hardcode it within UI routines):
static readonly IReadOnlyDictionary<int, (string name, int size)> s_Options =
new Dictionary<int, (string name, int price)>() {
{1, ("small", 2)},
{2, ("medium", 5)},
{3, ("large", 7)},
};
Then asking for a single cup can be written like this:
private static int askForCoffee() {
// Keep asking until correct value is provided
while (true) {
var optionsToSell = s_Options
.OrderBy(pair => pair.Key)
.Select(pair => $"{pair.Key} - {pair.Value.name}");
Console.WriteLine();
Console.WriteLine("Please enter your coffee size : {string.Join(" - ", optionsToSell)}}");
Console.Write();
// If entered value is a valid integer and we have such an option in s_Options
// just return it
if (int.TryParse(Console.ReadLine(), out int choice) &&
s_Options.TryGetValue(choice, out var option))
return option.price;
Console.WriteLine("");
Console.WriteLine(" Please enter a valid choice");
}
}
To ask for several cups, we can use a simple loop:
private static int askForManyCoffee() {
int total = askForCoffee();
while (true) {
Console.WriteLine("");
Console.WriteLine(" Do you want have another coffee : Y or N (Yes or No) ?");
Console.Write(" ");
var input = Console.ReadLine().Trim().ToUpper();
if (input == "Y" || input == "YES")
totsl += askForCoffee();
else if (input == "N" || input == "NO")
return total;
else {
Console.WriteLine("");
Console.WriteLine(" Please enter a valid choice");
}
}
}
Then in program loop you can operate with TotalCoffeeCost:
private void programLoop() {
int TotalCoffeeCost = askForManyCoffee();
...
}
please, note, that being static askForCoffee() and askForManyCoffee() can't ruin anything like TotalCoffeeCost
try this, move the variable to a property and rename the TotalCoffeeCost instances to totalCoffeeCost. That should get you the desired result.
using System;
class Program
{
private int totalCoffeeCost = 0;
public static void Main()
{
var exiting = false;
while (!exiting)
{
Program p = new Program();
p.programLoop();
}
}
private int askForCoffee()
{
bool invalidChoice = true;
while (invalidChoice)
{
Console.WriteLine("");
Console.WriteLine(" Please enter your coffee size : 1 - small, 2 - medium, 3 - large");
Console.Write(" ");
int CoffeeChoice = int.Parse(Console.ReadLine());
switch (CoffeeChoice)
{
case 1:
totalCoffeeCost += 2;
invalidChoice = false;
break;
case 2:
totalCoffeeCost += 5;
invalidChoice = false;
break;
case 3:
totalCoffeeCost += 7;
invalidChoice = false;
break;
default:
Console.WriteLine("");
Console.WriteLine(" Please enter a valid choice");
break;
}
}
return totalCoffeeCost;
}
private void programLoop()
{
totalCoffeeCost += askForCoffee();
var invalidChoice = true;
while (invalidChoice)
{
Console.WriteLine("");
Console.WriteLine(" Do you want have another coffee : Y or N (Yes or No) ?");
Console.Write(" ");
string UserChoice = Console.ReadLine();
string upperCaseChoice = UserChoice.ToUpper();
if (upperCaseChoice == "Y" || upperCaseChoice == "YES")
{
totalCoffeeCost += askForCoffee(); //Note here that we did not set invalidChoice to false, meaning it will loop again
}
else if (upperCaseChoice == "N" || upperCaseChoice == "NO")
{
invalidChoice = false;
}
else
{
Console.WriteLine("");
Console.WriteLine(" Please enter a valid choice");
}
}
invalidChoice = true;
while (invalidChoice)
{
Console.WriteLine(" ");
Console.WriteLine(" Can i bring you the bill: y or n (yes or no)");
Console.Write(" ");
string Anything = Console.ReadLine();
string UpperCaseAnything = Anything.ToUpper();
if (UpperCaseAnything == "Y" || UpperCaseAnything == "YES")
{
invalidChoice = false;
}
else if (UpperCaseAnything == "N" || UpperCaseAnything == "NO")
{
return;
}
else
{
Console.WriteLine("");
Console.WriteLine(" Please enter a valid choice");
}
}
invalidChoice = true;
while (invalidChoice)
{
Console.WriteLine("");
Console.WriteLine(" Your total bill amount is = {0}$", totalCoffeeCost);
Console.WriteLine("");
Console.WriteLine(" Please pay the amount by entering the amount bellow");
Console.Write(" ");
int EnterdAmt = int.Parse(Console.ReadLine());
if (EnterdAmt != totalCoffeeCost)
{
Console.WriteLine("");
Console.WriteLine(" Please pay the correct amount");
}
else
{
invalidChoice = false;
}
}
Console.WriteLine("");
Console.WriteLine(" Thank for buying coffee, Hope you got a amazing experience");
}
}

C# code not building/running even though i have no errors

so as the title says my C# code is not running/debugging even though i have 0 errors being shown.
I begin the debugging and all that happens is the console screen flashes quickly then exits with 0 errors. Even the .exe in the bin\debug folder does the exact same. All i'm receiving is a wall of text in the output section.
Algorithms.vshost.exe' (CLR v4.0.30319: Algorithms.vshost.exe): Loaded C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\Accessibility\v4.0_4.0.0.0__b03f5f7f11d50a3a\Accessibility.dll. Symbols loaded.
The thread 0x12b8 has exited with code 0 (0x0).
The thread 0x289c has exited with code 0 (0x0).
The program [15012] Algorithms.vshost.exe has exited with code 0 (0x0).
I hope this is understandable enough! I would appreciate any help, thanks!
Code as requested by some! I hope it's helpful! I appreciate all the answers and help so far!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AlgorithmsResit
{
class Program
{
private static void Main(string[] args)
{ }
public static void AlgorithmSortInt(int[] array)
{
int j = array.Length - 1;
int x, i, temp;
for (x = 1; x <= j; ++x)
{
temp = array[x];
for (i = x - 1; i >= 0; --i)
{
if (temp < array[i]) array[i + 1] = array[i];
else break;
}
array[1 + 1] = temp;
}
}
public static void AlgorithmSortDouble(double[] array)
{
int j = array.Length - 1;
int x, i;
double temp;
for (x = 1; x <= j; ++x)
{
temp = array[x];
for (i = x - 1; i >= 0; --i)
{
if (temp < array[i]) array[i + 1] = array[i];
else break;
}
array[i + 1] = temp;
}
}
public static void AlgorithmDateTime(DateTime[] array)
{
int j = array.Length - 1;
int x, i;
DateTime temp;
for (x = 1; x <= j; ++x)
{
temp = array[x];
for (i = x - 1; i >= 0; --i)
{
if (temp < array[i]) array[i + 1] = array[i];
else break;
}
array[i + 1] = temp;
}
}
public static void StringToSort(string[] array)
{
int x = array.Length - 1;
for (int j = 0; j < x; j++)
{
for (int i = x; i > j; i--)
{
if (((IComparable)array[i - 1]).CompareTo(array[i]) > 0)
{
var temp = array[i - 1];
array[i - 1] = array[i];
array[i] = temp;
}
}
}
}
static void main(string[] args)
{
string[] Day1 = System.IO.File.ReadAllLines(#"TextFiles/Day_1.txt");
List<int> Day1List = new List<int>();
foreach (string Day in Day1)
{
int Days = Convert.ToInt32(Day);
Day1List.Add(Days);
}
int[] Day1Arr = Day1List.ToArray();
string[] Depth1 = System.IO.File.ReadAllLines(#"TextFiles/Depth_1.txt");
List<double> Depth1List = new List<double>();
foreach (string Depth in Depth1)
{
double Depths = Convert.ToDouble(Depth);
Depth1List.Add(Depths);
}
double[] Depth1Arr = Depth1List.ToArray();
string[] IRISID1 = System.IO.File.ReadAllLines(#"TextFiles/IRIS_ID_1.txt");
List<int> Iris1List = new List<int>();
foreach (string IRIS in IRISID1)
{
int Iris = Convert.ToInt32(IRIS);
Iris1List.Add(Iris);
}
int[] Iris1Arr = Iris1List.ToArray();
string[] Latitude1 = System.IO.File.ReadAllLines(#"TextFiles/Latitude_1.txt");
List<double> Latitude1List = new List<double>();
foreach (string Lat in Latitude1)
{
double Latitude = Convert.ToDouble(Latitude1);
Latitude1List.Add(Latitude);
}
double[] Latitude1Arr = Latitude1List.ToArray();
string[] Longitude1 = System.IO.File.ReadAllLines(#"TextFiles/Longitude_1.txt");
List<double> Longitude1List = new List<double>();
foreach (string Longitude in Longitude1)
{
double Longitudes = Convert.ToDouble(Longitude1);
Longitude1List.Add(Longitudes);
}
double[] Longitude1Arr = Longitude1List.ToArray();
string[] Magnitude1 = System.IO.File.ReadAllLines(#"TextFiles/Magnitude_1.txt");
List<Double> Magnitude1List = new List<Double>();
foreach (string Magnitude in Magnitude1)
{
double Magnitudes = Convert.ToDouble(Magnitude1);
Magnitude1List.Add(Magnitudes);
}
double[] Magnitude1Arr = Magnitude1List.ToArray();
string[] Month1 = System.IO.File.ReadAllLines(#"TextFiles/Month_1.txt");
string[] Region1 = System.IO.File.ReadAllLines(#"TextFiles/Region_1.txt");
string[] Time1 = System.IO.File.ReadAllLines(#"TextFiles/Time_1.txt");
List<DateTime> Time1List = new List<DateTime>();
foreach (string Time in Time1)
{
DateTime Times = Convert.ToDateTime(Time);
Time1List.Add(Times);
}
DateTime[] Time1Arr = Time1List.ToArray();
string[] Timestamp1 = System.IO.File.ReadAllLines(#"TextFiles/Timestamp_1.txt");
List<int> Timestamp1List = new List<int>();
foreach (string Timestamp in Timestamp1)
{
int Timestamps = Convert.ToInt32(Timestamp);
Timestamp1List.Add(Timestamps);
}
int[] Timestamp1Arr = Timestamp1List.ToArray();
string[] Year1 = System.IO.File.ReadAllLines(#"TextFiles/Year_1.txt");
List<int> Year1List = new List<int>();
foreach (String Date in Year1)
{
int Dates = Convert.ToInt32(Date);
Year1List.Add(Dates);
}
int[] Year1Arr = Year1List.ToArray();
string UserArrayChoice, AscOrDescChoice;
int ArrayChoice;
int count = 0;
do
{
count++;
Console.Write("{0} ", Day1Arr[count]);
Console.Write("{0} ", Depth1[count]);
Console.Write("{0} ", IRISID1[count]);
Console.Write("{0} ", Latitude1Arr[count]);
Console.Write("{0} ", Longitude1Arr[count]);
Console.Write("{0} ", Magnitude1Arr[count]);
Console.Write("{0} ", Month1[count]);
Console.Write("{0} ", Region1[count]);
Console.Write("{0} ", Time1Arr[count]);
Console.Write("{0} ", Timestamp1Arr[count]);
Console.Write("{0}", Year1Arr[count]);
Console.Write("\n");
} while (count < Year1Arr.Length - 1);
Console.WriteLine("Enter the number of the file you would like to sort... \n1 ) Day_1.txt\n2 ) Depth_1.txt\n3 ) IRIS_ID_.txt\n4 ) Latitude_1.txt\n5 ) Longitude_1.txt\n6 ) Magnitude_1.txt\n7 ) Month_1.txt\n8 ) Region_1.txt\n9 ) Time_1.txt\n10 ) Timestamp_1.txt\n11 ) Year_1.txt\n12");
UserArrayChoice = Console.ReadLine();
ArrayChoice = Convert.ToInt32(UserArrayChoice);
switch (UserArrayChoice)
{
case "1":
UserArrayChoice = "Day_1.txt";
break;
case "2":
UserArrayChoice = "Depth_1.txt";
break;
case "3":
UserArrayChoice = "IRIS_ID_1.txt";
break;
case "4":
UserArrayChoice = "Latitude_1.txt";
break;
case "5":
UserArrayChoice = "Longitude_1.txt";
break;
case "6":
UserArrayChoice = "Magnitude_1.txt";
break;
case "7":
UserArrayChoice = "Month_1.txt";
break;
case "8":
UserArrayChoice = "Region_1.txt";
break;
case "9":
UserArrayChoice = "Time_1.txt";
break;
case "10":
UserArrayChoice = "Timestamp_1.txt";
break;
case "11":
UserArrayChoice = "Year_1.txt";
break;
default:
break;
}
Console.WriteLine("---------------------------------------------------------------------------");
Console.WriteLine("{0} Has been selected, would you like to sort by Ascending or Descending? ", UserArrayChoice);
Console.WriteLine("---------------------------------------------------------------------------");
AscOrDescChoice = Console.ReadLine();
if (AscOrDescChoice == "Ascending" | AscOrDescChoice == "ascending")
{
Console.WriteLine("---------------------------------");
Console.WriteLine("{0} Will sort in Ascending order!", UserArrayChoice);
Console.WriteLine("---------------------------------");
switch (ArrayChoice)
{
case 1:
AlgorithmSortInt(Day1Arr);
foreach (int temp in Day1Arr)
{
Console.WriteLine("{0} ", temp);
}
break;
case 2:
AlgorithmSortDouble(Depth1Arr);
foreach (double temp in Depth1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 3:
AlgorithmSortInt(Iris1Arr);
foreach (int temp in Iris1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 4:
AlgorithmSortDouble(Latitude1Arr);
foreach (double temp in Latitude1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 5:
AlgorithmSortDouble(Longitude1Arr);
foreach (double temp in Longitude1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 6:
AlgorithmSortDouble(Magnitude1Arr);
foreach (double temp in Magnitude1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 7:
StringToSort(Month1);
foreach (string temp in Month1)
{
Console.WriteLine("{0}", temp);
}
break;
case 8:
StringToSort(Region1);
foreach (string temp in Region1)
{
Console.WriteLine("{0}", temp);
}
break;
case 9:
AlgorithmDateTime(Time1Arr);
foreach (DateTime temp in Time1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 10:
AlgorithmSortInt(Timestamp1Arr);
foreach (int temp in Timestamp1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 11:
AlgorithmSortInt(Year1Arr);
foreach (int temp in Year1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
}
}
else if (AscOrDescChoice == "Descending" | AscOrDescChoice == "descending")
{
Console.WriteLine("----------------------------------");
Console.WriteLine("{0} Will sort in Descending order!", UserArrayChoice);
Console.WriteLine("----------------------------------");
switch (ArrayChoice)
{
case 1:
AlgorithmSortInt(Day1Arr);
Array.Reverse(Day1Arr);
foreach (int temp in Day1Arr)
{
Console.WriteLine("{0} ", temp);
}
break;
case 2:
AlgorithmSortDouble(Depth1Arr);
Array.Reverse(Depth1Arr);
foreach (double temp in Depth1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 3:
AlgorithmSortInt(Iris1Arr);
Array.Reverse(Iris1Arr);
foreach (int temp in Iris1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 4:
AlgorithmSortDouble(Latitude1Arr);
Array.Reverse(Latitude1Arr);
foreach (double temp in Latitude1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 5:
AlgorithmSortDouble(Longitude1Arr);
Array.Reverse(Longitude1Arr);
foreach (double temp in Longitude1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 6:
AlgorithmSortDouble(Magnitude1Arr);
Array.Reverse(Magnitude1Arr);
foreach (double temp in Magnitude1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 7:
StringToSort(Month1);
Array.Reverse(Month1);
foreach (string temp in Month1)
{
Console.WriteLine("{0}", temp);
}
break;
case 8:
StringToSort(Region1);
Array.Reverse(Region1);
foreach (string temp in Region1)
{
Console.WriteLine("{0}", temp);
}
break;
case 9:
AlgorithmDateTime(Time1Arr);
Array.Reverse(Time1Arr);
foreach (DateTime temp in Time1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 10:
AlgorithmSortInt(Timestamp1Arr);
Array.Reverse(Timestamp1Arr);
foreach (int temp in Timestamp1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 11:
AlgorithmSortInt(Year1Arr);
Array.Reverse(Year1Arr);
foreach (int temp in Year1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
}
}
else
{
Console.WriteLine("-------------------");
Console.WriteLine("Incorrect Response!");
Console.WriteLine("-------------------");
}
Console.WriteLine("Enter the number of the file you would like to search... \n1 ) Day_1.txt\n2 ) Depth_1.txt\n3 ) IRIS_ID_1\n4 ) Latitude_1\n5 ) Longitude_1\n6 ) Magnitude_1\n7 ) Month_1\n8 ) Region_1\n9 ) Time_1\n10 ) Timestamp_1\n11 ) Year_1\n12");
UserArrayChoice = Console.ReadLine();
ArrayChoice = Convert.ToInt32(UserArrayChoice);
switch (UserArrayChoice)
{
case "1":
UserArrayChoice = "Day_1.txt";
break;
case "2":
UserArrayChoice = "Depth_1.txt";
break;
case "3":
UserArrayChoice = "IRIS_ID_1.txt";
break;
case "4":
UserArrayChoice = "Latitude_1.txt";
break;
case "5":
UserArrayChoice = "Longitude_1.txt";
break;
case "6":
UserArrayChoice = "Magnitude_1.txt";
break;
case "7":
UserArrayChoice = "Month_1.txt";
break;
case "8":
UserArrayChoice = "Region_1.txt";
break;
case "9":
UserArrayChoice = "Time_1.txt";
break;
case "10":
UserArrayChoice = "Timestamp_1.txt";
break;
case "11":
UserArrayChoice = "Year_1.txt";
break;
default:
break;
}
Console.WriteLine("--------------------------------------------------------------------");
Console.WriteLine("{0} has been selected! Please enter what you would like to search - ", UserArrayChoice);
Console.WriteLine("--------------------------------------------------------------------");
string SearchTemp = Console.ReadLine();
bool Found = false;
int counter = 0;
switch (ArrayChoice)
{
case 1:
int SearchDay = Convert.ToInt32(SearchTemp);
for (int x = 0; x < Day1Arr.Length; x++)
{
if (SearchDay == Day1Arr[x])
{
Found = true;
}
}
if (Found == true) { Console.WriteLine("Successful! :-)"); }
else { Console.WriteLine("Unsuccessful! Sorry :-("); }
break;
case 2:
double DepthSearch = Convert.ToDouble(SearchTemp);
for (int x = 0; x < Depth1Arr.Length; x++)
{
if (DepthSearch == Depth1Arr[x])
{
Found = true;
}
}
if (Found == true) { Console.WriteLine("Successful!:-)"); }
else { Console.WriteLine("Unsuccessful! Sorry :-("); }
break;
case 3:
int SearchIris = Convert.ToInt32(SearchTemp);
for (int x = 0; x < Iris1Arr.Length; x++)
{
if (SearchIris == Iris1Arr[x])
{
Found = true;
}
}
if (Found == true) { Console.WriteLine("Successful! :-)"); }
else { Console.WriteLine("Unsuccessful! Sorry :-("); }
break;
case 4:
double SearchLatitude = Convert.ToDouble(SearchTemp);
for (int x = 0; x < Latitude1Arr.Length; x++)
{
if (SearchLatitude == Latitude1Arr[x])
{
Found = true;
}
}
if (Found == true) { Console.WriteLine("Successful! :-)"); }
else { Console.WriteLine("Unsuccessful! Sorry :-("); }
break;
case 5:
double SearchLong = Convert.ToDouble(SearchTemp);
for (int x = 0; x < Longitude1Arr.Length; x++)
{
if (SearchLong == Longitude1Arr[x])
{
Found = true;
}
}
if (Found == true) { Console.WriteLine("Successful! :-)"); }
else { Console.WriteLine("Unsuccessful! Sorry :-("); }
break;
case 6:
double SearchMag = Convert.ToDouble(SearchTemp);
for (int x = 0; x < Magnitude1Arr.Length; x++)
{
if (SearchMag == Magnitude1Arr[x])
{
Found = true;
}
}
if (Found == true) { Console.WriteLine("Successful! :-)"); }
else { Console.WriteLine("Unsuccessful! Sorry :-("); }
break;
case 7:
foreach (var Months in Month1)
{
if (Months.Contains(SearchTemp))
{
count++;
Found = true;
Console.Write("{0} ", Day1Arr[counter]);
Console.Write("{0} ", Depth1Arr[counter]);
Console.Write("{0} ", Iris1Arr[counter]);
Console.Write("{0} ", Latitude1Arr[counter]);
Console.Write("{0} ", Longitude1Arr[counter]);
Console.Write("{0} ", Magnitude1Arr[counter]);
Console.Write("{0} ", Month1[counter]);
Console.Write("{0} ", Region1[counter]);
Console.Write("{0} ", Time1Arr[counter]);
Console.Write("{0} ", Timestamp1Arr[counter]);
Console.Write("{0} ", Year1Arr[counter]);
Console.Write("\n");
}
}
if (Found == true) { Console.WriteLine("Successful! :-)"); }
else { Console.WriteLine("Unsuccessful! Sorry :-("); }
break;
case 8:
foreach (var Regions in Region1)
{
if (Regions.Contains(SearchTemp))
{
Found = true;
}
}
if (Found == true) { Console.WriteLine("Successful! :-)"); }
else { Console.WriteLine("Unsuccessful! Sorry :-("); }
break;
case 9:
DateTime SearchDate = Convert.ToDateTime(SearchTemp);
for (int x = 0; x < Time1Arr.Length; x++)
{
if (SearchDate == Time1Arr[x])
{
Found = true;
}
}
if (Found == true) { Console.WriteLine("Successful! :-)"); }
else { Console.WriteLine("Unsuccessful! Sorry :-("); }
break;
case 10:
int SearchTimestamp = Convert.ToInt32(SearchTemp);
for (int x = 0; x < Timestamp1Arr.Length; x++)
{
if (SearchTimestamp == Timestamp1Arr[x])
{
Found = true;
}
}
if (Found == true) { Console.WriteLine("Successful! :-)"); }
else { Console.WriteLine("Unsuccessful! Sorry :-("); }
break;
case 11:
int SearchYear = Convert.ToInt32(SearchTemp);
for (int x = 0; x < Year1Arr.Length; x++)
{
{
Found = true;
}
}
if (Found == true) { Console.WriteLine("Successful! :-)"); }
else { Console.WriteLine("Unsuccessful! Sorry :-("); }
break;
}
}
}
}
What I know that it is just debugging message. You can switch that off by right clicking into the output window and uncheck the thread ended message.
http://msdn.microsoft.com/en-us/library/bs4c1wda.aspx
(1)Please add a breakpoint in your app, and then debug it again.
Like this thread:
Keeping console window open when debugging.
(2)If you run it with “start without debugging”, it would not be closed. You could also add Console.ReadLine()in your app like this thread.
(3)If you just debug your app and get this messages, please also enable the Exceptions settings under Debugger->Windows menu, and make sure that no Exception.

Convert Months To Number Equivalent To Be Used In Quicksort

I have some months read into an array from an external text file and I need to convert the months to an array that holds the value equivalent of the months e.g. January = 1, February = 2 etc. So that they can then be put through Quicksort.
public static void Main(string[] args)
{
//Read external files into arrays.
string[] Month = File.ReadLines(#"Month.txt").ToArray();
string[] Year = File.ReadLines(#"Year.txt").ToArray();
//Convert arrays from string to double to be used in sort.
double[] YearSort = Array.ConvertAll(Year, double.Parse);
int UserInput1;
//Create new array that will hold selected array to be used in sort.
double[] data = new double[1022];
//Prompt user to select action.
Console.WriteLine("Press 1 to Sort by month or 2 to sort by year.");
UserInput1 = Convert.ToInt32(Console.ReadLine());
if(UserInput1 == 1)
{
Array.Copy(Month,data,1022);
QuickSort(data);
for (int i = 0; i < 1022; i++)
Console.WriteLine(data[i]);
Console.WriteLine();
}
else if (UserInput1 == 2)
{
Array.Copy(YearSort,data,1022);
QuickSort(data);
for (int i = 0; i < 1022; i++)
Console.WriteLine(data[i]);
Console.WriteLine();
}
else
{
Console.WriteLine("Please try again and select a valid option");
}
}
static int MonthToDouble( string Month )
{
int NewMonth = 0;
switch(Month)
{
case "January":
case "january":
NewMonth = 1;
break;
case "February":
case "february":
NewMonth = 2;
break;
case "March":
case "march":
NewMonth = 3;
break;
case "April":
case "april":
NewMonth = 4;
break;
case "May":
case "may":
NewMonth = 5;
break;
case "June":
case "june":
NewMonth = 6;
break;
case "July":
case "july":
NewMonth = 7;
break;
case "August":
case "august":
NewMonth = 8;
break;
case "September":
case "september":
NewMonth = 9;
break;
case "October":
case "october":
NewMonth = 10;
break;
case "November":
case "november":
NewMonth = 11;
break;
case "December":
case "december":
NewMonth = 12;
break;
}
return NewMonth;
}
static string DoubleToMonth(double Month)
{
string NewMonth = "";
switch ((int)Month)
{
case 1:
NewMonth = "January";
break;
case 2:
NewMonth = "February";
break;
case 3:
NewMonth = "March";
break;
case 4:
NewMonth = "April";
break;
case 5:
NewMonth = "May";
break;
case 6:
NewMonth = "June";
break;
case 7:
NewMonth = "July";
break;
case 8:
NewMonth = "August";
break;
case 9:
NewMonth = "September";
break;
case 10:
NewMonth = "October";
break;
case 11:
NewMonth = "November";
break;
case 12:
NewMonth = "December";
break;
}
return NewMonth;
}
//QuickSort for double data values are in ascending order.
public static void QuickSort(double[] data)
{
Quick_Sort(data, 0, data.Length - 1);
}
public static void Quick_Sort(double[] data, int left, int right)
{
int i, j;
double pivot, temp;
i = left;
j = right;
pivot = data[(left + right) / 2];
do
{
while ((data[i] < pivot) && (i < right)) i++;
while ((pivot < data[j]) && (j > left)) j--;
if (i <= j)
{
temp = data[i];
data[i] = data[j];
data[j] = temp;
i++;
j--;
}
} while (i <= j);
if (left < j) Quick_Sort(data, left, j);
if (i < right) Quick_Sort(data, i, right);
}
}
A DateTime object's Month property gives you the integer value of the month starting at 1 like you need. So you can use DateTime.ParseExact() to parse the string into a full DateTime object then grab the Month property:
int monthNumber = DateTime.ParseExact("January", "MMMM", CultureInfo.CurrentCulture).Month;
You just need to replace "January" with your month strings, and leave "MMMM"which is the Custom Format String for "The full name of the month".
All the above code does is simplify your MonthToDouble() method, which you are not even using for some reason (also it should return a double, not an int). Contrary to your title, you already have a method to "Convert months to number equivalent", you just aren't using it.
So, I assume the only thing you are missing is to replace this:
Array.Copy(Month,data,1022);
QuickSort(data);
With this:
double[] monthsAsDoubles = new double[Month.Length];
for (int i = 0; i < monthsAsDoubles.Length; i++)
{
monthsAsDoubles[i] = MonthToDouble(Month[i]);
}
QuickSort(monthsAsDoubles);
Also change the return value of MonthToDouble() from int to double (cast if you need to).
Edit: On second thought, Quantic's answer is simpler. I'll just leave this here as an alternative.
Your code can be simplified a lot by using the DateTimeFormatInfo.MonthNames property, along with a case-insensitive string comparison. This also has the advantage of being much easier to port to use different languages for the month names.
Here is a snippet:
using System;
using System.Globalization;
using System.Linq;
using System.Collections.Generic;
public class Test
{
public static void Main()
{
var InputMonths = new List<string> { "January","march","sepTEmber","smarch" };
var MonthNames = new DateTimeFormatInfo().MonthNames.ToList();
var InputMonthNumbers = new List<int>();
foreach (var m in InputMonths)
{
//Find index of the month name, ignoring case
//Note if the input month name is invalid, FindIndex will return 0
int month_num = 1 + MonthNames.FindIndex(name => name.Equals(m, StringComparison.OrdinalIgnoreCase));
if (month_num > 0)
{
InputMonthNumbers.Add(month_num);
}
}
foreach (var n in InputMonthNumbers)
{
Console.WriteLine(n.ToString());
}
}
}
output:
1
3
9

Trying to write out a program

Ok for my program I am trying to get it so that when I have a Key press on my program and say I Press L and it moves in the 4x4 2d array and I get to pit which I designated as P on the array I want it to know it hit the P and print out you have a hit a Pit or if I reach where it has G on the array I want it to print out you have found gold. Any help is appreciated.
using System;
namespace DragonCave
{
public struct DragonPlayer
{
public int X, Y;
public string CurrentMove;
}
public class DragonGameboard
{
public string[,] GameboardArray;
public DragonPlayer Player;
private Random r;
public DragonGameboard(){
GameboardArray = new string[4,4];
Player.CurrentMove = "";
r = new Random();
Player.X = r.Next(0, 4);
Player.Y = r.Next(0, 4);
GenerateRandomBoard();
}
private void GenerateRandomBoard()
{
//Put a dot in every spot
int row;
int col;
for (row = 0; row < 4; row++)
{
for (col = 0; col < 4; col++)
{
Console.Write(GameboardArray[row, col] = ".");
}
//Console.WriteLine();
}
//Randomly Places the entrance, dragon, pit and gold.
GameboardArray[r.Next(0,4), r.Next(0, 4)] = "E";
GameboardArray[r.Next(0,4), r.Next(0,4)] = "D";
GameboardArray[r.Next(0, 4), r.Next(0, 4)] = "P";
GameboardArray[r.Next(0, 4), r.Next(0, 4)] = "P";
GameboardArray[r.Next(0, 4), r.Next(0, 4)] = "P";
GameboardArray[r.Next(0, 4), r.Next(0, 4)] = "G";
}
public void PrintBoard()
{
int row;
int col;
for (row = 0; row < 4; row++)
{
for (col = 0; col < 4; col++)
{
Console.Write(GameboardArray[row, col] + "\t");
}
Console.WriteLine();
}
Console.WriteLine("Cheat you are in" + Player.X + "," + Player.Y);
//fill with room numbers
}
public void ProcessMove(string move)
{
switch (move)
{
case "F":
Console.WriteLine("You chose forward");
break;
case "L":
Player.X--;
Player.Y--;
//Console.WriteLine("You chose Left");
Console.WriteLine("A Breeze is in the air");
break;
case "R":
Player.X++;
Player.Y++;
if (GameboardArray)
Console.WriteLine("You chose Right");
break;
case "G":
Console.WriteLine("You chose Grab gold");
break;
case "S":
Console.WriteLine("You chose Shoot arrow");
break;
case "C":
Console.WriteLine("You chose Climb");
break;
case "Q":
Console.WriteLine("You chose Quit");
break;
case "X":
Console.WriteLine("You chose Cheat");
PrintBoard();
break;
default:
Console.WriteLine("Invalid move!!!!!!!!!!1");
break;
}
}
}
Just check what the string is at GameboardArray[player.x, player.y].
public void ProcessTileEvent()
{
if( Player.X >= 0 && Player.X < 4 && Player.Y >= 0 && Player.Y < 4 )
{
switch( GameboardArray[Player.X, Player.Y] )
{
case "G":
Console.WriteLine( "You found gold!" );
break;
case "P":
Console.WriteLine( "You fell in a pit!" );
break;
}
}
}
You'd probably want to do this every time the player moves.

Keeping track of what the user inputs

This is my hangman code, and its almost good up to the point where it displays the guessed letters. It only displays the most recent guessed letter but I want it to continue on from whats left off. Such as if a person guess "A" and then "L" then Guessed letters are A, L.
I tried using a for loop after "Guessed letters are" but then it gives me the output
"A, A, A, A, A". What should I do to fix this problem?
class Hangman
{
public string[] words = new string[5] { "ARRAY", "OBJECT", "CLASS", "LOOP", "HUMBER" };
public string[] torture = new string[6] { "left arm", "right arm", "left leg", "right leg", "body", "head" };
public char[] guessed = new char[26];
int i;
public void randomizedWord()
{
Random random = new Random();
int index = random.Next(0, 5);
char[] hidden = new char[words[index].Length];
string word = words[index];
Console.WriteLine(words[index]);
Console.Write("The word is: ");
for (i = 0; i < hidden.Length; i++)
{
Console.Write('-');
hidden[i] = '-';
}
Console.WriteLine();
int lives = 6;
do
{
Console.WriteLine("Guess a letter: ");
char userinput = Console.ReadLine().ToCharArray()[0];
index++;
guessed[index] = userinput;
Console.WriteLine("Guessed letters are: " + guessed[index]);
bool foundLetter = false;
for (int i = 0; i < hidden.Length; i++)
{
if (word[i] == userinput)
{
hidden[i] = userinput;
foundLetter = true;
Console.WriteLine("You guessed right!");
}
}
for (int x = 0; x < hidden.Length; x++)
{
Console.Write(hidden[x]);
}
if (!foundLetter)
{
Console.WriteLine(" That is not a correct letter");
lives--;
if (lives == 5)
{
Console.WriteLine("You lost a " + torture[0]);
}
else if (lives == 4)
{
Console.WriteLine("You lost the " + torture[1]);
}
else if (lives == 3)
{
Console.WriteLine("You lost your " + torture[2]);
}
else if (lives == 2)
{
Console.WriteLine("You lost the " + torture[3]);
}
else if (lives == 1)
{
Console.WriteLine("You lost your " + torture[4]);
}
else
{
Console.WriteLine("You lost your " + torture[5]);
Console.WriteLine("You lose!");
break;
}
}
bool founddash = false;
for (int y = 0; y < hidden.Length; y++)
{
if (hidden[y] == '-')
{
founddash = true;
}
}
if (!founddash)
{
Console.WriteLine(" You Win! ");
break;
}
Console.WriteLine();
} while (lives != 0);
}
I was going to post on your other thread Hangman Array C#
Try changing this line
Console.WriteLine("Guessed letters are: " + guessed[index]);
To
Console.WriteLine("Guessed letters are: " + string.Join(" ", guessed).Trim());
I had a play with your hangman game and came up with this solution (while we are doing your homework). Although not related to the question.
public class HangCSharp
{
string[] words = new string[5] { "ARRAY", "OBJECT", "CLASS", "LOOP", "HUMBER" };
List<char> guesses;
Random random = new Random();
string word = "";
string current = "";
int loss = 0;
readonly int maxGuess = 6;
int highScrore = 0;
public void Run()
{
word = words[random.Next(0, words.Length)];
current = new string('-', word.Length);
loss = 0;
guesses = new List<char>();
while (loss < maxGuess)
{
Console.Clear();
writeHeader();
writeLoss();
writeCurrent();
var guess = Console.ReadKey().KeyChar.ToString().ToUpper()[0];
while (!char.IsLetterOrDigit(guess))
{
Console.WriteLine("\nInvalid Guess.. Please enter a valid alpha numeric character.");
Console.Write(":");
guess = Console.ReadKey().KeyChar;
}
while (guesses.Contains(guess))
{
Console.WriteLine("\nYou have already guessed {0}. Please try again.", guess);
Console.Write(":");
guess = Console.ReadKey().KeyChar;
}
guesses.Add(guess);
if (!isGuessCorrect(guess))
loss++;
else if (word == current)
break;
}
Console.Clear();
writeHeader();
writeLoss();
if (loss >= maxGuess)
writeYouLoose();
else
doYouWin();
Console.Write("Play again [Y\\N]?");
while (true)
{
var cmd = (Console.ReadLine() ?? "").ToUpper()[0];
if (cmd != 'Y' && cmd != 'N')
{
Console.WriteLine("Invalid Command. Type Y to start again or N to exit.");
continue;
}
else if (cmd == 'Y')
Run();
break;
}
}
bool isGuessCorrect(char guess)
{
bool isGood = word.IndexOf(guess) > -1;
List<char> newWord = new List<char>();
for (int i = 0; i < word.Length; i++)
{
if (guess == word[i])
newWord.Add(guess);
else
newWord.Add(current[i]);
}
current = string.Join("", newWord);
return isGood;
}
void writeCurrent()
{
Console.WriteLine("Enter a key below to guess the word.\nHint: {0}", current);
if (guesses.Count > 0)
Console.Write("Already guessed: {0}\n", string.Join(", ", this.guesses));
Console.Write(":");
}
void writeHeader()
{
Console.WriteLine("Hang-CSharp... v1.0\n\n");
if (highScrore > 0)
Console.WriteLine("High Score:{0}\n\n", highScrore);
}
void writeYouLoose()
{
Console.WriteLine("\nSorry you have lost... The word was {0}.", word);
}
void doYouWin()
{
Console.WriteLine("Congratulations you guessed the word {0}.", word);
int score = maxGuess - loss;
if (score > highScrore)
{
highScrore = score;
Console.WriteLine("You beat your high score.. New High Score:{0}", score);
}
else
Console.WriteLine("Your score:{0}\nHigh Score:{1}", score, highScrore);
}
void writeLoss()
{
switch (loss)
{
case 1:
Console.WriteLine(" C");
break;
case 2:
Console.WriteLine(" C{0} #", Environment.NewLine);
break;
case 3:
Console.WriteLine(" C\n/#");
break;
case 4:
Console.WriteLine(" C\n/#\\");
break;
case 5:
Console.WriteLine(" C\n/#\\\n/");
break;
case 6:
Console.WriteLine(" C\n/#\\\n/ \\");
break;
}
Console.WriteLine("\n\nLives Remaining {0}.\n", maxGuess - loss);
}
}
Can be run as new HangCSharp().Run();
The index variable is being set to a random number when the random word is selected in this line.
int index = random.Next(0, 5);
Then that index is being used to store the guesses in the do..while loop. However, since index starts from a random number between 0 and 5 you see unexpected behaviour.
Set index to 0 in the line before the do..while loop and the for loop (or the alternatives suggested elsewhere) should work e.g. as so
index = 0;
int lives = 6;
do
{
// rest of the code

Categories