variable doesn't increment/decrement on my code - c#

if (getchar == '+') {
answer = getnum1+getnum2; // if the random operation is add, it will add
addtemp++; // <---- disregard this
if (answer == getanswer) // the answer from my textbox which is
{ // user-input it is stored on "getanswer"
correct++; // it is compared if its correct or wrong
addcomp++;
}
else { wrong++; }
}
else if (getchar == '-') {
subtemp++;
answer = nextValue - nextValue1;
if (answer == getanswer) {
correct++;
subcomp++;
}
else { wrong++; }
}
else if (getchar == '*') {
multemp++;
answer = nextValue * nextValue1;
if (answer == getanswer) {
correct++;
mulcomp++;
}
else { wrong++; }
}
else if (getchar == '/') {
divtemp++;
answer = nextValue / nextValue1;
if (answer == getanswer) {
correct++;
divcomp++;
}
else { wrong++; }
}
else if (getchar == '%') {
modtemp++;
answer = nextValue % nextValue1;
if (answer == getanswer) {
correct++;
modcomp++;
}
else { wrong++; }
}
C# programming HELP! Now whenever i press the button "SCORES" it is a MessageBox.Show(correct or wrong) , the values are wrong. it sometimes increment corrected but just once or twice.Is there something wrong with my code?
///////////////////////////////////////////////////////////
ENTIRE CODE for #boncodigo
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace A1_ALS_Noroña
{
public partial class Form1 : Form
{
int minV=0, maxV=0,ques=0,tempques=1;
int addtemp, subtemp, multemp, divtemp, modtemp;
int addcomp, subcomp, mulcomp, divcomp, modcomp;
int answer,getanswer;
int getnum1, getnum2;
char getchar;
char[] select = new char[5];
int count=0;
int correct, wrong;
public Form1()
{
InitializeComponent();
}
private void bttnstart_Click(object sender, EventArgs e)
{
bttnanswer.Enabled = true;
grpbox1.Enabled = false;
bttnanswer.Enabled = true;
lblnum1.Visible = true;
lblnum2.Visible = true;
lbloperator.Visible = true;
bttnstop.Enabled = true;
bttnscore.Enabled = true;
bttnstart.Enabled = false;
Random random = new Random();
int nextValue = random.Next(minV, maxV);
int nextValue1 = random.Next(minV, maxV);
lblnum1.Text = nextValue.ToString();
lblnum2.Text = nextValue1.ToString();
var rand = new Random();
char num = select[rand.Next(count)];
lbloperator.Text = Convert.ToString(num);
}
private void txtboxmin_TextChanged(object sender, EventArgs e)
{
minV = Convert.ToInt32(txtboxmin.Text);
}
private void txtbxmax_TextChanged(object sender, EventArgs e)
{
maxV = Convert.ToInt32(txtbxmax.Text);
}
private void bttnexit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void bttnstop_Click(object sender, EventArgs e)
{
MessageBox.Show("APPLICATION STOP! The application will restart.");
Application.Restart();
}
private void bttnanswer_Click(object sender, EventArgs e)
{
tempques++;
Random random = new Random();
int nextValue = random.Next(minV,maxV);
int nextValue1 = random.Next(minV, maxV);
lblnum1.Text = nextValue.ToString();
var rand = new Random();
char num = select[rand.Next(count)];
lbloperator.Text = Convert.ToString(num);
lblnum2.Text = nextValue1.ToString();
getnum1 = Convert.ToInt32(lblnum1.Text);
getnum2 = Convert.ToInt32(lblnum2.Text);
getanswer = Convert.ToInt32(txtbxans.Text);
getchar = Convert.ToChar(lbloperator.Text);
if (getchar == '+')
{
answer = getnum1 + getnum2;
addtemp++;
if (answer == getanswer)
{
correct++;
addcomp++;
}
else
{
wrong++;
}
}
else if (getchar == '-')
{
subtemp++;
answer = nextValue - nextValue1;
if (answer == getanswer)
{
correct++;
subcomp++;
}
else
{
wrong++;
}
}
else if (getchar == '*')
{
multemp++;
answer = nextValue * nextValue1;
if (answer == getanswer)
{
correct++;
mulcomp++;
}
else
{
wrong++;
}
}
else if (getchar == '/')
{
divtemp++;
answer = nextValue / nextValue1;
if (answer == getanswer)
{
correct++;
divcomp++;
}
else
{
wrong++;
}
}
else if (getchar == '%')
{
modtemp++;
answer = nextValue % nextValue1;
if (answer == getanswer)
{
correct++;
modcomp++;
}
else
{
wrong++;
}
}
}
private void txtbxques_TextChanged(object sender, EventArgs e)
{
ques = Convert.ToInt32(txtbxques.Text);
}
private void chkbxtimer_CheckedChanged(object sender, EventArgs e)
{
rdoeasy.Enabled = true;
rdomed.Enabled = true;
rdohard.Enabled = true;
}
private void chkboxAdd_CheckedChanged(object sender, EventArgs e)
{
if (chkboxAdd.Checked == true)
{
select[count] = '+';
count++;
}
else if (chkboxAdd.Checked == false)
{
Array.Clear(select, 0, select.Length);
count--;
}
}
private void chkboxSub_CheckedChanged(object sender, EventArgs e)
{
if (chkboxSub.Checked == true)
{
select[count] = '-';
count++;
}
else if (chkboxSub.Checked == false)
{
Array.Clear(select, 0, select.Length);
count--;
}
}
private void chkboxMul_CheckedChanged(object sender, EventArgs e)
{
if (chkboxMul.Checked == true)
{
select[count] = '*';
count++;
}
else if (chkboxMul.Checked == false)
{
Array.Clear(select, 0, select.Length);
count--;
}
}
private void chkboxDiv_CheckedChanged(object sender, EventArgs e)
{
if (chkboxDiv.Checked == true)
{
select[count] = '/';
count++;
}
else if (chkboxDiv.Checked == false)
{
Array.Clear(select, 0, select.Length);
count--;
}
}
private void chkboxMod_CheckedChanged(object sender, EventArgs e)
{
if (chkboxMod.Checked == true)
{
select[count] = '%';
count++;
}
else if (chkboxMod.Checked == false)
{
Array.Clear(select, 0, select.Length);
count--;
}
}
private void bttnscore_Click(object sender, EventArgs e)
{
MessageBox.Show("Correct Answer"+correct);
}
}
}

One thing in advance: I don't know where your bug is. Here's just a couple of tips that I think it would make sense if you think about them, in order to avoid similar bugs in the future:
If I had to review this code, my major issue would be with the amount of repeating code, where very similar multi-line long patterns are copied over and over. I think in the whole code you don't call any method, but implement stuff right away in the event-handlers, thereby repeating yourself and multiplying the potential for bugs. Let's look at this code:
if (chkboxSub.Checked == true)
{
select[count] = '-';
count++;
}
else if (chkboxSub.Checked == false)
{
Array.Clear(select, 0, select.Length);
count--;
}
apart from the bug with count when you have added several operators to the select-array, this code repeats several times. Let's extract the code into a method and make the bits that change parameterizable:
void AddOrRemoveOperator(bool isChecked, char operatorChar) {
if (isChecked) {
select[count] = operatorChar;
count++;
}
else {
Array.Clear(select, 0, select.Length);
count--;
}
}
Now you can call that method many times, e.g. like:
AddOrRemoveOperator(chkboxSub.Checked, '-');
Next point would be lack of .NET Base Class Library knowledge (BCL). E.g., wouldn't it be easier to use a List<T> instead of an array?
The above method becomes:
void AddOrRemoveOperator(bool isChecked, char operatorChar) {
if (isChecked) {
select.Add(operatorChar);
}
else {
select.Clear();
}
}
An Observation: All operators except the add one use the values nextValue, nextValue1 while the add one uses getnum1 and 2. Is that intended?
Short of extracting the code blocks in bttnanswer_Click into their own class, you can also extract the repeating code into a method:
void PerformComparison(Func<int> answerProvider,
ref int operatorCount,
ref int operatorSpecificCorrectCount)
{
var answer = answerProvider();
operatorCount++;
if (answer == getanswer) {
correct++;
operatorSpecificCorrectCount++;
}
else {
wrong++;
}
}
That code would still drive me mad (because the class you have programmed lacks cohesion), but we have fought code duplication. Now you can call the method e.g. like that:
if (getchar == '+')
{
PerformComparison(()=>getnum1 + getnum2, ref addtemp, ref addcomp);
}
There are many techniques to morph code into forms that are more easily testable and maintainable (refactoring), we have only used extract method so far. For more techniques the book Refactoring: Improving the Design of Existing Code is still highly recommendable.

It might be a float precision issue (maybe your user is entering 3 and the program calculates 2.9999999). Debug your code and identify one case when it is not adding correctly.

Related

How to enable GetAsyncKeyState using char?

Good morning, I would like to "enable" the functions from GetAsyncKeyState from a button that is a char
ps. I am making a AutoClicker for game. (sorry for bad English xd)
example:
private void siticoneButton5_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 27)
{
siticoneButton5.Text = "Zbinduj";
keyRegisteringBool = false;
}
if (keyRegisteringBool)
{
siticoneButton5.Text = "Bind: " + e.KeyChar.ToString();
char bind = e.KeyChar;
keyRegisteringBool = false;
}
}
//here i have a void with a function
int min = Convert.ToInt32(materialSingleLineTextField1.Text);
int max = Convert.ToInt32(materialSingleLineTextField2.Text);
Random rand = new Random();
int cps = rand.Next(min, max);
while (true)
{
if (GetAsyncKeyState() < 0) //here I want to start this by key down a char.
{
bot.Mouse.LeftButtonClick();
Thread.Sleep(1000 / cps);
}
}
```
Thanks in advace

Ensure first and last characters of text box are numbers c#

Im currently creating a windows form that must only allow a password through when it matches certain criteria. Im close to finishing however im a bit stuck with one element. "the first and last characters of the password HAVE to be numbers".
looking at my current code how would i go about this because i have ZERO idea. so baby steps and patience would be appreciated.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;
namespace password_test
{
public partial class Form1 : Form
{
bool Finished = false;
private bool TestPassword(string passwordText, int minimumLength = 5, int maximumLength = 12, int minimumNumbers = 1, int minimumLetters = 1)
{
int letters = 0;
int digits = 0;
int minLetters = 0;
if (passwordText.Length < minimumLength)
{
MessageBox.Show("You must have at least " + minimumLength + " characters in your password.");
return false;
}
if (passwordText.Length > maximumLength)
{
MessageBox.Show("You must have no more than " + maximumLength + " characters in your password.");
return false;
}
foreach (var ch in passwordText)
{
if (char.IsLetter(ch)) letters++;
if (char.IsDigit(ch)) digits++;
if (ch > 96 && ch < 123)
{
minLetters++;
}
}
if (digits < minimumNumbers)
{
MessageBox.Show("You must have at least " + minimumNumbers + " numbers in your password.");
return false;
}
if (minLetters < minimumLetters)
{
MessageBox.Show("You must have at least " + minimumLetters + " letter in your password");
return false;
}
Finished = true;
return true;
}
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void butConfirm_Click(object sender, EventArgs e)
{
if (txtPassword.Text == txtRetypePassword.Text)
{
bool temp = TestPassword(txtPassword.Text, 10, 100, 1, 1);
if (Finished == true)
{
MessageBox.Show("Password Accepted");
Application.Exit();
//this.Hide();
//Form2 f2 = new Form2();
//f2.ShowDialog();
}
}
else
{
MessageBox.Show("Please ensure the passwords you have typed match");
return;
}
}
private void txtPassword_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsLetterOrDigit(e.KeyChar))
{
e.Handled = true;
}
else
{
return;
}
}
private void txtRetypePassword_TextChanged(object sender, EventArgs e)
{
}
}
}
Before Finished = true; you can simply do your check:
if (!char.IsDigit(passwordText[0]) || !char.IsDigit(passwordText[passwordText.Length - 1]))
{
MessageBox.Show("The first and last characters of the password have to be numbers");
return false;
}
Finished = true;
You should also enforce a minimum length in your method.
Or you can use Regex Test Pattern
// ^\d = start with digit
// \d$ end with digit
// .{3,10} including start and ending, min 5 max 12
if (!Regex.IsMatch(str, #"\d.{3,10}\d$")
{
// Invalid
}
Use \D to reverse.

C# BlackJack - same card dealt to player & cpu? [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 8 years ago.
Improve this question
i'm working on a little black jack game for no apparent reason, and I've run into an issue and i can't figure out where i'm going wrong, the only thing i can imagine is that the 'new card' method is being called twice, too quickly...
The problem is that it's giving the same card to both players :/
Here is my code
Thank you! :)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BlackJack_Reworked
{
public partial class BlackJack : Form
{
public BlackJack()
{
InitializeComponent();
}
class myVars
{
public static int cardsDrawn = 0;
public static int playerX = 230;
public static int playerY = 160;
public static int cpuX = 230;
public static int cpuY = 60;
public static int playerCardValue = 0;
public static int cpuCardValue = 0;
}
private PictureBox[] card = new PictureBox[100];
private void makeCard(string pickedCard, int x)
{
card[myVars.cardsDrawn] = new PictureBox();
if (x == 0)
{
card[myVars.cardsDrawn].Location = new Point(myVars.playerX, myVars.playerY);
myVars.playerX += 15;
}
if (x == 1)
{
card[myVars.cardsDrawn].Location = new Point(myVars.cpuX, myVars.cpuY);
myVars.cpuX += 15;
}
card[myVars.cardsDrawn].Image = (Image)Properties.Resources.ResourceManager.GetObject(pickedCard);
card[myVars.cardsDrawn].Size = new Size(72, 96);
card[myVars.cardsDrawn].Parent = this;
card[myVars.cardsDrawn].BringToFront();
card[myVars.cardsDrawn].Update();
myVars.cardsDrawn++;
checkScores(false);
}
private void newCard(int x)
{
Random cardPicker = new Random();
int cardChoice = cardPicker.Next(1, 13);
int houseChoice = cardPicker.Next(1, 4);
string house = null;
switch (houseChoice)
{
case 1:
house = "Hearts";
break;
case 2:
house = "Diamonds";
break;
case 3:
house = "Spades";
break;
case 4:
house = "Clubs";
break;
}
if (x == 0)
{
makeCard(house + Convert.ToString(cardChoice), 0);
myVars.playerCardValue += cardChoice;
}
if (x == 1)
{
makeCard(house + Convert.ToString(cardChoice), 1);
myVars.cpuCardValue += cardChoice;
}
}
private bool feelingLucky()
{
Random Dice = new Random();
if (myVars.cpuCardValue >= 20) { return false; }
if (myVars.cpuCardValue <= 16) { return true; }
if (myVars.cpuCardValue >= 17 && myVars.cpuCardValue <= 18) if (Dice.Next(1, 5) == 1) { return true; }
if (myVars.cpuCardValue == 19) if (Dice.Next(1, 10) == 1) { return true; }
return false;
}
private void updateHandValues()
{
lblPlayerHand.Text = "Player: " + myVars.playerCardValue.ToString();
lblCPUhand.Text = "CPU: " + myVars.cpuCardValue.ToString();
}
private void checkScores(bool stand)
{
if (stand == true)
{
if (myVars.playerCardValue <= 21 && myVars.playerCardValue > myVars.cpuCardValue)
{
MessageBox.Show("Win!");
btnNewGame.Visible = true;
}
else if (myVars.cpuCardValue <= 21 && myVars.cpuCardValue > myVars.playerCardValue)
{
btnNewGame.Visible = true;
MessageBox.Show("Lose!");
}
}
else
{
if (myVars.playerCardValue > 21)
{
MessageBox.Show("Bust!");
btnNewGame.Visible = true;
}
if (myVars.cpuCardValue > 21)
{
MessageBox.Show("Win!");
btnNewGame.Visible = true;
}
}
}
private void newGame()
{
for(int x = 0; x < myVars.cardsDrawn; x++) { card[x].Dispose(); }
myVars.cpuCardValue = 0;
myVars.playerCardValue = 0;
myVars.cpuX = 230;
myVars.playerX = 230;
btnNewGame.Visible = false;
newCard(0); newCard(1);
}
private void btnNewGame_Click(object sender, EventArgs e)
{
newGame();
}
private void btnHit_Click(object sender, EventArgs e)
{
newCard(0); newCard(1);
updateHandValues();
}
private void btnStand_Click(object sender, EventArgs e)
{
if (feelingLucky() == true) newCard(1);
else checkScores(true);
}
}
}
EDIT Here's the code to my new and working version with help from these nice guys below, just in case someone finds it useful, thanks everyone!
Here are the card picture files you'll need to add to your project's resources for this code to work.
I know my logic probably isn't great, but i feel like I've learnt from this little project, hopefully someone else might too, now, time to conjure up something new.. thanks stackoverflow.
Playing Card Pictures Download
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Text.RegularExpressions;
namespace BlackJack_Reworked
{
public partial class BlackJack : Form
{
public BlackJack()
{
InitializeComponent();
}
private PictureBox[] Card = new PictureBox[52];
static List<string> Deck = new List<string>();
class myVars
{
public static int playerX = 230;
public static int cpuX = 230;
public static int playerCardValue = 0;
public static int cpuCardValue = 0;
public static int cardsDrawn = 0;
}
private void newDeck()
{
Deck.Clear();
for (int x = 0; x < myVars.cardsDrawn; x++)
{
Card[x].Dispose();
}
for (int x = 0; x < 52; x++)
{
int cardSuite = (x / 13) + 1;
int faceValue = (x % 13) + 1;
string Suite = null;
switch (cardSuite)
{
case 1:
Suite = "Hearts";
break;
case 2:
Suite = "Diamonds";
break;
case 3:
Suite = "Spades";
break;
case 4:
Suite = "Clubs";
break;
}
Deck.Add(Suite + Convert.ToString(faceValue));
}
Extensions.Shuffle(Deck);
myVars.cardsDrawn = myVars.cpuCardValue = myVars.playerCardValue = 0;
myVars.cpuX = myVars.playerX = 230;
}
private void handCard(string recipient)
{
Random Random = new Random(); Extensions.Shuffle(Deck);
string pickedCard = Deck[Random.Next(Deck.Count)];
int cardvalue = Convert.ToInt32(Regex.Replace(pickedCard, "[^0-9]", ""));
Card[myVars.cardsDrawn] = new PictureBox();
if (recipient == "player") {
Card[myVars.cardsDrawn].Location = new Point(myVars.playerX, 160); myVars.playerX += 15;
myVars.playerCardValue += cardvalue;
}
if (recipient == "cpu") {
Card[myVars.cardsDrawn].Location = new Point(myVars.cpuX, 60); myVars.cpuX += 15;
myVars.cpuCardValue += cardvalue;
}
Card[myVars.cardsDrawn].Image = (Image)Properties.Resources.ResourceManager.GetObject(pickedCard);
Card[myVars.cardsDrawn].Size = new Size(72, 96);
Card[myVars.cardsDrawn].Parent = this;
Card[myVars.cardsDrawn].BringToFront();
Card[myVars.cardsDrawn].Update();
Deck.Remove(pickedCard); myVars.cardsDrawn++; updateHandValues();
}
private void updateHandValues()
{
lblPlayerHand.Text = "Player: " + myVars.playerCardValue.ToString();
lblCPUhand.Text = "CPU: " + myVars.cpuCardValue.ToString();
}
private void newGame()
{
lblBlackJack.Text = "♠ Blackjack ♥";
btnNewGame.Visible = false;
newDeck(); handCard("player"); handCard("cpu");
}
private void checkCards()
{
if (playerWins() == true)
{
lblBlackJack.Text = "♠ You Win! ♥";
btnNewGame.Visible = true;
}
else if (playerWins() == false)
{
lblBlackJack.Text = "♠ Dealer Wins! ♥";
btnNewGame.Visible = true;
}
}
private void tieBreak()
{
if (myVars.cpuCardValue == myVars.playerCardValue && myVars.cpuCardValue >= 17)
{
lblBlackJack.Text = "♠ Tie! ♥";
btnNewGame.Visible = true;
}
else { checkCards(); }
}
private bool? playerWins()
{
if(myVars.cpuCardValue == 21 || myVars.playerCardValue > 21) { return false; }
if(myVars.playerCardValue == 21 || myVars.cpuCardValue > 21) { return true; }
else { return null; }
}
private bool cpuShouldPlay(bool stand)
{
Random Dice = new Random();
if (stand == false)
{
if (myVars.cpuCardValue <= 15) { return true; }
if (myVars.cpuCardValue >= 20 && myVars.cpuCardValue <= 21 && myVars.cpuCardValue > myVars.playerCardValue) { return false; }
if (myVars.cpuCardValue == 19 && myVars.cpuCardValue < myVars.playerCardValue) { return true; } else { return false; }
}
else
{
if(myVars.cpuCardValue < myVars.playerCardValue)
{
return true;
}
else { return false; }
}
}
private void btnNewGame_Click(object sender, EventArgs e)
{
newGame();
}
private void btnHit_Click(object sender, EventArgs e)
{
handCard("player"); if(cpuShouldPlay(false) == true) handCard("cpu"); checkCards();
}
private void btnStand_Click(object sender, EventArgs e)
{
if (cpuShouldPlay(true) == true) handCard("cpu"); tieBreak();
}
}
public static class Extensions
{
public static void Shuffle<T>(this IList<T> list)
{
Random rng = new Random();
int n = list.Count;
while (n > 1)
{
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}
}
If you're playing from single deck rules, you must use a 'bag' or 'no replacement' model of random value source. Initially , fill the bag with all 52 possible cards. Then each iteration, pick one card at random from what remains in the bag, removing it from the bag. When the bag is empty, refill it.
Do note that when picking a random card from a bag that has n remaining items, your random value, being the index of the item in the bag to take, must be no larger than n-1 (assuming indicies run from 0 to n-1).
However, there are models of blackjack where multiple decks are shuffled together; many casinos play like this. From Wikipedia Blackjack, rules of play at casinos:
At a casino blackjack table, the dealer faces five to seven playing positions from behind a semicircular table. Between one and eight standard 52-card decks are shuffled together.
In this above model, it is certainly possible for the same card to be dealt twice in a row; however, depending on how many decks are shuffled together, this can happen only a limited number of times.
If I understand your code correctly, you currently model a blackjack shoe that has an infinite number of decks shuffled together.
Random.Next method generates random number from current time stamp and previously generated number (known as 'seed'). As you are create new object of Random everytime, it initializes with same seed. In your case, timestamp and seed doesn't change to 'Next' method of Random.
If you use single object of Random for all your operation, seed will change for each call of 'next'.
Second: You need to keep track of which cards are already drawn, so I've create a shoe list. I will remove the cards which are already used, just like real table.
NOTE: create a new shoe, when your number of cards are let's say 20.
List<string> aShoe = new List<string>(); //shoe contains 4 to 8 decks. Depending upon blackjack version.
int numberOfDeckPerShoe = 4;
private void CreateNewDeck()
{
for(int i =0;i <numberOfDeckPerShoe;i++)
for(int j=0;j<52;j++)
{
int cardFace = (j%13)+1;
int cardSuite = (j/13) + 1;
string Suite = null;
switch (cardSuite)
{
case 1:
Suite = "Hearts";
break;
case 2:
Suite = "Diamonds";
break;
case 3:
Suite = "Spades";
break;
case 4:
Suite = "Clubs";
break;
}
aShoe.add(Suite + Convert.ToString(cardFace));
}
}
Random cardPicker = new Random(); //This is change
private void newCard(int x)
{
int cardChoice = 0;
int houseChoice = 0;
string cardDrawn = "";
int cardToDraow = cardPicker.Next(0,aShoe.length);
cardDrawn = card aShoe[cardToDraow];
card.removeAt(cardToDraow);
if (x == 0)
{
makeCard(cardDrawn, 0);
myVars.playerCardValue += cardChoice;
}
if (x == 1)
{
makeCard(cardDrawn, 1);
myVars.cpuCardValue += cardChoice;
}
}
You are declaring a new Random() within the new card method.
If the method is being called twice, and very quickly, the seed's that are automatically generated (Based on time I believe) will be so close that they will generate pretty much the same number.
The best thing to do would be to create your instance of random outside of the method, and pass the random in each time, that way you will not get the same number each call.

How to call GetPrice method by passing converted value into txtQty?

I'm not sure if I'm writing the call correctly. 'intQty' says doesn't exist in current context. So how would I go about fixing that?
txtQty.Text = getPrice(intQty);
txtPrice.Text = decPrice.ToString("C2");
//Also to compute the order total it has to be written as
Order Total = (Order Qty * Price) * (1 + Tax Rate)
what I have: decTotal = (intQty * decPrice) * (1 + fltTaxRate);
so would I replace the that with values I've already declared?
EDIT: 'intQty' is declared right under the btnCalculate_Click as 'int intQty;'
there's data validation underneath and some methods as well.
FULL CODE:
string sCboStates;
int intQty;
string sWrapperSample;
// data validation
try
{
intQty = Convert.ToInt32(txtQty.Text);
}
catch
{
MessageBox.Show("Contents are not numeric.",
"Quantity",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
txtQty.Focus();
return;
}
try
{
sWrapperSample = Convert.ToString(txtWrapperSample.Text);
}
catch
{
MessageBox.Show("Content's empty.",
"Wrapper Sample",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
txtLine1.Focus();
return;
}
try
{
sCboStates = Convert.ToString(cboStates.Text);
}
catch
{
MessageBox.Show("Content's empty.",
"States",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
cboStates.Focus();
return;
}
}
// Method 1
private decimal getPrice(int intQty)
{
decimal decPrice;
if (intQty <= 500)
{
decPrice = 1.25m;
}
else if (intQty >= 501 && intQty <= 1000)
{
decPrice = 1.05m;
}
else if (intQty >= 1001 && intQty <= 5000)
{
decPrice = .90m;
}
else if (intQty > 5001)
{
decPrice = .75m;
}
decPrice = Convert.ToDecimal(txtPrice.Text);
txtQty.Text = intQty.ToString();
return intQty;
}
//Method 2
private float getTaxRate(string sCboStates)
{
string sStates = "";
float fltTaxRate=0;
if (sStates == "CT")
{
fltTaxRate = 0.06f;
}
else if (sStates == "MA")
{
fltTaxRate =.0625f;
}
else if (sStates == "ME")
{
fltTaxRate = .085f;
}
else if (sStates == "NH")
{
fltTaxRate = .0f;
}
else if (sStates == "RI")
{
fltTaxRate = .07f;
}
else if (sStates == "VT")
{
fltTaxRate = .06f;
}
return fltTaxRate;
}
//Method 3
private void formatWrapperSample()
{
txtWrapperSample.Text = txtLine1.Text + " " +
Environment.NewLine +
txtLine2.Text + " " +
Environment.NewLine +
txtLine3.Text;
}
// Method 4
private Color GetColor(string sColorIn)
{
return Color.FromName(sColorIn);
//CALCULATIONS
decimal decTotal = 0;
//Call the price method by passing the numeric value and the text qty
txtQty.Text = getPrice(intQty);
txtPrice.Text = decPrice.ToString("C2");
// Compute the total
decTotal = (intQty * decPrice) * (1 + fltTaxRate);
txtTotal.Text = decTotal.ToString("C2");
}
private void cboWrapperColor_SelectedIndexChanged(object sender, EventArgs e)
{
//Label Color 'cboWrapperColor_Selected' is a typo
txtWrapperSample.BackColor = GetColor(cboLabelColor.Text);
}
private void cboFontColor_SelectedIndexChanged(object sender, EventArgs e)
{
txtWrapperSample.ForeColor = GetColor(cboFontColor.Text);
}
private void cboStates_SelectedIndexChanged(object sender, EventArgs e)
{
getTaxRate("P2");
}
private void btnClear_Click(object sender, EventArgs e)
{
txtLine1.Clear();
txtLine2.Clear();
txtLine3.Clear();
txtQty.Clear();
txtWrapperSample.Clear();
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
It looks like there is some code missing, is everything starting with //CALCULATIONS to the end of the code part of the GetColor() method?
At any rate, you're declaring and initializing intQty in your btnCalculate_Click event handler. This means that the rest of your program does not know about intQty (with the exception of GetPrice() since you're passing it in).
Declare intQty as a global variable at the top of your class and then set the correct value in btnCalculate_Click
That way when you go to do the calculations it will know about intQty
Also...
You are using exceptions to control program flow, which is generally considered bad practice.
Exceptions are for exceptional cases, because they are computationally expensive.
You should use Int32.TryParse() instead
txtQty.Text = getPrice(intQty);
For one your method returns Decimal - you can't assign it to String property. C# is stringly typed.

So the first if statement never triggers because it does not seem to read the negative number entered in the text box

private void button1_Click(object sender, EventArgs e)
{
double temp = double.Parse(textBox1.Text);
if (temp < 0)
{
label2.Text = "Freezing.";
}
if (temp > 40)
{
label2.Text = "Hot.";
}
else
{
label2.Text = "Moderate.";
}
}
Whenever converting user input, or any form of type String in to an object, I always like to use TryParse(...) as it provides you with better control if something isn't right.
double temp = 0.0d;
var converted = double.TryParse(textBox1.Text, out temp);
if (!converted) throw new Exception("Please enter a positive or negative temperature.");
if (temp < 0.0d)
{
// Freezing
}
else if (temp >= 0.0d && temp < 40.0d)
{
// Moderate
}
else if (temp >= 40.0d)
{
// Hot
}
The key is finding out what the value is being read in to temp. If its bringing in a negative number then I would recommend the code change below. What its really doing is if the 1st isnt true, then it checks the second, and finally it uses the third if neither are true.
private void button1_Click(object sender, EventArgs e)
{
double temp = double.Parse(textBox1.Text);
if (temp < 0)
{
label2.Text = "Freezing.";
}
else if (temp > 40)
{
label2.Text = "Hot.";
}
else
{
label2.Text = "Moderate.";
}
}

Categories