Loop for char not working - c#

So, I am attempting to make a loop where if someone enters a char it will execute. If it is wrong it will will display not an option. If I put an Else {Console.WriteLine("Not an option") at the end of the the "end" after my Array() method, it doesn't work either.
So, I am not completely sure of what I am doing. Does this even require a loop? As I would imagine it does to work? Any suggestions would be wonderful.
class Program
{
static void Main(string[] args)
{
string _a = "";
constructor dick = new constructor();
Console.WriteLine("Enter C for constructor, M for method, A for an array...");
Console.WriteLine("Please reference source code to have full details and understanding...");
while (_a.ToUpper() == "C" || "M" || "A")
{
_a = Console.ReadLine();
if (_a.ToUpper() == "C")
{
Console.WriteLine(dick.a);
}
if (_a.ToUpper() == "M")
{
Shit();
}
if (_a.ToUpper() == "A")
{
Array();
}
}
}
public class constructor
{
public string a = "This is a constructor!";
}
static public void Shit()
{
string b = "This is a method!";
Console.WriteLine(b);
}
static public void Array()
{
Console.WriteLine("\nHow large of an array?\n");
string sSize = Console.ReadLine();
int arraySize = Convert.ToInt32(sSize);
int[] size = new int[arraySize];
Random rd = new Random();
Console.WriteLine();
for (int i = 0; i < arraySize; i++)
{
size[i] = rd.Next(arraySize);
Console.WriteLine(size[i].ToString());
}
}
}
}

instead of this:
while (_a.ToUpper() == "C" || "M" || "A")
Define a bool variable and:
bool control = true;
while (control)
{
_a = Console.ReadKey();
var character = _a.KeyChar.ToString().ToUpper();
switch (character)
{
case "C":
Console.WriteLine(dick.a);
control = false;
break;
case "M":
control = false;
Shit();
break;
case "A":
control = false;
Array();
break;
default:
Console.WriteLine("You entered wrong character");
break;
}
}
If you want to force user to enter a correct character, yes you need a loop.And use Console.ReadKey instead of Console.ReadLine if the input is just one character

Related

How to create Palindrome with Reverse method

I am learning C# but I just stack at some simple task with creating Palindrome function. I decided to change string to char array and then use reverse method and compare initial char array to reversed one. But it is look like reverse method do not work when put into if statement, or maybe I made mistake somewhere else??
void IsPalindrome(string x)
{
bool isEqual = true;
char[] charArr = x.ToCharArray();
char[] reversed = charArr;
Array.Reverse(reversed);
for (int i = 0; i < reversed.Length; i++)
{
if (reversed[i] != charArr[i])
{
isEqual = false;
}
}
if (isEqual == true)
{
Console.WriteLine($"True, {x.Length}");
}
else
{
Console.WriteLine($"False, {x.Length}");
}
}
Console.WriteLine("Type a string:");
string? userString = Console.ReadLine();
IsPalindrome(userString);
charArr and reversed are pointing to the same address in memory. Try this instead:
void IsPalindrome(string x)
{
bool isEqual = true;
char[] reversed = x.ToCharArray();
Array.Reverse(reversed);
for (int i = 0; i < reversed.Length; i++)
{
if (reversed[i] != x[i])
{
isEqual = false;
}
}
if (isEqual == true)
{
Console.WriteLine($"True, {x.Length}");
}
else
{
Console.WriteLine($"False, {x.Length}");
}
}
Console.WriteLine("Type a string:");
string? userString = Console.ReadLine();
IsPalindrome(userString);

How can I use List.Contains

I have assignment to make Hangman game with methods, so far everything is going ok until I realized that the word that I input by char when has two consecutive characters it can't get the following if statement
if (correctGuesses.Count == randomWord.Length)
{
Console.WriteLine("You won the word is: {0}", randomWord);
break;
}
and thus I can never finish the game if the word is something like Green
I was trying to use List.Contains('*') if contains it to continue if not to break and to write the Word thus to win, but it fails if I put '!' in front or if I don't put it, it becomes a endless loop . Could you please help me if there is a way to use Contains in a way that will not search only for one symbol but will check for every single one until there is no more.
I will post the code here.
static string GeneratingRandomWords()
{
Random r = new Random();
List<string> words = new List<string>() { /*"Cat", "Dog", "Eagle", "Lion", "Shark",*/ "Green" };
string word = words[r.Next(0, words.Count)];
return word;
}
static char Input()
{
char inputt = char.Parse(Console.ReadLine());
return inputt;
}
static char[] TransformingCharToInvisible(string randomWord)
{
char[] charFromString = randomWord.ToCharArray();
for (int i = 0; i < randomWord.Length; i++)
{
charFromString[i] = '*';
}
Console.WriteLine(charFromString);
return charFromString;
}
static int CorrectGuesses(char input, string randomWord, int correct)
{
if (randomWord.Contains(input))
{
Console.WriteLine("Next");
correct++;
}
return correct;
}
static int Lives(string randomWord, char input, int lives)
{
if (!randomWord.Contains(input))
{
Console.WriteLine("Try another one");
lives--;
}
return lives;
}
static List<char> CorrectWord(List<char> correctGuesses, string randomWord, char input)
{
if (randomWord.Contains(input))
{
correctGuesses.Add(input);
char[] charFromString = randomWord.ToCharArray();
for (int i = 0; i < randomWord.Length; i++)
{
charFromString[i] = '*';
if (correctGuesses.Contains(randomWord[i]))
{
charFromString[i] = randomWord[i];
}
}
Console.WriteLine(charFromString);
}
return correctGuesses;
}
static void Main(string[] args)
{
string randomWord = GeneratingRandomWords();
TransformingCharToInvisible(randomWord);
List<char> correctGuesses = new List<char>();
int lives = 10;
int correct = 0;
//bool won = true;
while (true)
{
Console.WriteLine("Write a char");
char input = Input();
correct = CorrectGuesses(input, randomWord, correct);
lives = Lives(randomWord, input, lives);
if (correctGuesses.Contains(input))
{
Console.WriteLine("You've already tried '{0}', and it was correct!", input);
continue;
}
correctGuesses = CorrectWord(correctGuesses, randomWord, input);
if (lives == 0)
{
Console.WriteLine("You lose sorry, try againg next time ");
break;
}
if (correctGuesses.Count == randomWord.Length)
{
Console.WriteLine("You won the word is: {0}", randomWord);
break;
}
}
}
Here a simplified version of your code where i did not add all the error checking but the basics use the required Contains to check if letters are found
static void Main(string[] args)
{
var lives = 10;
var correctGuesses = new List<char>();
var word = "green";
while (true)
{
Console.WriteLine("Guess a letter? ");
// deliberatly just check for 1 character for simplicity reasons
var input = Console.ReadLine()[0];
// if already guessed give a chance to the user to retry
if (correctGuesses.Contains(input))
{
Console.WriteLine("Letter already guessed");
}
else
{
// if the word contains the letter
if (word.Contains(input))
{
// add as a correct guess
correctGuesses.Add(input);
Console.WriteLine("Letter found");
}
else
{
// letter dont exist remove a life
lives--;
Console.WriteLine("Letter not found");
}
}
// check if the user still have lives
if (lives == 0)
{
Console.WriteLine("You lost");
break;
}
// check if the amount of distinct character in the word match
// the amount found. This mean the word is completly guessed
else if (word.Distinct().Count() == correctGuesses.Count())
{
Console.WriteLine("You won you found the word");
break;
}
}
Console.ReadKey();
}
I didn't understand you very well
but I modified your code like this :
private static bool IsCorrectGuess(char input, string actualWord)
{
return actualWord.Contains(input);
}
private static void WriteCorrectGuesses(ICollection<char> correctGuesses, string randomWord)
{
char[] charFromString = randomWord.ToCharArray();
for (var i = 0; i < randomWord.Length; i++)
{
charFromString[i] = '*';
if (correctGuesses.Contains(randomWord[i]))
charFromString[i] = randomWord[i];
}
Console.WriteLine(charFromString);
}
private static string GeneratingRandomWords()
{
var r = new Random();
var words = new List<string>
{
/*"Cat", "Dog", "Eagle", "Lion", "Shark",*/ "Green"
};
return words[r.Next(0, words.Count)];
}
private static char Input()
{
return char.Parse(Console.ReadLine() ?? throw new InvalidOperationException());
}
private static void Main(string[] args)
{
string randomWord = GeneratingRandomWords();
var correctGuesses = new List<char>();
WriteCorrectGuesses(correctGuesses, randomWord);
var lives = 10;
var correct = 0;
//bool won = true;
while (true)
{
Console.WriteLine("Write a char");
char input = Input();
if (IsCorrectGuess(input, randomWord))
{
// correct letter
int score = randomWord.ToCharArray().Count(item => item == input);
for (var i = 0; i < score; i++)
{
correctGuesses.Add(input);
correct++;
}
WriteCorrectGuesses(correctGuesses, randomWord);
if (correctGuesses.Count == randomWord.Length)
{
Console.WriteLine("You won the word is: {0}", randomWord);
Console.Read();
break;
}
Console.WriteLine("Next");
}
else
{
// wrong letter
Console.WriteLine($"Try another one. You still have {lives} to try.");
lives--;
}
if (lives == 0)
{
Console.WriteLine("You lose sorry, try again next time ");
break;
}
}
}

Problem with palindrome checker for numbers

I'm having problem with my code and cannot find my error. Why only the first try is working and on every other tries it prints me false?
Even when I enter 323, which is true, for example, and prints "true" after that everything is false even empty scapes.
class Program
{
public static void Main()
{
string inputedString = Console.ReadLine();
string reversedString = string.Empty;
while (true)
{
if (inputedString == "END")
{
break;
}
for (int i = inputedString.Length - 1; i >= 0; i--)
{
reversedString += inputedString[i];
}
if (reversedString == inputedString)
{
Console.WriteLine("true");
}
else
{
Console.WriteLine("false");
}
}
}
}
You read the first string outside the loop and never reread the string inside the loop. You also don't clear the reversedString so each subsequent time in the loop its wrong.
public static void Main()
{
string inputedString;
string reversedString;
while (true)
{
inputedString = Console.ReadLine();
reversedString = string.Empty;
if (inputedString == "END")
{
break;
}
for (int i = inputedString.Length - 1; i >= 0; i--)
{
reversedString += inputedString[i];
}
if (reversedString == inputedString)
{
Console.WriteLine("true");
}
else
{
Console.WriteLine("false");
}
}
}
}
The part of the code below should be inside the 'while" loop
string inputedString = Console.ReadLine();
string reversedString = string.Empty;

Case Switch with a loop

I am not understanding what is going on in my case statement to determine if I want to redo the users input. Should I make another loop outside of my while loop? I attempted such and my case statement becomes unreachable code. Maybe I am not understanding case-switch statements.
class Program
{
static void Main(string[] args)
{
string _a = "";
constructor con = new constructor();
Console.WriteLine("Enter enter exit to end the program...");
Console.WriteLine("Enter C for constructor, M for method, A for an array...");
Console.WriteLine("Please reference source code to have full details and understanding...");
bool control = true;
while (control)
{
_a = Console.ReadLine();
switch (_a.ToUpper())
{
case "EXIT":
Console.WriteLine("Thank you for using AJ's program...");
control = false;
break;
case "C":
Console.WriteLine(con.a);
Console.WriteLine("Would you like to test another scenario?");
Console.ReadLine();
if (_a.ToUpper() == "Y")
{
Console.ReadLine();
return;
}
control = false;
break;
case "M":
control = false;
metroid();
break;
case "A":
control = false;
Array();
break;
default: Console.WriteLine("No match");
break;
}
}
}
public class constructor
{
public string a = "This is a constructor!";
}
static public void metroid()
{
string b = "This is a method!";
Console.WriteLine(b);
}
static public void Array()
{
try
{
Console.WriteLine("This is a random array. Please enter the size.");
string sSize = Console.ReadLine();
int arraySize = Convert.ToInt32(sSize);
int[] size = new int[arraySize];
Random rd = new Random();
Console.WriteLine();
for (int i = 0; i < arraySize; i++)
{
size[i] = rd.Next(arraySize);
Console.WriteLine(size[i].ToString());
}
}
catch (System.FormatException)
{
Console.WriteLine("Not correct format, restarting array process.");
Array();
}
}
}
}
Here's what I came up with. You had too many ways of exiting your loop, so I removed all of the control = false lines except where the user typed "EXIT"
Also, in case "C" you return out of the method if they choose "Y", I changed that to continue so that the loop would continue.
Finally, I moved the 3 instruction statements into the loop, so when the user hit "Y" it would print those again.
static void Main(string[] args)
{
string _a = "";
constructor con = new constructor();
bool control = true;
while (control)
{
Console.WriteLine("Enter enter exit to end the program...");
Console.WriteLine("Enter C for constructor, M for method, A for an array...");
Console.WriteLine("Please reference source code to have full details and understanding...");
_a = Console.ReadLine();
switch (_a.ToUpper())
{
case "EXIT":
Console.WriteLine("Thank you for using AJ's program...");
control = false;
break;
case "C":
Console.WriteLine(con.a);
Console.WriteLine("Would you like to test another scenario?");
_a = Console.ReadLine(); //<==problem #1 you didnt set your var name
if (_a.ToUpper() == "Y")
{
continue; //<==problem #2 return exits the program, continue, just keeps going
}
control = false;
break;
case "M":
metroid();
break;
case "A":
Array();
break;
default:
Console.WriteLine("No match");
break;
}
}
}
I think you should considering goto in this case. Yes you need to put some extra effort, but it will help you overcoming the While loop.
A sample below:
switch (_a.ToUpper())
{
case "EXIT":
Console.WriteLine("Thank you for using AJ's program...");
control = false;
// execute goto when your all line executes successfully
goto case "New";
case "New":
// some logic
}
See working sample here Goto-Switch
string NewInput= Console.ReadLine();
if (NewInput.ToUpper() == "Y")
{
//print some thing with console.writeline
//if after this you want to restart the loop then instead of return use
continue;
}
Try putting the Console.Writeline inside the while loop like this:
static void Main(string[] args)
{
bool control = true;
while (control)
{
Console.WriteLine("Enter enter exit to end the program...");
Console.WriteLine("Enter C for constructor, M for method, A for an array...");
Console.WriteLine("Please reference source code to have full details and understanding...");
string _a = Console.ReadLine();
switch (_a.ToUpper())
{
case "EXIT":
Console.WriteLine("Thank you for using AJ's program...");
control = false;
break;
case "C":
Console.WriteLine("press c");
Console.WriteLine("Would you like to test another scenario?");
Console.ReadLine();
if (_a.ToUpper() == "Y")
{
Console.ReadLine();
return;
}
control = false;
break;
case "M":
control = false;
metroid();
break;
case "A":
control = false;
Array();
break;
default: Console.WriteLine("No match");
break;
}
}
}
Additional reading about switch here and here.
Just add comment for the result, thanks. Hope this helped!
may be you want to change
Console.ReadLine();
if (_a.ToUpper() == "Y")
{
Console.ReadLine();
return;
}
as
_a = Console.ReadLine();
if (_a.ToUpper() == "Y")
{
_a = Console.ReadLine();
continue;
}

Error with if/else condition in main method

I need to press t two times in order to get any output; otherwise the program goes directly into the else condition or gives an exception handler error. What am I doing wrong here?
As you guys can see there are two classes one twotable and other program which contains the main method. I am trying to get the output using the invoke method of twotable class.
namespace ConsoleApplication6
{
class twotable
{
public static void two()
{
int i;
int j;
for (i = 1; i <= 10;i++)
{
for (j = 2; j <= 2;j++ )
{
Console.WriteLine(i * j);
}
}
}
}
class Program
{
static void Main()
{
Console.WriteLine("Press t for two table");
char c = Convert.ToChar(Console.ReadLine());
{
char t = Convert.ToChar(Console.ReadLine());
if (c == t)
{
twotable.two();
}
else
{
Console.WriteLine("i hate u");
}
}
}
}
}
You are reading from the console twice.
Instead of
char t = Convert.ToChar(Console.ReadLine());
if (c == t)
You need
if (c == 't')
Do you want the user to enter in the character 't' twice on separate ReadLine()s in order to show the output? If so:
static void Main()
{
Console.WriteLine("Press t for two table");
char c1 = Convert.ToChar(Console.ReadLine());
char c2 = Convert.ToChar(Console.ReadLine());
if (c1 == 't' && c2 == 't')
{
twotable.two();
}
else
{
Console.WriteLine("i hate u");
}
}
Or do you want to read in 'tt' in one ReadLine()?
static void Main()
{
Console.WriteLine("Press t for two table");
string input = Console.ReadLine();
if (input.Equals("tt"))
{
twotable.two();
}
else
{
Console.WriteLine("i hate u");
}
}
Code is little bit messy, but loking even on this code
char c = Convert.ToChar(Console.ReadLine());
...
{
char t = Convert.ToChar(Console.ReadLine());
.....
}
you call Console.ReadLine(...) 2 times, so you need to press t 2 times.
It's hard to say, but probabbly you want to do something like:
char t = 't';
...
{
char consoleChar = Convert.ToChar(Console.ReadLine());
if(consoleChar == t) // or simple if(consoleChar == 't')
{
//do something here, we get a t symbol from console
}
.....
}
My be need to use Console.ReadKey instead, and test c == 't':
Obtains the next character or function key pressed by the user.
and your code like this:
var cki = Console.ReadKey();
if (cki.KeyChar == 't')
{
...
}
I think your problem is here - char c. You're comparing char c with char t
Both lines ask for user input.
char c = Convert.ToChar(Console.ReadLine());

Categories