Couldn't print random switch cases string inside a for loop - c#

Hit everyone! I'm still learning C# and I would like to print different string for each loop based on the switch cases.
static Random rand = new Random();
static void Main(string[] args){
string someString = "";
int someRandom = rand.Next(4);
switch(someRandom) {
case 0:
someString = "Woa";
break;
case 1:
someString = "Waa";
break;
case 2:
someString = "Wee";
break;
case 3:
someString = "Wow!";
break;
}
int someCount = 5;
for (int someInt = 0; someInt < someCount; someInt++) {
Console.WriteLine(someString);
}
Console.Read();
}
What it should do: display random string each loop from the switch.
What it actually does: Selects case randomly and prints the same case in each loop.
I couldn't produce a random string, why is that? I tried adding someRandom = rand.Next(4) inside the for loop but still produces same.
I already tried searching but couldn't find an answer that could solve my problem.

It seems that you are only setting somestring once, and then printing it a bunch. You should put the switch statement in the for loop.

You need to generate the random number (and set the someString variable) inside the loop, otherwise you only pick one random number and then display it multiple times in the loop.
Here's an example but with some slightly better names (IMO):
static Random rand = new Random();
static void Main()
{
int count = 5;
for (int i = 0; i < count; i++)
{
string output;
switch(rand.Next(4))
{
case 0:
output = "Woa";
break;
case 1:
output = "Waa";
break;
case 2:
output = "Wee";
break;
case 3:
output = "Wow!";
break;
default:
output = "This shouldn't happen";
break;
}
Console.WriteLine(output);
}
Console.Read();
}

Related

Regex Error in Switch Statements

I want to create a program that takes in a string and output just the numbers, hopefully using regex to save effort, here is the following code i have
public void main{
string str = "abc-123.44def";
string output = "";
bool setA = false;
StringBuilder stb = new StringBuilder();
for(int i=0; i<str.Length; i++){
switch(str[i]){
case 'b':
setA = foo();
break;
case 'c':
foo2();
break;
case '\d':
case '-':
case '.':
if(setA){
stb.Append(str[i]);
}
break;
default:
break;
}
}
output = stb.toString();
}
public void foo(){
return true;
}
Problem is, the editor gives me a error saying
Unrecognized Escape Sequence
on the '\d' part. Ive seen online sample codes where such usage is allowed so im not sure why my editor is not accepting this. Can someone explain to me what the problem is and how to solve it?
EDIT: It seems like my sample was alittle misleading. I cannot just take out the numbers from the strings by itself since other characters in the string calls different functions and the number characters i want to take out depends on some of them. I updated the code to correct the misinformation.
You can use the Char.IsDigit() to check if a char is a digit (as I mentioned in my first comment):
string str = "abc-123.44def";
string output = "";
bool setA = false;
StringBuilder stb = new StringBuilder();
for(int i=0; i<str.Length; i++){
switch(str[i]){
case 'b':
setA = foo();
break;
case 'c':
foo2();
break;
// case '\d': REMOVE IT
case '-':
case '.':
if(setA){
stb.Append(str[i]);
}
break;
default:
if (Char.IsDigit(str[i])) stb.Append(str[i]); // Add this
break;
}
}
output = stb.ToString();
}
Result:
Is this what you are looking for ?
Regex r = new Regex(#"\d+");
string s = "abc-123.44def";
var matches = r.Matches(s);
List<string> numbersOnly = new List<string>();
foreach (Match match in matches)
numbersOnly.Add(match.Value);
foreach (var number in numbersOnly)
Console.WriteLine(number);
//output:
//123
//44

Why is my array of cards empty?

I am a novice coder learning C# for my class and am having trouble with a practice exercise where we have to make a deck of cards and deal them out.
We need to make a class that creates cards by receiving parameters from another class through a constructor. Then use those values in a Tostring method to set the value and suit of those cards with switch statements and return a card. In the second class we populate an array with cards and call the Tostring method in a Dealing method to randomly generate a user specified amount of cards by pulling them out of the array.
The problem is my array isn't being populated I have tried to Console.WriteLine parts of the array directly after they would be assigned and they are empty. You don't have to give me the full answer put just put me on the right track.
Here is the code:
This is the card creation class
` class Card
{
static int value;
static int suit;
static string cdvalue;
static string cdsuit;
string card;
public Card(int ranvalue, int ransuit) //constructor that sets value and suit
{
value = ranvalue;
suit = ransuit;
}
public override string ToString()
{
switch (value) //switch statement for card value
{
case 1: cdvalue = "ace";
break;
case 2: cdvalue = "two";
break;
case 3: cdvalue = "three";
break;
case 4: cdvalue = "four";
break;
case 5: cdvalue = "five";
break;
case 6: cdvalue = "six";
break;
case 7: cdvalue = "seven";
break;
case 8: cdvalue = "eight";
break;
case 9: cdvalue = "nine";
break;
case 10: cdvalue = "ten";
break;
case 11: cdvalue = "jack";
break;
case 12: cdvalue = "queen";
break;
case 13: cdvalue = "king";
break;
}
switch (suit) // switch for card suit
{
case 1: cdsuit = "Hearts ";
break;
case 2: cdsuit = "Spades ";
break;
case 3: cdsuit = "Diamonds ";
break;
case 4: cdsuit = "Clubs ";
break;
}
card = cdvalue + " of " + cdsuit;
return card;// returns a string in the form of "value of suit"`
This class creates the deck
class Deck
{
Random rng = new Random(); //Random object
private static Card[] deck;
static string[] cards;
public Deck()
{
deck = new Card[52];//creates array of 52 elements
int l = 0;
for (int i = 1; i <= 13; i++)//loops to create cards
{
for (int j = 1; j <= 4; j++)
{
deck[l++] = new Card(i,j); // populates the array with all 52 cards
}
}
}
static string dealt;
static int Rndm;
public string deal(int number)//parameter received from user
{
cards = new string[number];//creates an array to contain dealt card objects
int m = 0;
for (int num=0;num<number;num++) // determines the amount of cards to be dealt
{
Rndm = rng.Next(0,53);
cards[m++] = deck[Rndm].ToString();//fills the card array with randomly dealt cards from the deck
dealt = string.Join(" ", cards); // turns the card array into a single string of the cards dealt
}
return dealt;//returns the cards dealt
This is the test class
static void Main(string[] args)
{
// get the number of cards from the user - must be between 1 and 52
int cardsDealt = -1;
do
{
Console.Write("Enter number of cards to get (1-52): ");
String dealStr = Console.ReadLine();
Boolean parsed = int.TryParse(dealStr, out cardsDealt);
} while (cardsDealt < 1 || cardsDealt > 52);
// create a Deck object
Deck cardDeck = new Deck();
// Call the deal method
String cards = cardDeck.deal(cardsDealt);
// List the result
Console.WriteLine("\nCards dealt:\n" + cards);
In your Card class you have the variables value and suit marked as static.
private static int value;
private static int suit;
Because these two variables are static, the reference to these variables will be maintained across instances of the Card objects. What this means is that every time you create a new Card object you are inadvertently updating all the other Card objects value and suit variables with the same value. So now whenever you get an instance of a Card it will be the same card as all other instances (the last Card that was created).
Remove the static keyword from these declarations and you should be ok.
Also I would suggest reading up on static to more familiarize yourself with its usage: Static keyword in c#
Your code is very close to being correct. You seem to have a misunderstanding of when to use static or not.
If you need a variable that is shared amongst all instances of a class, then use static. But if you need per instance values, then don't.
There are no variables in your code that should be static.
Also, just to help you with your code, you don't need to define all of your variables at the class-level. A lot can (and should) be declared within each method.
Here's the refactored version of your code so that you can see what should be done.
void Main()
{
// get the number of cards from the user - must be between 1 and 52
int cardsDealt = -1;
while (cardsDealt < 1 || cardsDealt > 52)
{
Console.Write("Enter number of cards to get (1-52): ");
String dealStr = Console.ReadLine();
Boolean parsed = int.TryParse(dealStr, out cardsDealt);
}
// create a Deck object
Deck cardDeck = new Deck();
// Call the deal method
String cards = cardDeck.deal(cardsDealt);
// List the result
Console.WriteLine("\nCards dealt:\n" + cards);
}
public class Card
{
private int value;
private int suit;
public Card(int ranvalue, int ransuit) //constructor that sets value and suit
{
value = ranvalue;
suit = ransuit;
}
public override string ToString()
{
string cdvalue = null;
switch (value) //switch statement for card value
{
case 1:
cdvalue = "ace";
break;
case 2:
cdvalue = "two";
break;
case 3:
cdvalue = "three";
break;
case 4:
cdvalue = "four";
break;
case 5:
cdvalue = "five";
break;
case 6:
cdvalue = "six";
break;
case 7:
cdvalue = "seven";
break;
case 8:
cdvalue = "eight";
break;
case 9:
cdvalue = "nine";
break;
case 10:
cdvalue = "ten";
break;
case 11:
cdvalue = "jack";
break;
case 12:
cdvalue = "queen";
break;
case 13:
cdvalue = "king";
break;
}
string cdsuit = null;
switch (suit) // switch for card suit
{
case 1:
cdsuit = "Hearts ";
break;
case 2:
cdsuit = "Spades ";
break;
case 3:
cdsuit = "Diamonds ";
break;
case 4:
cdsuit = "Clubs ";
break;
}
string card = cdvalue + " of " + cdsuit;
return card;// returns a string in the form of "value of suit"`
}
}
public class Deck
{
private Random rng = new Random(); //Random object
private Card[] deck;
public Deck()
{
deck = new Card[52];//creates array of 52 elements
int l = 0;
for (int i = 1; i <= 13; i++)//loops to create cards
{
for (int j = 1; j <= 4; j++)
{
deck[l++] = new Card(i, j); // populates the array with all 52 cards
}
}
}
public string deal(int number)//parameter received from user
{
string[] cards = new string[number];//creates an array to contain dealt card objects
for (int num = 0; num < number; num++) // determines the amount of cards to be dealt
{
int Rndm = rng.Next(deck.Length);
cards[num] = deck[Rndm].ToString();//fills the card array with randomly dealt cards from the deck
}
string dealt = string.Join(" ", cards); // turns the card array into a single string of the cards dealt
return dealt;//returns the cards dealt
}
}
The only other concern with this is that your dealing code produces duplicate cards. You may need to do something about that.
If I were coding this, this is how I would do it:
public class Card
{
private int value;
private int suit;
public Card(int ranvalue, int ransuit)
{
value = ranvalue;
suit = ransuit;
}
public override string ToString()
{
var values = new []
{
"ace", "two", "three", "four", "five", "six", "seven",
"eight", "nine", "ten", "jack", "queen", "king"
};
var suits = new []
{
"Hearts", "Spades", "Diamonds", "Clubs"
};
return String.Format("{0} of {1}", values[value - 1], suits[suit - 1]);
}
}
public class Deck
{
private Random rng = new Random();
private Card[] deck;
public Deck()
{
deck =
(
from value in Enumerable.Range(1, 13)
from suit in Enumerable.Range(1, 4)
select new Card(value, suit)
).ToArray();
}
public string deal(int number)
{
string dealt = string.Join(" ", deck.OrderBy(x => rng.Next()).Take(number));
return dealt;
}
}
This fixes the duplicate card issue.

C#, how to make list<int> and functional if statements [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am a novice C# user, and I am experimenting with lists in Csharp's console application. This list contains 10 numbers, and the order of these numbers are randomized. What I want to do is to make specific text for a specific number which if statements will handle.
For example: If number == 0, the text "Hello" will show up. Or if the number == 3, the text "Goodbye" will show up.
I tried a few things but I got problems like repeated text: http://i.imgur.com/8sCbeLn.jpg?1
Random r = new Random();
int tempValue;
List<int> number = new List<int>();
number.Add(0);
number.Add(1);
number.Add(2);
number.Add(3);
number.Add(4);
number.Add(5);
number.Add(6);
number.Add(7);
number.Add(8);
number.Add(9);
for (int i = 0; i < 10; i++)
{
tempValue = r.Next(0, number.Count);
Console.WriteLine(number[tempValue]);
number.RemoveAt(tempValue);
Console.ReadLine();
}
Please help me getting on the right track.
You can for example use a switch to select strings from a value.
If you get repeated values, I suspect that you used tempValue to select the string, you have to use number[tempValue]:
string text = null;
switch (number[tempValue]) {
case 0: text = "Hello"; break;
case 1: text = "How do you do"; break;
case 2: text = "Howdie"; break;
case 3: text = "Goodbye"; break;
case 4: text = "Bye"; break;
case 5: text = "Hello again"; break;
case 6: text = "Good day"; break;
case 7: text = "Have fun"; break;
case 8: text = "Greatings"; break;
case 9: text = "Goodbye again"; break;
}
Why not add 10 random numbers to a list and then loop through the list, and print using you if statements
Random r = new Random();
List<int> nums= new List<int>();
int numForList = r.Next(0,10);
bool numInList = true;
//add 10 random numbers to a list
for(int i=0;i<10;i++)
{
do
{
if(!nums.Contains(numForList))
{
numInList = false;
nums.Add(numForList);
}
else
{
numForList = r.Next(0,10);
}
} while (numInList == true);
numInList = true;
}
foreach(var num in nums)
{
switch (num)
{
case 0: Console.WriteLine("Hello"); break;
case 1: Console.WriteLine("How do you do"); break;
... //Add more cases here for each possible random number
}
}

not recognizing a declared variables in c#.net

The last but 3rd line of code is not recognizing variables that I have declared and filled with strings.
static void Main(string[] args)
{
string inputNumber = "1979";
string input1 = inputNumber.Substring(0, 1);
string input2 = inputNumber.Substring(1, 1);
string input3 = inputNumber.Substring(2, 1);
string input4 = inputNumber.Substring(3, 1);
int intInput1;
int intInput2;
int intInput3;
int intInput4;
intInput1 = Convert.ToInt32(input1);
intInput2 = Convert.ToInt32(input2);
intInput3 = Convert.ToInt32(input3);
intInput4 = Convert.ToInt32(input4);
string stringOutput1;
string stringOutput2;
string stringOutput3;
string stringOutput4;
// 1000 Input.
switch (intInput1)
{
case 1:
stringOutput1 = "M";
break;
default:
break;
}
//100 Input
switch (intInput2)
{
case 9:
stringOutput2 = "CM";
break;
default:
break;
}
//10 Input
switch (intInput3)
{
case 7:
stringOutput3 = "LXX";
break;
default:
break;
}
//1 Input
switch (intInput4)
{
case 9:
stringOutput4 = "IX";
break;
default:
break;
}
//Use of unassigned local variable error is showing for 'stringOutput1', 'stringOutput2', 'stringOutput3' and 'stringOutput4'
Console.WriteLine("{0} is {1}{2}{3}{4} in Roman Numerals",inputNumber, stringOutput1, stringOutput2, stringOutput3, stringOutput4);
Console.CursorVisible = false;
Console.ReadKey();
}
P.S. I know that the variables are being filled by commenting out
Console.WriteLine("{0} is {1}{2}{3}{4} in Roman Numerals",inputNumber, stringOutput1, stringOutput2, stringOutput3, stringOutput4);
and using break point and stepping over the code.
This is because your variables might not have been assigned anything yet. Variables must be guaranteed to have been assigned something before they can be used. As a simple fix, you can use declarations like this:
string stringOutput1 = "";
Try assigning nulls to the declarations
string stringOutput1 = null;
string stringOutput2 = null;
string stringOutput3 = null;
string stringOutput4 = null;
You have to initialize your variables, do it like this.
string stringOutput1 , stringOutput1, stringOutput3, stringOutput4 = string.Empty;
and you can also assign default values per variable.
string stringOutput1 = "foo1", stringOutput1 = "foo2"
, stringOutput3= "foo3", stringOutput4 = "foo4";

Prompting user to enter numbers into Array and exiting a program when condition is met

I am hoping this is something small and not a big issue. I am coding a program (Self teaching via book) which will ask for an operator, then an array of numbers then apply the operator to get a result. The program isn't prompting me for numbers and assumes an empty array. I think I understand what is going wrong, just not how to recode it so that it will ask me to enter the numbers into the array.
The other thing I am curious about is can I force the program to exit in the first switch of the class code if the Operator is not valid? I found Application.Exit() but that only seems to work for WinForms. Is there a C# code equivalent?
My Main method is as follows:
static void Main(string[] args)
{
MathMethodClass mathMethods = new MathMethodClass();
int[] intArray = new int[] { };
Console.Write("Choose an Operator + or *: ");
string whichOp = Console.ReadLine();
Console.WriteLine("Thank you. You chose {0}.", mathMethods.OperatorName(whichOp));
Console.WriteLine("Please enter an array of numbers: ");
for (int i=0;i<intArray.Length;i++)
{
intArray[i] = Int32.Parse(Console.ReadLine());
}
Console.WriteLine("Thank you. You entered the numbers {0}", intArray);
Console.WriteLine("The answer is: {0}.", mathMethods.MathMethod(whichOp, intArray));
Console.ReadLine();
}
And my Class is as follows:
class MathMethodClass
{
public string OperatorName(string whichOp)
{
switch (whichOp)
{
case "+":
whichOp = "addition";
break;
case "*":
whichOp = "multiplication";
break;
default:
Console.WriteLine("Error: Unknown Operator. Exiting ...");
Console.ReadLine();
break;
}
return whichOp;
}
public int MathMethod(string whichOp, params int[] theNums)
{
int theAnswer = 0;
switch (whichOp)
{
case "+":
for (int ct = 0; ct < theNums.Length; ct++)
{
theAnswer += theNums[ct];
}
break;
case "*":
for (int ct = 0; ct < theNums.Length; ct++)
{
theAnswer *= theNums[ct];
}
break;
default:
Console.WriteLine("Error. Something went wrong in the MathMethod. Exiting ...");
Console.ReadLine();
break;
}
return theAnswer;
}
}
Any assistance in letting me know where I am going wrong would be great.
Thanks.
You need to specify an array size, you are currently creating an empty array. Define it with some size like:
int[] intArray = new int[5];
Or the better approach would be to ask the user for the array size. Add the following code before your for loop
Console.Write("Enter Number of elements in Array: ");
arraySize = int.Parse(Console.ReadLine());
intArray = new int[arraySize];
Console.WriteLine("Please enter an array of numbers: ");
for (int i = 0; i < intArray.Length; i++)
{
intArray[i] = Int32.Parse(Console.ReadLine());
}
In your original code you are specifying the array of 0 size with int[] intArray = new int[] { }; and later in your loop, you are checking it against the length and thus not getting into the loop. That is why you are having problem. Other than that code seems to be fine. A much better approach would be to use int.TryParse instead of int.Parse, so that you can check for valid int input.
I think your proble is here
int[] intArray = new int[] { };
You are specifying an empty array, with lenght of 0
thus this statement
for (int i=0;i<intArray.Length;i++)
will never enter the loop.

Categories

Resources