Problem with palindrome checker for numbers - c#

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;

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);

A simple iteration with if else

Iterating through an array of strings i want it to write a specific line if one of the elements coresponds to the condition. The problem is with the else condition. It is written as many times as the length of the array and i only need it written once
public static void FindSandy(params string[] ocean)
{
for (int i = 0; i < ocean.Length; i++)
{
if (ocean[i] == "Sandy")
{
Console.WriteLine("We found Sandy on position {0}", i);
}
else
{
Console.WriteLine("He was not here");
}
}
}
static void Main(string[] args)
{
{
FindSandy("Bob","Bella", "Sandy", "Nemo", "Dory");
}
}
What about if you just return if you found it?
public static void FindSandy(params string[] ocean)
{
for (int i = 0; i < ocean.Length; i++)
{
if (ocean[i] == "Sandy")
{
Console.WriteLine("We found Sandy on position {0}", i);
// Found, you can return from method.
return;
}
}
// Not found, write the 'not found' message.
Console.WriteLine("He was not here");
}
The simplest way to change your code to handle this is to create a variable that tracks the index where Sandy is found, initialize it to an invalid value (like -1), and then set it to the actual value in your if block (and we can also add a break; statement to exit the loop as soon as we find him).
Then, we output a string based on the value of the position variable:
public static void FindSandy(params string[] ocean)
{
int position = -1;
for (int i = 0; i < ocean?.Length; i++)
{
if (ocean[i] == "Sandy")
{
position = i;
break;
}
}
if (position > -1)
{
Console.WriteLine("We found Sandy on position {0}", position);
}
else
{
Console.WriteLine("He was not here");
}
}
The code can be simplified a little with the System.Linq extension methods Select (to select the name and then index) and FirstOrDefault which returns the first item that meets a condidion, or the default for the type (which is null):
public static void FindSandy(params string[] ocean)
{
var position = ocean?.Select((name, index) => new {name, index})
.FirstOrDefault(item => item.name == "Sandy");
Console.WriteLine(position == null
? "He was not here"
: $"We found Sandy on position {position.index}");
}
You can use the keyword break to exit the for loop :
public static void FindSandy(params string[] ocean)
{
for (int i = 0; i < ocean.Length; i++)
{
if (ocean[i] == "Sandy")
{
Console.WriteLine("We found Sandy on position {0}", i);
break;
}
else if (i == ocean.Length - 1)
{
Console.WriteLine("He was not here");
break;
}
}
}
To solve your issue, you could add a new boolean variable (e.g. weFoundSandy): if you find an occurrence, set this variable to true, use the break statement (to reduce the iterations of the for) and, at the end, use this boolean variable to determine which message to display.
public static void FindSandy(params string[] ocean) {
bool weFoundSandy = false;
for (int i = 0; i < ocean.Length; i++) {
if (ocean[i] == "Sandy") {
Console.WriteLine("We found Sandy on position {0}", i);
weFoundSandy = true;
break;
}
}
if (!weFoundSandy) {
Console.WriteLine("Sandy was not here");
}
}
or, you could simply use the C# Array.IndexOf method, e.g.:
public static void FindSandy(params string[] ocean) {
int indexOfSandy = Array.IndexOf(ocean, "Sandy");
if (indexOfSandy >= 0) {
Console.WriteLine("We found Sandy on position {0}", indexOfSandy);
} else {
Console.WriteLine("Sandy was not here");
}
}

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;
}
}
}

Foreach won't return elements of char list

So im making this hangman game, as Im trying to learn C# but now im stuck with System.Collection.Generic.List'1[System.Char]. What im trying to do is to save wrong answers into List nepravilne, look into functions izpis and igra
class Program
{
static private int _sccore;
static void Main(string[] args)
{
string beseda;
int dolzina;
bool play=true;
char input;
do
{
beseda = izberi_besedo();
dolzina = beseda.Length;
igra(beseda, dolzina);
Console.WriteLine("Vnesite Y za nadaljevanje ali N za zakljucitev igre.");
input = char.Parse(Console.ReadLine());
if (input.Equals('y'))
{
play = true;
Console.WriteLine("play {0}",play);
}
if (input.Equals('n'))
{
play = false;
Console.WriteLine("play {0}", play);
}
} while (play == true);
}
static private string izberi_besedo() {
string[] besede = { "voda", "ladija", "letalo", "motor", "klavir", "harmonika", "saksofon", "oklep", "penkalo", "tiskalnik", "miza", "copat", "krogla", "klobuk", "gumb", "harfa", "kontrabas", "mandarina", "les", "knjiga", "vlak", "vijak", "struna", "kozarec" };
Random rnd = new Random();
int stevilka = rnd.Next(0, 23);
string beseda = besede[stevilka];
return beseda;
}
static private void igra (string beseda, int dolzina){
int i, poizkusi = 0;
int pravilne = 0;
bool endloop = false;
char crka;
List<char> nepravilne = new List<char>();//declaring char list for wrong words
string[] odkrite = new string[dolzina];
for(i=0; i<dolzina; i++) { odkrite[i] = "_"; }
do {
izpis(odkrite,nepravilne); //izpis - function which returns just text, we are inputing list nepravilne, which are wrong answers
vpis(out crka);
if (!(beseda.Contains(crka)))//if word doesen't contain letter
{
poizkusi++;
_sccore--;
nepravilne.Add(crka);//add that letter to list
}
for (i = 0; i<dolzina; i++)
{
if (crka.Equals(beseda[i]))
{
odkrite[i] = Convert.ToString(crka);
pravilne++;
_sccore++;
}
}
Console.Clear();
if (pravilne >= dolzina || poizkusi >= 4)endloop = true;
} while (endloop==false);
}
static private void vpis(out char crka)
{
string vpis;
bool stevilka=false, status;
Console.WriteLine("\nVnesite crko za ugibanje besede");
vpis = Console.ReadLine();
stevilka = IsNumeric(vpis);
if (vpis.Length == 1 && stevilka==false)
{
crka = Convert.ToChar(vpis);
}
else
{
do
{
status = false;
if (vpis.Length!=1) Console.WriteLine("Vnesli ste prevec crk, poizkusite ponovno");
if(stevilka==true) Console.WriteLine("Vnesli ste stevilko, poizkusite ponovno");
vpis = Console.ReadLine();
stevilka = IsNumeric(vpis);
if (vpis.Length == 1 && stevilka == false)
{
status = true;
}
} while (status==false);
crka = Convert.ToChar(vpis);
}
}
private static bool IsNumeric(string vpis)
{
int number;
return int.TryParse(vpis, out number);
}
private static void izpis(string[] odkrite, List<char> nepravilne)
{
Console.Write("Rezultat {0} | ", _sccore);
foreach (char element in nepravilne)//write out char elements which contain letter
{
Console.Write("{0} ", nepravilne);
}
Console.WriteLine();
foreach (string element in odkrite)
{
Console.Write("{0} ", element);
}
}
}
}
I think you have a typo in the following code, i.e I think you are intending to print the variable element in the loop and not nepravilne:
foreach (char element in nepravilne)
{
Console.Write("{0} ", nepravilne);
}
Should be as follows instead?
foreach (char element in nepravilne)
{
Console.Write("{0} ", element);
}

Loop for char not working

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

Categories