I have a simple code just to have fun, it was supposed to print the entire alphabet, each letter separated from each other with 100 empty lines... But this is not printing any line....
Note: Before I used code similar to this and it worked (obviously the other was real code and didn't have the 100 lines thingy)
"alfabeto" = "alphabet" (Portuguese word, I was not going to translate 26 lines if I could just say this)
namespace Alfabeto_das_100_linhas
{
class Inicial
{
static void Main(string[] args)
{
string[] alfabeto = new string[26];
alfabeto[0] = "A";
alfabeto[1] = "B";
alfabeto[2] = "C";
alfabeto[3] = "D";
alfabeto[4] = "E";
alfabeto[5] = "F";
alfabeto[6] = "G";
alfabeto[7] = "H";
alfabeto[8] = "I";
alfabeto[9] = "J";
alfabeto[10] = "K";
alfabeto[11] = "L";
alfabeto[12] = "M";
alfabeto[13] = "N";
alfabeto[14] = "O";
alfabeto[15] = "P";
alfabeto[16] = "Q";
alfabeto[17] = "R";
alfabeto[18] = "S";
alfabeto[19] = "T";
alfabeto[20] = "U";
alfabeto[21] = "V";
alfabeto[22] = "W";
alfabeto[23] = "X";
alfabeto[24] = "Y";
alfabeto[25] = "Z";
for (int i = 0; i <= alfabeto.Length; i++)
{
Console.WriteLine(alfabeto[i]);
for(int iii = 0; i != 100; iii++)
{
Console.Write("\n");
}
Console.WriteLine();
}
Console.Read();
}
}
}
Your inner loop is wrong:
for(int iii = 0; i != 100; iii++)
{
Console.Write("\n");
}
Depending on the the value of i this will either do nothing or loop forever.
It should be:
for(int iii = 0; iii < 100; iii++)
{
Console.Write(Environment.NewLine);
}
In addition to fixing your loop counter, you were outputting the string \n rather than the newline character. You could also just use WriteLine with an empty string.
Now I look again, I see that your outer loop is also wrong. It should be:
for (int i = 0; i < alfabeto.Length; i++)
If you loop to the count equal to the length you'll exceed the length of the array - a 26 element array has indices 0 to 25.
If you're not sure what the inner loop is doing I'd reduce the end test to something more manageable (5 for example) so you can see exactly how many lines are being inserted between each of your letters. You could also output the loop counter (as a debug measure) as an extra check
Also notice that you have 101 line, not 100. Should be:
for (int i = 0; i < alfabeto.Length; i++)
{
Console.WriteLine(alfabeto[i]);
for (int iii = 0; iii < 100; iii++)
{
Console.WriteLine();
}
}
Console.Read();
Or you can simplify:
string s = new string('\n', 100);
for (char ch = 'A'; ch <= 'Z'; ch++)
{
Console.WriteLine(ch);
Console.Write(s);
}
Console.Read();
Related
I'm making a program that generates the "names" (random lines of text from the ASCII) that are the names of movies in this instance. I should follow them up with a "name" of a director for each (can also be generated from the ASCII), and after that the random year that is the year the "movie" was made (from 1896 to 2021).
I have two separate functions that randomize the names of the movies and directors, but I'm confused with the supposed placement of the Console.Writeline which the intelligence only allows inside their own loops. Otherwise it doesn't seem to be able to use the values "directorname" and "moviename".
I need it to write the names in a single line, ai. (KHGTJ, KGHTJF).
Also I need a way to generate a random year from 1896 to 2021 that is printed after the names of the movie, and director, ai. (KFJU, MDDOS, 1922).
private static void GenerateRandomNames()
{
Random random = new Random();
char y = (char)65;
for (int p = 0; p < 100; p++)
{
string directorname = "";
for (int m = 0; m < 5; m++)
{
int b = random.Next(65, 90);
y = (char)b;
directorname += y;
}
Console.WriteLine(directorname);
}
Random rnd = new Random();
char x = (char)65;
for (int j = 0; j < 100; j++)
{
string moviename = "";
for (int i = 0; i < 5; i++)
{
int a = rnd.Next(65, 90);
x = (char)a;
moviename += x;
}
Console.WriteLine(moviename);
}
Console.WriteLine();
I need to fix the plecement of the Console.Writeline() so it can print both names in the same line, and be able to print the year after them.
I've tried placing the Console.Writeline() outside the loops, but of course it can't then use the name. But this way it prints them the wrong way.
If you want to have minimal changes in your code, you can use the following code:
private static void GenerateRandomNames()
{
//a separate thing for the names of the directors (ASCII)
// then for the years they were made (1896-2021)
//they should all be printed in the end ie. (KGMFK, JDBDJ, 1922)
Random rnd = new Random();
char x = (char)65;
for (int j = 0; j < 100; j++)
{
string directors = "";
string moviename = "";
for (int i = 0; i < 5; i++)
{
int a = rnd.Next(65, 90);
x = (char)a;
moviename += x;
}
for (int i = 0; i < 5; i++)
{
int a = rnd.Next(65, 90);
x = (char)a;
directors += x;
}
Console.WriteLine("( "+directors +", "+ moviename + ", " +rnd.Next(1896, 2021).ToString()+" )");
}
Console.WriteLine();
}
and result:
Not sure if it is good to answer this type of question, but answering it anyway.
Since you only want other 5-letter words and 4-digit numbers ranging from 1896 - 2021,
Just get another variable 'b' and do the same as you did for 'a', like :
int b = rnd.Next(65,90) ;
y = char(b) ;
director name += y ;
and to get the year value, you can use this :
year = rnd.Next(1896,2021)
So, by combining all of the above, you have the code like this :
internal class Program
{
private static void GenerateRandomNames()
{
Random rnd = new Random();
char x = (char)65;
char y = (char) 65 ;
for (int j = 0; j < 100; j++)
{
string moviename = "";
string directorName = "";
int year = rnd.Next(1896,2021);
for (int i = 0; i < 5; i++)
{
int a = rnd.Next(65, 90);
int b = rnd.Next(65, 90);
x = (char)a;
moviename += x;
y = (char)a;
directorName += x;
}
Console.WriteLine(moviename);
Console.WriteLine(directorName);
Console.WriteLine(year);
}
Console.WriteLine();
}
static void Main(string[] args)
{
GenerateRandomNames();
}
}
The task becomes easier if you extract the creation of a random name to a new method. This allows you to call it twice easily. I moved the random object to the class (making it a class field), so that it can be reused in different places.
internal class Program
{
private static readonly Random _rnd = new Random();
private static string CreateRandomName(int minLength, int maxLength)
{
string name = "";
for (int i = 0; i < _rnd.Next(minLength, maxLength + 1); i++)
{
char c = (char)_rnd.Next((int)'A', (int)'Z' + 1);
name += c;
}
return name;
}
private static void WriteRandomNames()
{
for (int i = 0; i < 100; i++)
{
string movie = CreateRandomName(4, 40);
string director = CreateRandomName(3, 30);
int year = _rnd.Next(1896, 2022);
Console.WriteLine($"{movie}, {director}, {year}");
}
Console.WriteLine();
}
static void Main(string[] args)
{
WriteRandomNames();
}
}
Note that the second parameter of the Next(Int32, Int32) method is the exclusive upper bound. Therefore I added 1.
output:
HATRHKYAHQTGS, NCPQ, 1999
QVJAYOTTISN, LJTGJDMB, 2018
JEXJDICLRMZFRV, GJPZHFBHOTR, 1932
SKFINIGVYUIIVBD, DIZSKOS, 1958
LWWGSEIZT, AMDW, 1950
OAVZVQVFPPBY, SPEZZE, 2008
YLNTZZIXOCNENGYUL, URNJMK, 1962
ONIN, WUITIL, 1987
RJUXGORWDVQRILDWWKSDWF, MOEYPZQPV, 1946
YUQSSOPZTCTRM, UEPPXIVGERG, 1994
KILWEYC, QJZOTLKFMVPHUE, 1915
Wow, in the time it took me to write an answer, three or more others appeared. They all seem like pretty good answers to me, but since I went to the trouble of writing this code, here you go. :)
I focused on using the same Random in different ways, because I think that's what you were asking about.
using System;
using System.Collections.Generic;
using System.Linq;
Random rnd = new Random(1950);
GenerateRandomNames();
void GenerateRandomNames()
{
for (int j = 0; j < 100; j++)
{
// here's one way to get a random string
string name = Guid.NewGuid().ToString().Substring(0, 5);
string description = new string(GetRandomCharacters(rnd.Next(5,16)).ToArray());
string cleaner = new string(GetCleanerCharacters(rnd.Next(5, 16)).ToArray());
string preferred = new string(GetPreferredRandomCharacters(rnd.Next(5, 16)).ToArray());
int year = rnd.Next(1896, DateTime.Now.Year + 1);
Console.WriteLine($"{year}\t{preferred}");
Console.WriteLine($"{year}\t{cleaner}");
Console.WriteLine($"{year}\t{name}\t{description}");
Console.WriteLine();
}
Console.WriteLine();
}
// Not readable
IEnumerable<char> GetRandomCharacters(int length = 5)
{
for (int i = 0; i < length; i++)
{
yield return Convert.ToChar(rnd.Next(0, 255));
}
}
// gives you lots of spaces
IEnumerable<char> GetCleanerCharacters(int length = 5)
{
for (int i = 0; i < length; i++)
{
char c = Convert.ToChar(rnd.Next(0, 255));
if (char.IsLetter(c))
{
yield return c;
}
else
{
yield return ' ';
}
}
}
// Most readable (in my opinion), but still nonsense.
IEnumerable<char> GetPreferredRandomCharacters(int length = 5)
{
for (int i = 0; i < length; i++)
{
bool randomSpace = rnd.Next(0, 6) == 3;
if (i > 0 && randomSpace) // prevent it from starting with a space
{
yield return ' ';
continue;
}
var c = Convert.ToChar(rnd.Next(65, 91)); // uppercase letters
if (rnd.Next(0, 2) == 1)
{
c = char.ToLower(c);
}
yield return c;
}
}
My application basically takes a string of characters and counts how many times each of the alphabetic characters appears. It also ignores numbers being type. But it duplicates the same alphabets second time I input it.
Code:
string input = Console.ReadLine().ToUpper();
while (input[0] != 'q') {
int[] counting = new int[26];
Array.Clear(counting, 0, counting.Length);
//string to array conversion
if (input.Length > 0 && input.ToUpper()[0] == 'Q')
return;
string all = ".";
for (int i = 0; i < input.Length; i++) {
bool checking = false;
string number = "";
for (int j = 0; j < input.Length; j++) {
if (input.ToUpper()[i] == input.ToUpper()[j]) {
number += input.ToUpper()[i];
}
}
for (int j = 0; j < all.Length; j++) {
if (input[i] == all[j]) {
checking = true;
}
}
all += input[i];
if (!checking) {
input = Regex.Replace(input, # "[\d-]", string.Empty);
Console.Write(number[0].ToString() + number.Length.ToString() + " ");
}
}
Console.WriteLine();
input = Console.ReadLine();
It is supposed to only output "A6" which it did successfully the first time but stops on the second time.
Output:
aAaAaA
A6
aAaAaA
A6 A2
For my problem I am experiencing today comes in the form of a string array. The goal of this assignment is to use Random with a seed value of 243 as a key to access a hidden message from 22 lines. Within these 22 lines are 5 letters that form a word. Here is 22 lines containing 60 characters in each line and the goal is to use the key to pick the 5 letters from each line.
String[] line = { "<?JRrP*h^vtVc^ppOZI#PCAa{ (n1>&VSf~59eI7Tn5We^77O/CEvgdq}gU0",
"G;t#o=#|^ZWV01`a-h{=Js>!z`_j!&7PB9nCgtfHZ:WtWk4e&#k5i7uV{$E/",
"]7zXf&4uA=n8!Sa08IIoKyc~:#d*T8FcOWjB?~QQ =Ch(S37UT>RYobbSz>#",
"w*A)v5gHh>p9vvVeUzvfmMT~tr)8s(nC`11Lz:qhjjN6c$Z ^T,W$VQqUB/#",
"+NSrOLhed*2;)$z#}=;t7FY?z6?e^?cX+nf;6me6Kt|TBpN ZNr7&9j t4c8",
"-N&E2X/:<_k0W$HpH${*f?M0K_Qp##F!)M){nVAu`4bzab_too;m8YPm!tyR",
"s=69 j&*yLRpb2IR[RNg~O!ZfUhr{czx]mbB}Hau]T(CtI-%0}1NFeRV<ZRb",
"!U-]QY4sN&S2pW+JGaenHc?|)KQJ:,&Cu}s'GIp:59U)J~]n&(/^s6:=htS ",
"'iXi 0;qbk#|kn&/-5Q*mbC2|FN_bVp6tk3K_3):bj+#%1 I/+0 ]I6CEFDX",
" [/,2k( 7ZNy,7GlV#,kk$PVEpXKTn&8mPX&[~o9)q2S]6rs!3k$:i$]*WeA",
"3[KGT5+Z^#FWPt aq{y/|2I##!}5Kzz$9M&LFieF*8f_l4RGuBie]UD!2+Dh",
"7u.qDs=#k5:' S$dKiRmMU>)1lFb)%:;EL/4)#:Juu[_'a1)Q_TGWUe`V%QW",
"zZxtz~aOCoZGN(vny]#N[=1IOqbnGN]iQbN;Vtc' od`$-xN^&ex##z]HO )",
"<q(t2VukYZf%yyNzWODBw40wgc!Nfpr&]Yj- oNM6-t#^`h(R %o+s0'af-N",
"Ut$gg#F?/#Bg!v+j>,aedrzekyzhebJpb wo(-:>:hw1]<v3hEgU%&h]J=zm",
"D]uLuP$ ~;b1pBk% usN#f #ytk[6:Di1Lx[hK;,7u4mbVca:b[` bk]]qQ ",
"dHicvw De/<SM{7+QR#n0iAR^bUe_;}uy;Fr,PUiV?8*F(37a`++Q.nZ&6%3",
"Bcc-1EY1UG} {a on6,UN=P~/rDjKkguKBG<[*xsM#akb+/zA}gn*Nc$hc}>",
" ndhw'TX-O4f=* LZc<#cHIL#xk|]BSv+Z!^<s-ZUUlpi!Q~F7IimyZVD7de",
":Vzi{=[b)HEaV`M-[Wb#FlVFxNN0 I9. G?}Z#tKDmu|'gM LLzlT->M TpL",
"mKb^.+i/#NRXa7]XuX>1!gbR LOQ(q}%1H]x+.mz:=D}xB*<$eWDj_J%g/0a",
"[{&NOLF9YcL^iCvcBcY+A2LB:UoQ|V1{s,?>7krK{pb#8w]pgfa#U$tHNbay" };
For the chunk of code that I am working on comes here.
String[] decrypted = new String[22];
var randNum = new Random(243);
int i, k;
for (i = 0; i < 22; i++)
{
String currentLine = line[i];
for (k = 0; k < 5; k++)
{
decrypted[i] = Convert.ToString(currentLine[randNum.Next(0, 60)]);
}
}
printIt(decrypted);
Console.ReadLine();
}
static void printIt(string[] decrypted)
{
var build = new StringBuilder();
for (int h = 0; h < 22; h++)
{
build.Append(Convert.ToString(decrypted[h]));
}
Console.WriteLine(build);
The help I am looking for is to understand how I can store the 5 characters from each line successfully within the decrypted array.
I can gain the correct answer if I insert directly in my nested for loop the Console.WriteLine(decrypted[i]);
However, if I try to pull the same line anywhere after the for loop containing random, I only am able to pull the first letter of each line.
Change your loop to:
String[] decrypted = new String[110];
for (i = 0; i < 22; i++)
{
String currentLine = line[i];
for (k = 0; k < 5; k++)
{
decrypted[k + i * 5] = Convert.ToString(currentLine[randNum.Next(0, 60)]);
}
}
And Print:
static void printIt(string[] decrypted)
{
var build = new StringBuilder();
for (int h = 0; h < decrypted.Length; h++)
{
build.Append(Convert.ToString(decrypted[h]));
}
Console.WriteLine(build);
}
I was able to solve my own problem after doing a bit more research and deduction of what I could possibly be missing. Here is the solution.
for (i = 0; i < 22; i++)
{
String currentLine = line[i];
for (k = 0; k < 5; k++)
{
decrypted[i] = decrypted[i] + Convert.ToString(currentLine[randNum.Next(0, 60)]);
//Adding the previous character to the new character to help build up the string.
}
It was after I realized I wasn't building up the characters properly I chose to add the previous character and it solved my problem.
I need to add binary number logic into this snippet. I just cannot wrap my head around how to implement binary numbers, I could just add 0s and 1s but that does not seem to be right
namespace Star_Pyramid
{
class Program
{
static void Main(string[] args)
{
int num;
Console.WriteLine("enter level");
num = Int32.Parse(Console.ReadLine());
int count = 1;
for (int lines = num; lines >= 1; lines--)
{
for (int spaces = lines - 1; spaces >= 1; spaces--)
{
Console.Write(" ");
}
for (int star = 1; star <= count; star++)
{
Console.Write("*");
Console.Write(" ");
}
count++;
Console.WriteLine();
}
Console.ReadLine();
}
}
}
you can use modulo (%)
c = star % 2; // will print first the '1'
c = (star + 1) % 2; // will print first the '0'
int num;
Console.WriteLine("enter level");
num = Int32.Parse(Console.ReadLine());
int count = 1;
int c = 0;
for (int lines = num; lines >= 1; lines--)
{
for (int spaces = lines - 1; spaces >= 1; spaces--)
{
Console.Write(" ");
}
for (int star = 1; star <= count; star++)
{
c = star % 2; //this will return 1 if the value of star is odd then 0 if even
Console.Write(c);
Console.Write(" ");
}
count++;
Console.WriteLine();
}
Console.ReadLine();
VIEW DEMO
So i got The following Code Here... I have to provide 5 User provided words, randomize on the 5 and give any one of them up for a guess, the tries = word length + 2. The main problem i Am having is looping the entire check to fill in the 2nd, 3rd guess etc. The 1st guess is fine. How would i go about looping and keeping the characters which were guessed right while still keeping the ones that were not guessed as a "_" character.
Example - Word was "Heaven" - User Enters "e" - Produces - _ e _ _ e _ No Spaces.
The tries would then be equal to 6(Word Length) + 2 = 8 Tries
int tries = 0;
Random rand = new Random();
int randomword = rand.Next(1, 5);
string word = "";
Console.WriteLine("Please Enter 5 Words into the System");
Console.WriteLine();
for (int i = 0; i < 5; i++)
{
words.Add(Console.ReadLine());
Console.Clear();
}
Console.WriteLine("For Display Purposes. Here are Your 5 Words");
Console.WriteLine("===========================================");
Console.WriteLine();
foreach (var item in words)
{
Console.WriteLine(item);
}
Console.WriteLine();
Console.WriteLine("Now Guess The word given Below");
Console.WriteLine();
switch (randomword)
{
case 1:
//Gets the List index 0 - 1st word in the list
word = words[0];
tries = word.Length;
break;
case 2:
word = words[1];
tries = word.Length;
break;
case 3:
word = words[2];
tries = word.Length;
break;
case 4:
word = words[3];
tries = word.Length;
break;
case 5:
word = words[4];
tries = word.Length;
break;
default:
break;
}
//Default + addition to the Length
tries += 2;
Console.WriteLine();
Console.WriteLine("You Have {0} + tries",tries );
//Works for the 1st Guess
do
{
char guess = char.Parse(Console.ReadLine());
if (word.Contains(guess))
{
foreach (char item in word)
{
if (item == guess)
{
Console.Write(item);
}
else
{
Console.Write("_");
}
}
}
Console.WriteLine();
}
//If my word contains A "_" i will keep looping
while (word.Contains("_"));
Console.ReadKey();
Your main problem is that you're only keeping track of the current guess, not all the previous ones. You can use a HashSet to keep track of your previous guesses. So define a variable HashSet<char> guessedLetters before your do loop, and then as the 2nd line in your loop after you parse "guess" do guessedLetters.Add(guess). Then substitute if(item==guess) with if(guessedLetters.Contains(item)). Viola, only three lines code change!
Finally your exit condition can be while (word.Any(c=>!guessedChars.Contains(c)) && --tries != 0);.
How about:
static void Main(string[] args)
{
string[] words = new string[] { "Apple", "Banana", "Pear", "Pineapple", "Melon"};
Random random = new Random();
string wordToGuess = words[random.Next(5)].ToLower();
char[] currentLetters = new char[wordToGuess.Length];
for (int i = 0; i < currentLetters.Length; i++) currentLetters[i] = '_';
int numTries = currentLetters.Length + 1;
bool hasWon = false;
do
{
string input = Console.ReadLine().ToLower();
if (input.Length == 1) //guess a letter
{
char inputChar = input[0];
for (int i = 0; i < currentLetters.Length; i++)
{
if (wordToGuess[i] == inputChar)
{
currentLetters[i] = inputChar;
}
}
if (!currentLetters.Contains('_'))
{
hasWon = true;
}
else
{
Console.WriteLine(new string(currentLetters));
}
}
else
{
if (input == wordToGuess)
{
hasWon = true;
}
else
{
Console.WriteLine("Incorrect!");
Console.WriteLine(new string(currentLetters));
}
}
numTries--;
} while (new string(currentLetters) != wordToGuess && numTries > 0 && !hasWon);
if (hasWon)
{
Console.WriteLine("Congratulations, you guessed correctly.");
}
else
{
Console.WriteLine("Too bad! Out of tries");
}
}
you need to store the guessing result and check that for your loop (change your do while loop to as below):
string resultword = word;
do
{
char guess = char.Parse(Console.ReadLine());
if (word.Contains(guess))
{
resultword = resultword.Replace(guess, ' ');
for (int i = 0; i < resultword.Count(); i++)
{
if (resultword[i] == ' ')
{
Console.Write(word[i]);
}
else
{
Console.Write("_");
}
}
}
Console.WriteLine();
}
while (tries-- != 0 && resultword.Trim() != string.Empty);
How about, using your existing code;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
internal class Program
{
private static void Main(string[] args)
{
List<string> words = new List<string>();
int tries = 0;
Random rand = new Random();
var currentLetters = new List<char>();
int randomword = rand.Next(1, 5);
string word = "";
Console.WriteLine("Please Enter 5 Words into the System");
Console.WriteLine();
for (int i = 0; i < 5; i++)
{
words.Add(Console.ReadLine());
Console.Clear();
}
Console.WriteLine("For Display Purposes. Here are Your 5 Words");
Console.WriteLine("===========================================");
Console.WriteLine();
foreach (var item in words)
{
Console.WriteLine(item);
}
Console.WriteLine();
Console.WriteLine("Now Guess The word given Below");
Console.WriteLine();
switch (randomword)
{
case 1:
//Gets the List index 0 - 1st word in the list
word = words[0];
tries = word.Length;
break;
case 2:
word = words[1];
tries = word.Length;
break;
case 3:
word = words[2];
tries = word.Length;
break;
case 4:
word = words[3];
tries = word.Length;
break;
case 5:
word = words[4];
tries = word.Length;
break;
default:
break;
}
//Default + addition to the Length
tries += 2;
Console.WriteLine();
Console.WriteLine("You Have {0} + tries", tries);
//Works for the 1st Guess
do
{
char guess = char.Parse(Console.ReadLine());
if (!currentLetters.Contains(guess))
{
currentLetters.Add(guess);
foreach (var l in word.ToCharArray().Intersect(currentLetters).ToArray())
{
word = word.Replace(l, '_');
}
}
Console.WriteLine(word);
} //If my word contains A "_" i will keep looping
while (word.Contains("_"));
Console.ReadKey();
}
}
}
Working example:
List<string> words = new List<string>();
int tries = 0;
Random rand = new Random();
int randomword = rand.Next(1, 5);
string word = "";
Console.WriteLine("Please Enter 5 Words into the System");
Console.WriteLine();
for (int i = 0; i < 5; i++)
{
words.Add(Console.ReadLine());
Console.Clear();
}
Console.WriteLine("For Display Purposes. Here are Your 5 Words");
Console.WriteLine("===========================================");
Console.WriteLine();
foreach (var item in words)
{
Console.WriteLine(item);
}
Console.WriteLine();
Console.WriteLine("Now Guess The word given Below");
Console.WriteLine();
switch (randomword)
{
case 1:
//Gets the List index 0 - 1st word in the list
word = words[0];
tries = word.Length;
break;
case 2:
word = words[1];
tries = word.Length;
break;
case 3:
word = words[2];
tries = word.Length;
break;
case 4:
word = words[3];
tries = word.Length;
break;
case 5:
word = words[4];
tries = word.Length;
break;
default:
break;
}
//Default + addition to the Length
tries += 2;
Console.WriteLine();
Console.WriteLine("You Have {0} + tries", tries);
List<char> guesses = new List<char>();
string guessedWord = "";
for(int i=0;i<word.Length;i++)
{
guessedWord += "_";
}
//Works for the 1st Guess
do
{
char guess = char.Parse(Console.ReadLine());
if (word.Contains(guess))
{
guesses.Add(guess);
}
foreach (char storedGuess in guesses)
{
if(word.Contains(storedGuess))
{
int index = word.IndexOf(storedGuess);
while(index > -1)
{
StringBuilder sb = new StringBuilder(guessedWord);
sb[index] = storedGuess;
guessedWord = sb.ToString();
index = word.IndexOf(storedGuess, index+1);
}
}
}
Console.WriteLine(guessedWord);
}
while (guessedWord.Contains("_"));
Console.ReadKey();
You mention the number of tries, but you never use it in the code after it is used. Presumably, you want to do the following:
Pick a random word (in your case, you are picking one of the five words supplied by the user)
Set the number of guesses (tries?) equal to the length of the word plus 2. If they guess a letter that is present, then it is free. If the letter is not present, then they lose one of their guesses.
Before each guess, display the word with all the unguessed letters replaced by "_".
When the user guesses a letter that is present, replace the "_" in the displayed word by the letter.
Here is some sample code that should work (untested):
string displayword = String.Copy(word);
for (int j = 0; j < displayword.length; j++) displayword[j]='_';
do {
// Display the word so far.
Console.WriteLine("Word is {0}", displayword);
// Get a guess from the user
char guess = char.Parse(Console.ReadLine());
if (word.Contains(guess)) {
for (j=0; j<word.length; j++) {
if (word[j] == guess) displayword[j]=guess;
}
} else {
// Decrease the tries.
tries--;
}
} while (displayword.Contains("_") && (tries > 0));
You need to distinguish the input word from the result so-far. Initialize the result with underscores, and then add the letters to the result as people guess them. It's a little easier if you make result a char array instead of a string.
var result = new string('_', word.Length).ToCharArray();
do
{
char guess = char.Parse(Console.ReadLine());
for (var i = 0; i < word.Length; ++i)
{
if(word[i] == guess)
{
result[i] = guess;
}
}
Console.WriteLine(new string(result));
}
//If my word contains A "_" i will keep looping
while (result.Contains('_') && --tries != 0);