using radio buttons to do some basic maths - c#

i am making a program that will calculate how much someone needs to pay if they have had there vehicle parked. I am trying to use radio buttons to select the type of vehicle. when cars(radiobutton1) is selected the algorithm works but when trucks (radiobutton2)is selected it will not work. here is my code
// cars
if (radioButton1.Checked == true)
{
int hac = Convert.ToInt16(txthrs.Text);
int h1c = 5;
int h2c = 3;
if (txthrs.Text == "1") ;
money.Text = h1c.ToString();
if (hac < 1) ;
money.Text = (h1c + (hac - 1) * h2c).ToString();
// end of cars
// trucks
if (radioButton2.Checked == true)
{
int hat = Convert.ToInt16(txthrs.Text);
int h1t = 6;
decimal h2t = 3.5m;
if (txthrs.Text == "1") ;
money.Text = h1t.ToString();
if (hat < 1) ;
money.Text = (h1t + (hat - 1) * h2t).ToString();
}
}
}
}
}

when trucks (radiobutton2)is selected it will not work.
Firstly, you have some logical mistakes because if (hac < 1) ; and (hat < 1) ; doesn't do anything at all, it's just an expression on its own. With that in mind, i have updated your code to remove those logical errors.
Secondly, don't use == to compare strings, rather use Equals() method.
Thirdly, the radioButton2 condition is nested within the radioButton1 condition hence it causes the unexpected behaviour. You can solve it by separating them like this:
if (radioButton1.Checked == true)
{
int hac = Convert.ToInt16(txthrs.Text);
int h1c = 5;
int h2c = 3;
if (txthrs.Text.ToString().Equals("1"))
money.Text = h1c.ToString();
if (hac < 1)
money.Text = (h1c + (hac - 1) * h2c).ToString();
}
if (radioButton2.Checked == true)
{
int hat = Convert.ToInt16(txthrs.Text);
int h1t = 6;
decimal h2t = 3.5m;
if (txthrs.Text.ToString().Equals("1"))
money.Text = h1t.ToString();
if (hat < 1)
money.Text = (h1t + (hat - 1) * h2t).ToString();
}

You have nested your if statements, the second if statement will only execute if radio button one is checked. Move the second if block out of the first.

Related

Is there a way to do this "do while"?

I'm currently using Flexsim, which uses some kind of C#.
My problem is that I need to change port when 1000 items pass.
For example:
I have 2 processors but I can use one at a time.
Everytime 1000 items pass, I want to use the other processor.
Something like
double id = 1;
double count = count +1;
if(count < 1000)
{
id = 2 // to go to the other processor
count =0;
}
and I want it to stay in id = 2 until count reaches 1000 again.
Help please!
Something like this sounds like it would work?
double id = 1;
double count = 0;
do
{
count = count + 1;
if(count >= 1000)
{
if(id == 1)
{
id = 2;
}
else
{
id = 1;
}
count = 0;
}
} while(true);
You can write this shorter with ternary operators:
double id = 1;
double count = 0;
do
{
count = count + 1;
if(count >= 1000)
{
id = id == 1 ? 2 : 1;
count = 0;
}
} while(true);
I wasn't sure how you were doing your loop, so I've assumed a while loop would work. You could swap that bit out and make it fit your needs.

Having trouble understanding a solution to this c# algorithm

I was doing a LeetCode exercise for c# and made my own solution for the following prompt:
"Given a binary array nums, return the maximum number of consecutive 1's in the array."
"Input: nums = [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3."
My solution had a hardcoded array value, and i found a solution online that worked and ran fine. However, im having a really hard time understanding what the isStart and isEnd bools do. The code is below:
public class Solution {
public int FindMaxConsecutiveOnes(int[] nums)
{
if(nums == null || nums.Length == 0)
{
return 0;
}
var start = 0;
var length = nums.Length;
var maxLength = 0;
for(int i = 0; i < length; i++)
{
var current = nums[i];
bool isStart = current == 1 && (i == 0 || nums[i - 1] == 0);
bool isEnd = current == 1 && (i == length - 1 || nums[i + 1] == 0);
if (isStart)
{
start = i;
}
if(isEnd)
{
var currentOnes = i - start + 1;
maxLength = currentOnes > maxLength ? currentOnes : maxLength;
}
}
return maxLength;
}
I assume isStart and isEnd determine if we are at the Start or End of the array? I dont really understand what the operators do either. Any help could be appreciated. Thanks :)

Luhn Algorithm sorting out

I am sorting this code:
bool checkLuhn(const string& cardNo)
{
int nDigits = cardNo.length();
int nSum = 0, isSecond = false;
for (int i = nDigits - 1; i >= 0; i--) {
int d = cardNo[i] - '0';
if (isSecond == true)
d = d * 2;
nSum += d / 10;
nSum += d % 10;
isSecond = !isSecond;
}
return (nSum % 10 == 0);
}
There is one mystery what i do not know. Have googled, but still mystery.
That code:
if (isSecond == true)
d = d * 2;
Where on the code program detects is it splitable with 2? I understand if it's not splitable with 2, program multiply it with 2.
I understand operational principle of the program, but there must be some method or something which tells program what is that isSecond. Help me guys.
Now i understand it.
Before the for loop isSecond is false because first ordernumber is (0). Then this isSecond = !isSecond; change false to true. Then it's turn of the second ordernumber (1) and isSecond = true; so method multiplies it with 2. And then it goes false again and not multiplies number 2. Then it goes true and multiply number 3.
What a brain-teaser :D

Naughts and Crosses (Tic Tac Toe), subroutine query

So I'm at the final stage of my Noughts and Crosses project and I'm quite dearly stuck, I have done move validation subroutine as well as a subroutine that is solely based on changing the blank space in the box into an " X " or an " O ",
yet my code seems to tell me that some part of my code does not exist in the current context and I am completely baffled
The code is:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[,] grid = new string[3, 3] {{" "," "," "},
{" "," "," "},
{" "," "," "}};
string board = System.IO.File.ReadAllText("E:\\BoardGame.txt");
Console.WriteLine(board);
int player = 0;
var XCoordinate = 0;
var YCoordinate = 0;
int x, y;
GetMoveCoordinates(ref XCoordinate, ref YCoordinate);
if (player == 0)
{
grid[XCoordinate, YCoordinate] = " X ";
player++;
}
else
{
grid[XCoordinate, YCoordinate] = " O ";
player--;
}
UpdateGrid(grid, box);
if (player == 1)
{
}
}
public static void GetMoveCoordinates(ref int XCoordinate, ref int YCoordinate)
{
int CommaLocation;
bool GameHasBeenWon = false;
string CoordinatesInput;
string XChar, YChar;
while (GameHasBeenWon == false)
{
try
{
Console.Write("Enter your coordinates: (x,y) ");
CoordinatesInput = Console.ReadLine();
CommaLocation = CoordinatesInput.IndexOf(",".ToString());
XChar = CoordinatesInput.Substring(CommaLocation - 1, CommaLocation);
YChar = CoordinatesInput.Substring(CommaLocation + 1);
XCoordinate = int.Parse(XChar);
YCoordinate = int.Parse(YChar);
}
catch
{
Console.WriteLine("Invalid Input- Please Try Again");
}
}
}
public static bool CheckValidMove(int XCoordinate, int YCoordinate, string[,] Board)
{
if ((XCoordinate >= 1) || (XCoordinate <= 3))
{
if ((YCoordinate >= 1) || (YCoordinate <= 3))
{
if ((Board[XCoordinate, YCoordinate]) == " ")
{
return true;
}
else return false;
}
else return false;
}
else return false;
}
public static void UpdateGrid(string[,] grid, string box)
{
Console.Clear();
for (int x = 0; x < grid.GetLength(0); x++)
{
for (int y = 0; y < grid.GetLength(1); y++)
{
box = box.Replace((x + 1) + "," + (y + 1), grid[y, x]);
}
}
// In the case not required as clearning the console default the cursor back to 0,0, but left in
// as an example
Console.SetCursorPosition(0, 0);
Console.WriteLine(box);
}
}
}
Yet the problem I seem to have is under Main, under the if statement where the code seems to tell me that box in the Update(grid,box), does not exist in the current context, yet it should do in the last subroutine? Am I supposed to do it as a ref statement or am I missing something? Also if you have any tips on how to tidy up the code I'd gladly appreciate it (yes I will add win parameters but I'd like to draw my symbols first).
This is what the grid looks like this:
+---+---+---+
| | | |
+---+---+---+
| | | |
+---+---+---+
| | | |
+---+---+---+
There are several bugs here. First, the following won't compile:
UpdateGrid(grid, box);
As Andrew Whitaker indicated in the comments, there is no "box" variable in your main method (you never declared or initialized it). Define what that variable is and initialize it properly and that'll compile again.
Next, a quick stylistic note on the following:
while (GameHasBeenWon == false)
Don't explicitly compare to true and false - the correct way to do this is
while (!GameHasBeenWon)
The next line to comment on has several bugs:
(XCoordinate >= 1) || (XCoordinate <= 3)
This means that XCoordinate >= 1 OR it's less than or equal to 3, which isn't at all what you meant. Actually, by this logic, any integer is valid because it's either greater than 1, equal to 1, less than 3, or equal to 3. (Think about it - for what integers could a statement like this possibly be false?) Also, 3 is specifically not a valid index, but 0 is. Keep in mind that arrays are zero-indexed. Thus, this should actually be
(XCoordinate >= 0) && (XCoordinate < 3)
In terms of your if statements:
if ((Board[XCoordinate, YCoordinate]) == " ")
{
return true;
}
else return false;
returns true exactly when (Board[XCoordinate, YCoordinate]) == " " is true and false exactly when that statement is false. You could just do
return (Board[XCoordinate, YCoordinate]) == " ";
In fact, you could do that for the whole "if" statement. (I'm not sitting in front of an IDE right now so I apologize if my syntax isn't perfect here).
return ((XCoordinate >= 0) && (XCoordinate < 3) &&
((YCoordinate >= 0) && (YCoordinate < 3)) &&
((Board[XCoordinate, YCoordinate]) == " "));

Checking for a prime number

I'm having problems with a task. I need to find and alert the user if the number is prime or not.
Here is my code:
int a = Convert.ToInt32(number);
if (a % 2 !=0 )
{
for (int i = 2; i <= a; i++)
{
if (a % i == 0)
{
Console.WriteLine("not prime");
}
else
{
Console.WriteLine("prime");
}
Console.WriteLine();
}
}
else
{
Console.WriteLine("not prime");
}
Console.ReadLine();
Where did I go wrong, and how can I fix it?
Prime numbers is divisible by 1 and themselves you will need to check if number has exactly two divisor starting from one till number then it is prime.
int devisors = 0;
for (int i = 1; i <= a; i++)
if (a % i == 0)
devisors++;
if (devisors == 2)
Console.WriteLine("prime");
else
Console.WriteLine("not prime");
You can skip one iteration as we know all whole numbers are divisible by 1 then you will have exactly on divisor for prime numbers. Since 1 has only one divisor we need to skip it as it is not prime. So condition would be numbers having only one divisor other then 1 and number should not be one as one is not prime number.
int devisors = 0;
for (int i = 2; i <= a; i++)
if (a % i == 0)
devisors++;
if (a != 1 && devisors == 1)
Console.WriteLine("prime");
else
Console.WriteLine("not prime");
You just printed prime or not prime, and continued with the loop, rather than stopping. The %2 check is not really needed. Modified appropriately:
int a = Convert.ToInt32(number);
bool prime = true;
if (i == 1) prime = false;
for (int i = 2; prime && i < a; i++)
if (a % i == 0) prime = false;
if (prime) Console.WriteLine("prime");
else Console.WriteLine("not prime");
Console.ReadLine();
public bool isPrime(int num)
{
for (int i = 2; i < num; i++)
if (num % i == 0)
return false;
return num == 1 ? false : true;
}
Presumably your code is outputting lots of messages, which seem jumbled and meaningless? There are 3 key issues:
You arn't breaking out of your for loop when you've decided it can't be prime
You are assuming it is prime when it might not be, see the comments in the code below.
You are comparing to a itself, and that will always be divisible by a, the <= in the for condition needs to be <
Code:
int a = Convert.ToInt32(number);
if (a % 2 != 0)
{
for (int i = 3 i < a; i += 2) // we can skip all the even numbers (minor optimization)
{
if (a % i == 0)
{
Console.WriteLine("not prime");
goto escape; // we want to break out of this loop
}
// we know it isn't divisible by i or any primes smaller than i, but that doesn't mean it isn't divisible by something else bigger than i, so keep looping
}
// checked ALL numbers, must be Prime
Console.WriteLine("prime");
}
else
{
Console.WriteLine("not prime");
}
escape:
Console.ReadLine();
As other have mentioned, you could only loop to the square root of the a, by per-evaluating the square root and replacing this line:
for (int i = 3 i < a; i += 2)
with this:
float sqrRoot = (Int)Math.Sqrt((float)a);
for (int i = 3 i <= sqrRoot; i += 2)
It is important to per-evaluate it else your program will run much slower, rather than faster, as each iteration will involve a square root operation.
If you don't like goto statements (I love goto statements), post a comment and I'll replace it will a breakout boolean (or see Dukeling's more recent answer).
I've done far too much prime checking.
I did this:
bool isPrime = true;
List<ulong> primes = new List<ulong>();
ulong nCheck, nCounted;
nCounted = 0;
nCheck = 3;
primes.Add(2);
for (; ; )
{
isPrime = true;
foreach (ulong nModulo in primes)
{
if (((nCheck / 2) + 1) <= nModulo)
{ break; }
if (nCheck % nModulo == 0)
{ isPrime = false; }
}
if (isPrime == true)
{
Console.WriteLine("New prime found: " + (nCheck) + ", prime number " + (++nCounted) + ".");
primes.Add(nCheck);
}
nCheck++;
nCheck++;
}
This is not EXACTLY what you are looking for though, so what I'd do is put this in a background worker, but with the list of ulongs as a concurrent list, or something that you can access in 2 threads. Or just lock the list while it's being accessed. If the prime hssn't been worked out yet, wait until it is.
Yet another optimized way is to use Sieve of Eratosthenes algorithm.
From Wikipedia
To find all the prime numbers less than or equal to a given integer n by Eratosthenes' method:
1. Create a list of consecutive integers from 2 to n: (2, 3, 4, ..., n).
2. Initially, let p equal 2, the first prime number.
3. Starting from p, count up in increments of p and mark each of these numbers greater than p itself in the list. These will be multiples of p: 2p, 3p, 4p, etc.; note that some of them may have already been marked.
4. Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, let p now equal this number (which is the next prime), and repeat from step 3.
When the algorithm terminates, all the numbers in the list that are not marked are prime.
C# code
int[] GetPrimes(int number) // input should be greater than 1
{
bool[] arr = new bool[number + 1];
var listPrimes = new List<int>();
for (int i = 2; i <= Math.Sqrt(number); i++)
{
if (!arr[i])
{
int squareI = i * i;
for (int j = squareI; j <= number; j = j + i)
{
arr[j] = true;
}
}
for (int c = 1; c < number + 1; c++)
{
if (arr[c] == false)
{
listPrimes.Add(c);
}
}
}
return listPrimes.ToArray();
}
private static void checkpirme(int x)
{
for (int i = 1; i <= x; i++)
{
if (i == 1 || x == i)
{
continue;
}
else
{
if (x % i == 0)
{
Console.WriteLine(x + " is not prime number");
return;
}
}
}
Console.WriteLine(x + " is prime number");
}
where x is number to check it if prime or not

Categories

Resources