I am making simple PRG in console.
In my MenuSystem Console.Clear() does not clear text from other methods.
Any ideas?
class MenuSystem
{
public static void Controll(int count, List<String> texts)
{
Console.Clear();
int index = 0;
bool isEnter = false;
Write(0, texts);
while (!isEnter)
{
ConsoleKey key = Console.ReadKey().Key;
switch (key)
{
case ConsoleKey.UpArrow:
index -= 1;
break;
case ConsoleKey.DownArrow:
index += 1;
break;
}
if (index > (count - 1))
index = 0;
else if (index < 0)
index = count - 1;
Write(index, texts);
}
}
private static void Write(int index, List<String> texts)
{
Console.Clear();
texts[index] = "[ " + texts[index] + " ]";
foreach (String text in texts)
{
Console.WriteLine(text);
}
}
Console.Clear() in Write() does not clear console.
I think the problem you're having is not with Console.Clear (whose only purpose is to clear the screen, not "clear text from other methods" as you suggested.
The problem is that you're modifying an element in your array, then modifying a new element in the array without un-modifying the previous one. If you wanted to solve this problem using your current method, then you would need to track which item you previously modified in a class-level variable so you can un-modify it when the user changes the selection.
However, I would suggest a different approach. Instead of modifying the strings in your list, you should just change the way you display the information, not the information itself.
So, after applying your logic to detect which index to select, you just loop through the menu items and write them to the screen, and when you get to the index of the item that's selected, you write the "[" and "]" characters around it. For the other menu items, you should surround them with an empty space character, so they aren't moving all over the place as the selections change.
Note that I also made a small change to have the menu display horizontally:
class MenuSystem
{
public static void Control(List<string> menuItems)
{
var selectedIndex = 0;
var exitMenu = false;
while (!exitMenu)
{
DisplayMenu(selectedIndex, menuItems);
switch (Console.ReadKey().Key)
{
case ConsoleKey.LeftArrow:
selectedIndex -= 1;
if (selectedIndex < 0) selectedIndex = menuItems.Count - 1;
break;
case ConsoleKey.RightArrow:
selectedIndex += 1;
if (selectedIndex > menuItems.Count - 1) selectedIndex = 0;
break;
case ConsoleKey.Enter:
exitMenu = true;
break;
}
}
}
private static void DisplayMenu(int selectedIndex, List<string> menuItems)
{
Console.Clear();
for (int i = 0; i < menuItems.Count; i++)
{
if (i == selectedIndex)
{
Console.Write("[" + menuItems[i] + "]");
}
else
{
Console.Write(" " + menuItems[i] + " ");
}
Console.Write(" ");
}
}
}
This is really an answer to your question but merely a demonstration that the code you have posted does work.
private static void Main()
{
Console.Write("Some Text");
Console.Read(); //Console shows Show Text
MenuSystem.Controll(1, new List<string>() { "string" });
Console.Read(); //Console shows string
}
...
class MenuSystem
{
public static void Controll(int count, List<String> texts)
{
Write(count, texts);
}
private static void Write(int index, List<String> texts) //I don't know why you are passing index as it is never used here.
{
Console.Clear(); //Console is now cleared
foreach (String text in texts)
{
Console.WriteLine(text);
}
}
}
As the code you have provided is working I can only presume that there is some other logic in your full code that is causing the issue.
Please update your question with code that demonstrates your issue.
The example is far from perfect, but you will get the sense of using Console.Clear():
class Program
{
static void DrawPlayer(int x, int y)
{
for (int i = 0; i < y; i++)
Console.WriteLine();
for (int j = 0; j < x; j++)
Console.Write(' ');
Console.Write("\u25A0");
}
static void Main()
{
int playerX = 0, playerY = 0;
while (true)
{
DrawPlayer(playerX, playerY);
var keyInfo = Console.ReadKey(true);
switch (keyInfo.Key)
{
case ConsoleKey.W:
playerY--;
break;
case ConsoleKey.A:
playerX--;
break;
case ConsoleKey.S:
playerY++;
break;
case ConsoleKey.D:
playerX++;
break;
}
Console.Clear();
}
}
}
Related
My assignment is to create a string list that has at least two matching values and then to prompt the user to input one of those values and then I am to display the index or indices of that value entered.
I seem to have figured out how to get the desired indices to show, but I also need to have a statement in the event the value entered is not in the list and when I do an else, it messes things up. Looking for some help on this!
So this does what I want but without the else statement:
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
List<string> mprovinces = new List<string> { "Nova Scotia", "New Brunswick", "Prince Edward Island", "Nova Scotia" };
Console.WriteLine("Enter one of the following maritime provinces: \nNova Scotia, \nNew Brunswick, \nPrince Edward Island\n");
string input2 = Console.ReadLine();
for (int i = 0; i < mprovinces.Count; i++)
{
bool match = mprovinces[i] == input2;
if (match)
{
Console.WriteLine(i);
}
}
}
}
But when I add an else statement and I enter a value that is in the list it provides more data than I want:
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
List<string> mprovinces = new List<string> { "Nova Scotia", "New Brunswick", "Prince Edward Island", "Nova Scotia" };
Console.WriteLine("Enter one of the following maritime provinces: \nNova Scotia, \nNew Brunswick, \nPrince Edward Island\n");
string input2 = Console.ReadLine();
for (int i = 0; i < mprovinces.Count; i++)
{
bool match = mprovinces[i] == input2;
if (match)
{
Console.WriteLine(i);
}
else
{
Console.WriteLine("Sorry, this is not in the list");
}
}
}
}
Since the "Sorry" message is inside of the for loop you will show it for EVERY index that does not exactly match your input2. You need to pull the match value out of the for loop and check it once.
var matchIndex = -1; // can never get a -1 so it's a good default to check for later
for (int i = 0; i < mprovinces.Count; i++)
{
if (mprovinces[i] == input2)
{
matchIndex = i;
break; // break out of loop
}
}
if (matchIndex >= 0) // again a valid index will never be below 0
{
Console.WriteLine("Index: " + matchIndex);
}
else
{
Console.WriteLine("Sorry, this is not in the list");
}
I'm not sure exactly what you want to show. If you only want to show the FIRST index that matches then the above code will work. If you want to show EVERY index that matches then this would work.
EDIT: I have changed this function to not use a string to keep track of the list. It just shows the matching indexes as they appear.
bool matchExists = false;
for (int i = 0; i < mprovinces.Count; i++)
{
if (mprovinces[i] == input2)
{
matchExists = true;
Console.WriteLine(i);
}
}
if (matchExists == false)
{
Console.WriteLine("Sorry, this is not in the list");
}
So I did this hangman game, and it works perfectly fine, the only problem is that I want to use methods to organize everything.
And yes, it is a school project. I tried my best but whenever I try to put a part of the program in a method it's as if I removed a variable and it underlines it in red.
I removed them for now so it's more clear. also, the file I used contained 19 8 letters max words, one on each line.
Can someone tell me how I can incorporate methods without ruining the whole thing? also English isn't my first language plz excuse any mistakes, the code was in french and I translated it for this question. thank you very much. I appreciate your time and effort :)
using System;
using System.IO;
namespace TP3
{
class Program
{
public const String Dico = "dico.txt";
public static void Welcome()
{
//Mot de bienvenue
Console.WriteLine("Welcome to hangman !");
}
public static void Goodbye()
{
Console.WriteLine("thx for playing, goodbye!");
}
public static void Program()
{
int SolvedWords= 0;
string WordToGuess= "";
int NumberOfLetters ;
int x = 0;
int WordTried = 0;
Console.WriteLine("");
Console.WriteLine("Do you wanna guess a word ? oui or non.");
Console.WriteLine("you have 8 chances per word.");
string Answer= Console.ReadLine();
Answer= Answer.ToLower();
while (Answer== "oui" && WordTried <19)
{
const int Lives= 8;
int LostLives= 0;
int LivesLeft= 8;
int LettersGuesed= 0;
x += 1;
WordTried += 1;
if (WordTried <= 20 && WordTried >1)
{
Console.WriteLine("Do you wanna guess a word ? oui or non.");
Answer= Console.ReadLine();
Answer= Answer.ToLower();
}
//Read a word in the file
int compteur = 0;
string ligne;
// Read file and show on the line
System.IO.StreamReader file = new System.IO.StreamReader(#"dico.txt");
while ((line = file.ReadLine()) != null)
{
compteur++;
if (compteur == x)
{
WordToGuess= line;
}
}
file.Close();
char[] table;
table = new char[WordToGuess.Length];
for (int i = 0; i < table.Length; i++)
{
table[i] = WordToGuess [i];
}
//change each letter into a *
Console.WriteLine("here’s the word to guess : ");
string HiddenWord = "********";
char[] table2;
table2 = new char[WordToGuess.Length];
for (int i = 0; i < table2.Length; i++)
{
table2[i] = HiddenWord[i];
}
for (int i = 0; i < table2.Length; i++)
{
Console.Write(table2[i]);
}
Console.WriteLine("");
//guess the word
while (LettersGuesed< WordToGuess.Length && LivesLeft> 0)
{
Console.WriteLine("");
/* Console.WriteLine("Devinez une seule Letterdu mot. Ne pas écrire une Letter plus d'une fois de suite. Si c'est le cas, recommencez le jeu.");*/
string Letter= Console.ReadLine();
Letter= Letter.ToLower();
NumberOfLetters = Letter.Length;
char[] table3;
table3= new char[NumberOfLetters ];
for (int i = 0; i < table2.Length; i++)
{
if (table[i].Equals(Letter[0]))
{
Table2[i] = Letter[0];
LettersGuesed+= 1;
}
}
for (int i = 0; i < table2.Length; i++)
{
Console.Write(table2[i]);
}
if (WordToGuess.IndexOf(Lettre) < 0)
{
Console.WriteLine("");
Console.WriteLine("wrong letter.");
LostLives+= 1;
LivesLeft= Lives- LostLives;
Console.WriteLine("you have " + LivesLeft+ " lives left.");
}
if (WordToGuess.IndexOf(Lettre) >= 0)
{
Console.WriteLine(" ");
Console.WriteLine("right !");
Console.WriteLine("you have " + LivesLeft+ " lives left.");
}
if (LettersGuesed== WordToGuess.Length && LivesLeft> 0)
{
SolvedWords+= 1;
Console.WriteLine(" ");
Console.WriteLine("you found the word !");
Console.WriteLine("you found " + SolvedWords+ " on" + WordTried + " words so far.");
}
if (LivesLeft== 0)
{
Console.WriteLine("you couldnt guess the word.");
Console.WriteLine("the word was :");
for (int i = 0; i < table.Length; i++)
{
Console.Write(table[i]);
}
Console.WriteLine(" ");
Console.WriteLine("you found " + SolvedWords+ " on" + WordTried + " words so far.");
}
if (WordTried == 19)
{
Console.WriteLine("no more words to guess.");
}
}
}
}
static void Main(string[] args)
{
Welcome();
Programme();
Goodbye();
}
}
}
Im not going to make every method for your project, I'll help kickstart on how to think about it. Look at your current code for reading the file of words. You can move that into a method -
public string[] ReadWordsFromFile()
{
string file = "path to your file here";
return File.ReadAllLines(file);
}
Or pass the file path as parameter -
public string[] ReadWordsFromFile(string filePath)
{
return File.ReadAllLines(filePath);
}
Next you can have a method to get random words -
public string GetRandomWord(string[] wordsArray)
{
Random random = new Random();
int randomIndex = random.Next(0, wordsArray.Length);
return wordsArray[randomIndex];
}
Note - words can be repeated if you do it this way, if you don't want that - then add logic to remove that item from the list once its used in the game. If you remove it within this method, its not actually going to remove it from the game, as you'll still be passing the entire array when getting a new word. Ill leave the implementation of that logic to you, if you want it.
In the "game controller" code -
you can use the above methods like this -
string file = "your path to txt file";
string[] allWords = ReadWordsFromFile(file);
string WordToGuess = GetRandomWord(allWords);
May be your next goal should be something like this -
public void GameControler()
{
// get all words here and other logic before game starts
while (Attempts > 0)
{
string WordToGuess = GetRandomWord(wordsArray);
// get letterGuessed from user
bool letterExists = CheckIfLetterExists(WordToGuess, letterGuessed);
if (!letterExists)
{
Attempts--;
ExecuteWrongGuessMethod(x, y);
}
else
{
ExecuteRightGuessMethod(w);
}
}
}
public bool CheckIfLetterExists(string word, string letter)
{
if (word.Contains(letter)) return true;
else return false;
}
public void ExecuteWrongGuessMethod(string passWhatYouNeedTo, int somethingElse)
{
// what to do when the guess is wrong e.g. Console.Writeline("wrong guess");
}
public void ExecuteRightGuessMethod(string word)
{
// logic when guess is right. e.g. Show the letter guessed within the word on the console etc.
}
All of this isn't the best way to do it. BUT I personally feel this is logically next step a beginner takes after what you've implemented. Seeing a fully well-developed program might be too much without understanding atleast some basic concepts of OOP.
After learning how to create Methods and use them, then comes classes and objects. Which should be implemented in this game, but this is all for now. I recommend you do a short C# course on coursera etc or even youtube. And slowly move towards a better understanding of SOLID principles. And by SOLID I mean an acronym for the 5 principles and not the actual word. All the best.
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");
}
}
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;
}
}
}
I wrote this little program that catches five integer numbers that are entered consecutively at the console.
This works as expected - except for one thing:
I did not find a way to accept 0 as one of the numbers being entered.
Of course, a solution with another collection type is easy.
But the challenge here is to do it with an array of five integers.
I tried to set a boolean flag "zeroEntered", tried with a counter, tried to count j backwwards. It all does not work.
Perhaps this is not possible? Would somebody know for sure?
Here is the code:
class Program
{
static void Main(string[] args)
{
#region Catch5IntegerInArrayOfInt[5]
// I try to catch five integers in an array of int[5]
// This works as expected except I cannot catch 0 as one of the numbers
// Cannot wrap my head around this one it seems
// because all ints are initialized with 0
Console.WriteLine("Please enter five unique numbers consecutively.");
int[] fiveNumbers = new int[5]; // do it using an array just the same (as collections were not part of the lectures so far)
for (int i = 0; i < fiveNumbers.Length; i++)
{
Console.WriteLine("Please enter your {0} number:", (Countables)i);
CatchUsersNumbers(fiveNumbers, i);
}
DisplayResult(fiveNumbers);
Console.WriteLine("\n");
}
#endregion
#region HelperMethods
private static bool CheckWhetherInteger(string userInput)
{
bool result = Int32.TryParse(userInput, out myInteger);
if (result == false)
{
Console.Clear();
Console.WriteLine("You did not enter an integer.");
}
return result;
}
private static bool CheckUniqueness(int[] fiveNumbers, int userInput)
{
for (int i = 0; i < fiveNumbers.Length; i++)
{
if (userInput == 0)
{
for (int j = i ; j <fiveNumbers.Length; j--)
{
if (j == 0)
break;
if (fiveNumbers[j] == 0)
{
return false;
}
}
}
else if (fiveNumbers[i] == userInput)
{
return false;
}
}
return true;
}
private static void CatchUsersNumbers(int[] fiveNumbers, int i)
{
while (true)
{
userInput = Console.ReadLine().Trim();
if (CheckWhetherInteger(userInput) && CheckUniqueness(fiveNumbers, myInteger))
{
fiveNumbers[i] = myInteger;
break;
}
else
Console.Clear();
Console.WriteLine("You did not enter a unique integer number, try again...");
}
}
private static void DisplayResult(int[] fiveNumbers)
{
Console.Clear();
Array.Sort(fiveNumbers);
Console.WriteLine("These are the five interger numbers you entered \nand that were stored in the array:\n");
for (int i = 0; i < fiveNumbers.Length; i++)
{
if (i != fiveNumbers.Length - 1)
Console.Write(fiveNumbers[i] + ", ");
else
Console.Write(fiveNumbers[i]);
}
}
#endregion
#region Class Variables
private static int myInteger = 0;
private static string userInput;
private enum Countables
{
first = 0,
second,
third,
fourth,
fifth
}
#endregion
}
Thank you.
It is possible, but your array of 5 ints will be initialized to 5 zeroes, so when scanning for uniqueness, your check fails, especially because of this piece of code:
if (fiveNumbers[j] == 0)
{
return false;
}
So instead of looping through the entire array, you should keep a counter to keep track of how many items you already have in your array. Then, when performing the check, only check upto that index, and don't include the other items in the check, because they contain 0, but you should treat them as uninitialized.
You could also solve this using other data types. For instance, you could create an array of nullable integers, so you can actually check whether an item already got a value. Or (maybe the best solution) you could use a List instead of array.
Your Only error here is that int.TryParse() takes 0 as invalid you could make another if statement to handle the exception but this looks less clean
private static bool CheckWhetherInteger(string userInput)
{
if (userInput == "0")
{
myInteger = 0;
return true
}
else
{
bool result = Int32.TryParse(userInput, out myInteger);
if (result == false)
{
Console.Clear();
Console.WriteLine("You did not enter an integer.");
}
}
return result;
}
I just post the solution - using nullable integers - as suggested by Golez Trol. Here it is, should somebody be interested:
class Program
{
static void Main(string[] args)
{
#region Catch5IntegerInArrayOfInt[5]
// The solution to catching five integers in an array of int[5]
// is to use nullable integers.
// Keeping a counter when entering an integer to the array does not appeal to me.
// With normal integers I cannot catch 0 as one of the numbers
// because all ints are initialized with 0
Console.WriteLine("Please enter five unique numbers consecutively.");
var fiveNumbers = new int?[5]; // do it using an array just the same (as collections were not part of the lectures so far)
for (int i = 0; i < fiveNumbers.Length; i++)
{
Console.WriteLine("Please enter your {0} number:", (Countables)i);
CatchUsersNumbers(fiveNumbers, i);
}
DisplayResult(fiveNumbers);
Console.WriteLine("\n");
}
#endregion
#region HelperMethods
private static void CatchUsersNumbers(int?[] fiveNumbers, int i)
{
while (true)
{
userInput = Console.ReadLine().Trim();
if (CheckWhetherInteger(userInput) && CheckUniqueness(fiveNumbers, myInteger))
{
fiveNumbers[i] = myInteger;
break;
}
else
{
Console.Clear();
Console.WriteLine("You did not enter a unique integer number, try again...");
}
}
}
private static bool CheckWhetherInteger(string userInput)
{
bool result = Int32.TryParse(userInput, out myInteger);
if (result == false)
{
Console.Clear();
Console.WriteLine("You did not enter an integer.");
}
return result;
}
private static bool CheckUniqueness(int?[] fiveNumbers, int userInput)
{
for (int i = 0; i < fiveNumbers.Length; i++)
{
if (fiveNumbers[i] == userInput)
{
return false;
}
}
return true;
}
private static void DisplayResult(int?[] fiveNumbers)
{
Console.Clear();
Array.Sort(fiveNumbers);
Console.WriteLine("These are the five interger numbers you entered \nand that were stored in the array:\n");
for (int i = 0; i < fiveNumbers.Length; i++)
{
if (i != fiveNumbers.Length - 1)
Console.Write(fiveNumbers[i] + ", ");
else
Console.Write(fiveNumbers[i]);
}
}
#endregion
#region Class Variables
private static int myInteger = 0;
private static string userInput;
private enum Countables
{
first = 0,
second,
third,
fourth,
fifth
}
#endregion
}
Thank you for your hints - I was truly stuck.