I've been stuck at this exercise of making an array of cards and then picking a random card out of the first array and then storing it in the second one. My choice of loop is a do while where I increment I (the position of the card in the second array). Although it seems that i does not increment as i thought it would. Could somebody please tell me where i went wrong with this exercise it should be a really easy solve. Thanks in advance.
static void Main(string[] args)
{
string[] myCards = new string [52] {"H1","H2","H3","H4","H5","H6","H7","H8","H9","HT","HJ","HQ","HK",
"D1", "D2","D3","D4","D5","D6","D7","D8","D9","DT","DJ","DQ","DK",
"C1", "C2","C3","C4","C5","C6","C7","C8","C9","CT","CJ","CQ","CK",
"S1", "S2","S3","S4","S5","S6","S7","S8","S9","ST","SJ","SQ","SK"};
int i=0;
bool stopPlaying= true;
string[] arrDeckOfCardsPulled;
arrDeckOfCardsPulled = new string[i+1];
do
{
Console.Write("Choose one of the following options:");
Console.WriteLine("\t'A' : To pick a card.");
Console.WriteLine("\t\t\t\t\t"+"'B' : To fold the deck and END the game.");
string playOrNot = Console.ReadLine();
Random random = new Random();
int randomCard = random.Next(0,52);
string valueOfMycard = myCards[randomCard];
if (randomCard != Array.IndexOf(arrDeckOfCardsPulled, randomCard)) {
switch (playOrNot)
{
case "A":
{
arrDeckOfCardsPulled[i] = valueOfMycard;
Console.WriteLine();
Console.WriteLine("This is the card you picked: " + myCards[randomCard]);
Console.WriteLine();
Console.WriteLine("This is the position of your card in the first array: " + Array.IndexOf(myCards, valueOfMycard));
Console.WriteLine();
Console.WriteLine("This is the position of your card in the second array: " + Array.IndexOf(arrDeckOfCardsPulled, valueOfMycard));
i ++;
}
break;
case "B":
Console.WriteLine();
Console.Write("These are the cards that you pulled:");
foreach (string card in arrDeckOfCardsPulled)
{
Console.Write(card+" ");
}
Console.WriteLine();
Console.Write("I am folding the deck.");
Console.WriteLine();
Console.Write("\n\t\t\t\t\t\t THE END");
Console.WriteLine("\n");
Console.ReadKey();
stopPlaying = false;
break;
default:
break;
}
Console.WriteLine("\n");
}
} while (stopPlaying||(i)<52);
}
I was foolish
An array size is fixed as soon as it is initialized. I'm a total beginner forgive me for wasting your time this is my solution.
static void Main(string[] args)
{
string[] myCards = new string [52] {"H1","H2","H3","H4","H5","H6","H7","H8","H9","HT","HJ","HQ","HK",
"D1", "D2","D3","D4","D5","D6","D7","D8","D9","DT","DJ","DQ","DK",
"C1", "C2","C3","C4","C5","C6","C7","C8","C9","CT","CJ","CQ","CK",
"S1", "S2","S3","S4","S5","S6","S7","S8","S9","ST","SJ","SQ","SK"};
int arrayposition = 0;
bool stopPlaying= true;
string[] arrDeckOfCardsPulled;
arrDeckOfCardsPulled = new string[52];
do
{
Console.Write("Choose one of the following options:");
Console.WriteLine("\t'A' : To pick a card.");
Console.WriteLine("\t\t\t\t\t"+"'B' : To fold the deck and END the game.");
string playOrNot = Console.ReadLine();
Random random = new Random();
int randomCard = random.Next(0,52);
string valueOfMycard = myCards[randomCard];
if (randomCard != Array.IndexOf(arrDeckOfCardsPulled, valueOfMycard)) {
switch (playOrNot)
{
case "A":
{
arrDeckOfCardsPulled[arrayposition] = valueOfMycard;
Console.WriteLine();
Console.WriteLine("This is the card you picked: " + myCards[randomCard]);
Console.WriteLine();
Console.WriteLine("This is the position of your card in the first array: " + Array.IndexOf(myCards, valueOfMycard));
Console.WriteLine();
Console.WriteLine("This is the position of your card in the second array: " + Array.IndexOf(arrDeckOfCardsPulled, valueOfMycard));
arrayposition++;
}
break;
case "B":
string[]yourpulls=new string[arrayposition+1];
Array.Copy(arrDeckOfCardsPulled, 0, yourpulls,0, arrayposition);
Console.WriteLine();
Console.Write("These are the cards that you pulled: ");
foreach (string card in yourpulls)
{
Console.Write(card+" ");
}
Console.WriteLine();
Console.Write("I am folding the deck.");
Console.WriteLine();
Console.Write("\n\t\t\t\t\t\t THE END");
Console.WriteLine("\n");
Console.ReadKey();
stopPlaying = false;
break;
default:
break;
}
Console.WriteLine("\n");
}
} while (stopPlaying||(arrayposition)<53);
}
}
}
Related
I am making an interface to store character and dinosaur variables to a list and then print them out when asked.
There is a switch statement to take the users' inputs:
Case 1: The function allows the user to input character data and then it's put into a list.
Case 2.: The function allows the user to input dinosaur
data and then it put into a list.
Case 3 The function prints the objects in each list. However, whenever I run it it doesn't print anything and comes up with no errors. If I run the code to print each list in their respective case then they print out fine.
class Program
{
static void Main()
{
int NumAns;
Console.WriteLine("*1. Character Creator ");
Console.WriteLine("*2. Dinosaur Creator ");
Console.WriteLine("*3. Display ");
Console.WriteLine("");
Console.WriteLine("Specify your menu choice");
string NumAnsString = Console.ReadLine();
NumAns = Convert.ToInt32(NumAnsString);
MenuChosen(NumAns);
}
static void MenuChosen(int selection)
{
List<Dinosaur> Dinosaur_l = new List<Dinosaur>();
List<Character> CharSave = new List<Character>();
Character character = new Character();
Dinosaur dinosaur = new Dinosaur();
switch (selection)
{
case 1:
Console.WriteLine("You chose Character Creator");
character.CharacterVal();
CharSave.Add(new Character
{
name = character.name,
age = character.age,
height = character.height,
hair = character.hair,
eyes = character.eyes,
glasses = character.glasses
});
Main();
break;
case 2:
Console.WriteLine("You chose Dinosaurs");
dinosaur.DinoVal();
Dinosaur_l.Add(new Dinosaur
{
name = dinosaur.name,
species = dinosaur.species,
diet = dinosaur.diet,
sex = dinosaur.sex
});
Main();
break;
case 3:
Console.WriteLine(" ");
Console.WriteLine("Character: ");
Console.WriteLine(" ");
foreach (Character chara in CharSave)
{
Console.WriteLine(chara.name);
Console.WriteLine(chara.age);
Console.WriteLine(chara.height);
Console.WriteLine(chara.hair);
Console.WriteLine(chara.eyes);
Console.WriteLine(chara.glasses);
}
Console.WriteLine(" ");
Console.WriteLine("Dinosaurs: ");
Console.WriteLine(" ");
foreach (Dinosaur Dino in Dinosaur_l)
{
Console.WriteLine(Dino.name);
Console.WriteLine(Dino.species);
Console.WriteLine(Dino.diet);
Console.WriteLine(Dino.sex);
}
Console.WriteLine(" ");
Main();
break;
}
}
}
This is the code used for CharacterVal function
public class Character
{
public string name;
public string age;
public string height;
public string hair;
public string eyes;
public string glasses;
public int charID = 0;
int x = 1;
public void CharacterVal()
{
charID++;
Console.WriteLine("Name your Character: ");
name = Console.ReadLine();
Console.WriteLine("How old is " + name + "? :");
age = Console.ReadLine();
Console.WriteLine("How tall is " + name + "?: ");
height = Console.ReadLine();
Console.WriteLine("What colour is " + name + "'s hair ?: ");
hair = Console.ReadLine();
Console.WriteLine("What colour is " + name + "'s eyes ?: ");
eyes = Console.ReadLine();
GlassesCheck();
}
public void GlassesCheck()
{
Console.WriteLine("does " + name + " wear glasses? (yes/no): ");
while (x == 1)
{
glasses = Console.ReadLine();
if(glasses =="yes")
{
x = 2;
}
else if(glasses == "no")
{
x = 2;
}
else
{
x = 1;
Console.WriteLine("'"+glasses+"' is not a valid answer, does " + name + " wear glasses? (yes/no): ");
}
}
}
}
This is the code used for the DinoVal function
public class Dinosaur
{
public string species;
public string diet;
public string sex;
public string name;
public void DinoVal()
{
Console.WriteLine("***************************");
Console.WriteLine("*Choose a Dinosaur *");
Console.WriteLine("* *");
Console.WriteLine("*1. Alvarezsaurus *");
Console.WriteLine("*2. Avimimus *");
Console.WriteLine("*3. Bactrosaurus *");
Console.WriteLine("*4. Baryonyx *");
Console.WriteLine("*5. Coloradisaurus *");
Console.WriteLine("*6. Chungkingosaurus *");
Console.WriteLine("***************************");
int Selection = Convert.ToInt32(Console.ReadLine());
switch (Selection)
{
case 1:
Console.WriteLine("you have chosen the Alvarezsaurus");
Console.WriteLine("This is a Carnivore ");
species = "Alvarezsaurus";
diet = "Carnivore";
break;
case 2:
Console.WriteLine("you have chosen the Avimimus");
Console.WriteLine("This is an Omnivore ");
species = "Avimimus";
diet = "Omnivore";
break;
case 3:
Console.WriteLine("you have chosen the Bactrosaurus");
Console.WriteLine("This is a Herbivore ");
species = "Bactrosaurus";
diet = "Herbivore";
break;
case 4:
Console.WriteLine("you have chosen the Baryonyx");
Console.WriteLine("This is a Carnivore ");
species = "Baryonyx";
diet = "Carnivore";
break;
case 5:
Console.WriteLine("you have chosen the Coloradisaurus");
Console.WriteLine("This is an Omnivore ");
species = "Coloradisaurus";
diet = "Omnivore";
break;
case 6:
Console.WriteLine("you have chosen the Chungkingosaurus");
Console.WriteLine("This is a Herbivore ");
species = "Chungkingosaurus";
diet = "Herbivore";
break;
}
Console.WriteLine("Please choose the dinosaurs sex");
Console.WriteLine("1.Male");
Console.WriteLine("2.Female");
int GenderChoice = Convert.ToInt32(Console.ReadLine());
switch (GenderChoice)
{
case 1:
Console.WriteLine("the dinosaur will be male");
sex = "Male";
break;
case 2:
Console.WriteLine("the dinosaur will be female");
sex = "Female";
break;
}
Console.WriteLine("What name will you give this " + sex + " " + species + " ?:");
name = Console.ReadLine();
}
}
i've tried moving
CharSave.Add(new Character
{
name = character.name,
age = character.age,
height = character.height,
hair = character.hair,
eyes = character.eyes,
glasses = character.glasses
});
into case 3 but all that does is print blank spaces for each object
The lists that store the characters and the dinos need to be outside of the MenuChosen method because as you code is written everytime MenuChosen is called new lists are created.
You could:
class Program
{
static List<Dinosaur> Dinosaur_l = new List<Dinosaur>();
static List<Character> CharSave = new List<Character>();
}
Main -> MenuChosen -> Main -> MenuChosen -> ...
Because the way you structured (Main calls MenuChosen which calls Main and so on) your code - if you run the game for long enough - will get end up with a stack overflow.
To avoid this you can run your code in a loop:
Main()
{
while (true) // or selection was 'Quit', etc.
{
your code here
}
// Remove calls to 'Main' from the switch statement.
This question already has answers here:
Retrieving a random word from a string array [duplicate]
(2 answers)
Closed 2 years ago.
Good evening.
I am trying to create a hangman game in C#. It works fine when I use just one secret word (In this example, the word HASHTAG is used).
But I need to get it to work using an array of words as per those featured in the multi-line comments.
Can anyone please offer assistance?
My full code follows...
class HangManGame
{
static void Main()
{
Console.Title = ("Hangman Game");
string secretword = "HASHTAG";
/*string[] secretword = {
"MARIO", "SONIC", "THELEGENDOFZELDA", "DONKEYKONG", "LUIGI",
"PEACH", "LINK", "LARACROFT", "BOWSER", "KRATOS",
"PLAYSTATION", "NINTENDO", "TETRIS", "GRANDTHEFTAUTO",
"FINALFANTASY", "THELASTOFUS", "GHOSTOFTSUSHIMA", "HORIZONZERODAWN",
"HALO", "FORZA", "CRASHBANDICOOT", "WORLDOFWARCRAFT", "CALLOFDUTY",
"FORTNITE", "ANIMALCROSSING", "DOOM", "METALGEARSOLID", "MINECRAFT",
"RESIDENTEVIL", "PACMAN", "SPACEINVADERS", "ASTEROIDS",
"STREETFIGHTER", "MORTALKOMBAT", "SUPERMARIOKART", "POKEMON",
"BIOSHOCK", "TOMBRAIDER"
}; */
List<string> letterGuessed = new List<string>();
int live = 5;
Console.WriteLine("Welcome To Hangman!");
Console.WriteLine("Enter a letter to guess for a {0} Letter Word ", secretword.Length);
Console.WriteLine("You Have {0} Lives remaining \n", live);
Isletter(secretword, letterGuessed);
while (live > 0)
{
string input = Console.ReadLine();
if (letterGuessed.Contains(input))
{
Console.WriteLine("You Entered Letter [{0}] already", input);
Console.WriteLine("Try a Different Letter \n");
GetAlphabet(input);
continue;
}
letterGuessed.Add(input);
if (IsWord(secretword, letterGuessed))
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(secretword);
Console.WriteLine("Congratulations!");
break;
}
else if (secretword.Contains(input))
{
Console.WriteLine("Good Entry \n");
string letters = Isletter(secretword, letterGuessed);
Console.Write(letters);
Console.WriteLine("\n");
}
else
{
Console.WriteLine("That Letter Is Not In My Word");
live -= 1;
Console.WriteLine("You Have {0} Lives Remaining", live);
}
Console.WriteLine();
if (live == 0)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Game Over \nMy Secret Word is [ {0} ]", secretword);
break;
}
}
Console.ReadKey();
}
static bool IsWord(string secretword, List<string> letterGuessed)
{
bool word = false;
for (int i = 0; i < secretword.Length; i++)
{
string c = Convert.ToString(secretword[i]);
if (letterGuessed.Contains(c))
{
word = true;
}
else
{
return word = false;
}
}
return word;
}
static string Isletter(string secretword, List<string> letterGuessed)
{
string correctletters = "";
for (int i = 0; i < secretword.Length; i++)
{
string c = Convert.ToString(secretword[i]);
if (letterGuessed.Contains(c))
{
correctletters += c;
}
else
{
correctletters += "_ ";
}
}
return correctletters;
}
static void GetAlphabet(string letters)
{
List<string> alphabet = new List<string>();
for (int i = 1; i <= 26; i++)
{
char alpha = Convert.ToChar(i + 96);
alphabet.Add(Convert.ToString(alpha));
}
int num = 49;
Console.WriteLine("Letters Left are :");
for (int i = 0; i < num; i++)
{
if (letters.Contains(letters))
{
alphabet.Remove(letters);
num -= 1;
}
Console.Write("[" + alphabet[i] + "] ");
}
Console.WriteLine();
Console.WriteLine("\n");
}
}
}
Implementation of 'Honeyboy Wilson' comment
Random random = new Random();
string secretword = secretwords[random.Next(0, secretwords.Length)];
Switch the declaration order and use the Random class to pick a value from the Array?
string[] secretWords = {
"MARIO", "SONIC", "THELEGENDOFZELDA", "DONKEYKONG", "LUIGI",
"PEACH", "LINK", "LARACROFT", "BOWSER", "KRATOS",
"PLAYSTATION", "NINTENDO", "TETRIS", "GRANDTHEFTAUTO",
"FINALFANTASY", "THELASTOFUS", "GHOSTOFTSUSHIMA", "HORIZONZERODAWN",
"HALO", "FORZA", "CRASHBANDICOOT", "WORLDOFWARCRAFT", "CALLOFDUTY",
"FORTNITE", "ANIMALCROSSING", "DOOM", "METALGEARSOLID", "MINECRAFT",
"RESIDENTEVIL", "PACMAN", "SPACEINVADERS", "ASTEROIDS",
"STREETFIGHTER", "MORTALKOMBAT", "SUPERMARIOKART", "POKEMON",
"BIOSHOCK", "TOMBRAIDER"
};
Random R = new Random();
string secretword = secretWords[R.Next(secretWords.Length)];
So I'm trying to create a dartgame in Console Application with C#.
This is as far as I have gotten atm:
class Program
{
static void Main(string[] args)
{
Game gameOn = new Game();
gameOn.PlayGame();
}
class Game
{
private List<Players> playerList = new List<Players>();
public void AddPlayers(string name)
{
Players names = new Players(name);
playerList.Add(names);
}
public void PlayGame()
{
Console.WriteLine("Välkommen till Dartspelet! Tryck valfri knapp för att fortsätta...");
Console.ReadLine();
Console.WriteLine("Skriv in antal spelare. Ni kommer också att möta en Dator.");
Console.WriteLine();
int players = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < players; i++)
{
Console.Write("Skriv in spelarens namn: ");
string playersNames = Console.ReadLine();
AddPlayers(playersNames);
}
Console.WriteLine();
Console.WriteLine("Spelet har börjat!");
Console.WriteLine();
foreach (Players name in playerList)
{
Console.WriteLine("Datorn börjar att kasta... Var god vänta...");
System.Threading.Thread.Sleep(2000);
Random rng = new Random();
int ranAttempt1 = rng.Next(0, 21);
int ranAttempt2 = rng.Next(0, 21);
int ranAttempt3 = rng.Next(0, 21);
Attempts result = new Attempts(ranAttempt1, ranAttempt2, ranAttempt3);
Console.WriteLine("Datorn Fick " + result.GetScore() + " på 3 kast.");
Console.ReadLine();
Console.WriteLine(name + "s Tur! ");
Console.WriteLine("Skriv in Poäng mellan 0-20 för kast 1:");
int attempt1 = Int32.Parse(Console.ReadLine());
Console.WriteLine("Skriv in Poäng mellan 0-20 för kast 2:");
int attempt2 = Int32.Parse(Console.ReadLine());
Console.WriteLine("Skriv in Poäng mellan 0-20 för kast 3:");
int attempt3 = Int32.Parse(Console.ReadLine());
Attempts result1 = new Attempts(attempt1, attempt2, attempt3);
Console.WriteLine(name + " Fick " + result1.GetScore());
}
Console.ReadLine();
}
}
class Attempts
{
private int attempt1;
private int attempt2;
private int attempt3;
public Attempts(int attempt1 = 0, int attempt2 = 0, int attempt3 = 0)
{
this.attempt1 = attempt1;
this.attempt2 = attempt2;
this.attempt3 = attempt3;
}
public int GetScore()
{
return attempt1 + attempt2 + attempt3;
}
}
class Players
{
private string Name { get; set; }
public List<Attempts> attempts = new List<Attempts>();
public Players(string name = "")
{
Name = name;
}
public override string ToString()
{
return Name;
}
}
}
I need help with creating a while loop around the foreach loop that will end when one of the players has reached a score of 301 or over. I also need a method to keep the score in a List or something like that for every turn. But yeah I'm stuck so any help is greatly appriciated! :)
And sorry if the code is a bit messy
Thanks in advance!
Well, you already have the List for the player's attempts. You could:
add a while loop around the foreach(Players...):
append the attempt after it's finished.
after a each player's attempts, calculate the total score.
print the score and exit if the total score > 301
while(true)
{
foreach(Players name in playerList)
{
// existing code here
// you should encapsulate attempts with getter and setter,
// but according to your Players class this will work.
name.attempts.add(result1);
// now sum up the total results for the player
// exercise for the reader.
int totalResults = player.getTotalScore();
if(totalResults > 301)
{
Console.WriteLine("Player " + name.getName() + " won the game!");
Environment.exit(0);
}
}
}
In my hangman game, I am attempting to prompt the user to enter the number of "lives" (or guesses) the player should be given. After I type a number at the prompt, the following error message is displayed:
Cannot implicitly convert type 'int' to 'string'
The following line causes the error:
lives = Console.ReadLine();
The lives field is an integer. How can I correctly assign a user-entered value to an integer field?
Here is my complete code:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
namespace ConsoleApplication6
{
class Hangman
{
//guesses
public static int lives = 5;
//Words for the game
static string[] wordBank = { "study", "cat", "dress", "shoes", "lipstick" };
// Create new ArrayList and initialize with words from array wordBank
static ArrayList wordList = new ArrayList(wordBank);
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.Title = "C# Hangman";
Console.WriteLine("Hang man!");
//Gamemenu
string response = "";
do
{
Console.Write("Enter Command (1. Add Words, 2. List Words , 3. Play , 4. Exit) Pick 1-4: ");
response = Console.ReadLine();
switch (response)
{
case "1": AddWord(); break;
case "2": ListWords(); break;
case "3": Play(); break;
case "4": break;
}
} while (response != "4");
}
//add words to list
static void AddWord()
{
Console.Write("Enter the word to add: ");
String temp = Console.ReadLine();
wordList.Add(temp);
Console.WriteLine("{0} was added to the dictionary!", temp);
}
//Display words
static void ListWords()
{
foreach (Object obj in wordList)
Console.WriteLine("{0}", obj);
Console.WriteLine();
}
//How many guesses
static void AskLives()
{
try
{
Console.WriteLine("please enter number of lives?");
//This line gives me the error
lives = Console.ReadLine();
}
catch
{
// if user does not enter a number ask it again
AskLives();
}
}
//Gameplay
static void Play()
{
Random random = new Random((int)DateTime.Now.Ticks);
string wordToGuess = wordList[random.Next(0, wordList.Count)].ToString();
string wordToGuessUppercase = wordToGuess.ToUpper();
StringBuilder displayToPlayer = new StringBuilder(wordToGuess.Length);
for (int i = 0; i < wordToGuess.Length; i++)
displayToPlayer.Append('-');
List<char> correctGuesses = new List<char>();
List<char> incorrectGuesses = new List<char>();
bool won = false;
int lettersRevealed = 0;
string input;
char guess;
AskLives();
while (!won && lives > 0)
{
Console.WriteLine("Current word: " + displayToPlayer);
Console.Write("Guess a letter: ");
input = Console.ReadLine().ToUpper();
guess = input[0];
if (correctGuesses.Contains(guess))
{
Console.WriteLine("You've already tried '{0}', and it was correct!", guess);
continue;
}
else if (incorrectGuesses.Contains(guess))
{
Console.WriteLine("You've already tried '{0}', and it was wrong!", guess);
continue;
}
if (wordToGuessUppercase.Contains(guess))
{
correctGuesses.Add(guess);
for (int i = 0; i < wordToGuess.Length; i++)
{
if (wordToGuessUppercase[i] == guess)
{
displayToPlayer[i] = wordToGuess[i];
lettersRevealed++;
}
}
if (lettersRevealed == wordToGuess.Length)
won = true;
}
else
{
incorrectGuesses.Add(guess);
Console.WriteLine("Nope, there's no '{0}' in it!", guess);
lives--;
}
Console.WriteLine(displayToPlayer.ToString());
}
if (won)
Console.WriteLine("You won!");
else
Console.WriteLine("You lost! It was '{0}'", wordToGuess);
Console.Write("Press ENTER to exit...");
Console.ReadLine();
}
}
}
Your lives field is an integer, but Console.ReadLine returns a string.
You can use Int32.Parse(Console.ReadLine()) to parse the input into an integer. Note that an exception will be thrown if the text entered by the user cannot be interpreted as an integer.
Your catch block will work here and re-prompt. It would be more appropriate to use the Int32.TryParse method:
int tmpLives;
if (Int32.TryParse(Console.ReadLine(), out tmpLives))
{
lives = tmpLives;
}
else
{
AskLives();
}
You want to do something along the lines of:
string livesString = Console.ReadLine();
lives = Convert.ToInt32(livesString);
I'm guessing Console.ReadLine() gives you a string. This will not play ball with your integer lives. You could try this:
lives = Int.Parse(Console.ReadLine())
I am very new in C# programming and I have a problem. I dont know where to put my functions and how to declare them so that I can call them from my switch statement. And will I be able to use my numberarr and wordarr array in my functions or do I also need to create a separate function for it Here is my code:
class Program
{
enum Menu
{
Numbers = 1,
Words = 2,
Exit = 3,
}
static void Main(string[] args)
{
bool isValid;
do
{
isValid = true;
Menu menu = 0;
int number;
string word;
Console.WriteLine("Choose an option from the menu: ");
Console.WriteLine("1. Numbers ");
Console.WriteLine("2. Words ");
Console.WriteLine("3. Exit ");
switch (menu)
{
case Menu.Numbers:
List<int> numberarr = new List<int>();
Console.WriteLine("Please input as many numbers as you like or type exit");
number = int.Parse(Console.ReadLine());
numberarr.Add(number);
break;
case Menu.Words:
List<string> wordarr = new List<string>();
Console.WriteLine("Please input as many numbers as you like");
word = Console.ReadLine();
wordarr.Add(word);
break;
case Menu.Exit:
break;
default:
Console.WriteLine("You have made an invalid selection, try again");
isValid = false;
break;
}
} while (isValid);
}
}
class Choice
{
static void Numbers(int sum, int count, int average, int max, int min)
{
}
static void Words(string[] args)
{
}
static void Exit()
{
}
}
You can't use the methods defined in the Choice class in Main because you haven't declared them with the public identifier. In C# class properties default to being private so unless you explicitly declare them as public only the class itself will know of their existence.
So basically just change all of declarations in Choice from static void MethodName to public static void MethodName and then you will be able to call them in main from the Choice class like;
Choice.Exit();
EDIT: You'll also need to make some changes to make the switch statement work. As pointed out in the comments there is no way for menu to have a value other than 0. I suggest you use something more like the following;
isValid = true;
int menu = 0;
int number;
string word;
Console.WriteLine("What type do you want to use?");
Console.WriteLine("Press 1 for numbers, 2 for words, or 3 exit.");
string input = Console.ReadLine(); // we must read the users input
if (!int.TryParse(input, out menu))
{
// the user didn't enter a number make them try again
// note you might want to use a loop here to ensure the program does not
// proceed until the user has entered "1", "2", or "3"
}
switch (menu)
If I am understanding your question, just place your functions within your class. I've adjusted your code accordingly. You may also have problems with your word/num classes. You normally have to instantiate them but with something like Choice myChoice = new Choice();
Class Program
{
enum Menu
{
Numbers = 1,
Words = 2,
Exit = 3,
}
static void Main(string[] args)
{
bool isValid;
do
{
isValid = true;
Menu menu = 0;
int number;
string word;
Console.WriteLine("Choose an option from the menu: ");
Console.WriteLine("1. Numbers ");
Console.WriteLine("2. Words ");
Console.WriteLine("3. Exit ");
switch (menu)
{
case Menu.Numbers:
List<int> numberarr = new List<int>();
Console.WriteLine("Please input as many numbers as you like or type exit");
number = int.Parse(Console.ReadLine());
numberarr.Add(number);
int retInt = functionGetInt(number)
break;
case Menu.Words:
List<string> wordarr = new List<string>();
Console.WriteLine("Please input as many numbers as you like");
word = Console.ReadLine();
wordarr.Add(word);
string retString = functionGetString(word);
break;
case Menu.Exit:
break;
default:
Console.WriteLine("You have made an invalid selection, try again");
isValid = false;
break;
}
} while (isValid);
private string functionGetString(string pParmString)
{
//code
return "string";
}
private int functionGetInt(int pParmInt)
{
//code
return 0;
}
}
}
EDIT:
For the code you presented here this would be one possibility.I removed the enum,i normally try to deal with the code presented but yes it was not necessary:
class Program
{
//enum Menu
//{
// Numbers = 1,
// Words = 2,
// Exit = 3,
//}
static void Main(string[] args)
{
bool isValid;
do
{
isValid = true;
int menu = 0;
int[] number;
string word;
Console.WriteLine("Choose an option from the menu: ");
Console.WriteLine("1. Numbers ");
Console.WriteLine("2. Words ");
Console.WriteLine("3. Exit ");
string s = Console.ReadLine();
while (!Regex.IsMatch(s, "^[1-3]{1}$"))
{
Console.WriteLine("Please enter a valid choice(1 to 3)");
s = Console.ReadLine();
}
menu = Convert.ToInt32(s);
switch (menu)
{
case 1:
List<int> numberarr = new List<int>();
Console.WriteLine("Please input as many numbers as you like separeted by space or comma,or type exit");
string numbers = Console.ReadLine();
if (numbers == "exit")
Choice.Exit();
else
{
number = numbers.Split(new char[] { ',', ' ' }).Select(x => int.Parse(x)).ToArray();
numberarr.AddRange(number);
Choice.Numbers(numberarr.Sum(), numberarr.Count, numberarr.Average(), numberarr.Max(), numberarr.Min());
}
break;
case 2:
List<string> wordarr = new List<string>();
Console.WriteLine("Please input as many numbers as you like separeted by space or comma");
word = Console.ReadLine();
wordarr.AddRange(word.Split(new char[] { ',', ' ' }));
Choice.Words(wordarr);
break;
case 3:
Choice.Exit();
break;
default:
Console.WriteLine("You have made an invalid selection, try again");
isValid = false;
break;
}
} while (isValid);
Console.ReadKey();
}
}
class Choice
{
public static void Numbers(int sum, int count, double average, int max, int min)
{
int a = sum;
int b = count;
double c = average;
int d = max;
int e = min;
//just as example.
}
public static void Words(List<string> args)
{
//do whatever you need here
}
public static void Exit()
{
Environment.Exit(0);
}
}