I want to build a sequence randomiser mobile app in c#. I would like to retrieve the smallest and the largest number in an interval from two diffrent text boxes, and after I click the Generate button to display the random sequence of all the numbers in a new text box.
My code only displays one number. What's wrong with it?
Thanks.
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private void button_Click(object sender, RoutedEventArgs e)
{
int seed = 345;
var result = "";
int min = Convert.ToInt32(textBox.Text);
int max = Convert.ToInt32(textBox2.Text);
Random r3 = new Random(seed);
for (int i = min; i < max; i++)
{
ecran.Text = (/*"," + r3.Next(min, max)*/i).ToString();
}
}
To clarify what was wrong with your solution:
Inside the loop you were constantly reassigning the value of ecran.Text.
i.e.
1st loop cycle > ecran.Text = ", " + 77
2nd loop cycle > ecran.Text = ", " + 89
//Value of ecran.Text after 1st cycle is ", 77"
//Value of ecran.Text after 2nd cycle is ", 89"
Overriding the value of ecran.Text with each iteration.
Fixed by adding a plus symbol in front of equals ecran.Text += ", " + LOGIC
This happens because you assign sequence values to ecran.Text in a loop. Instead, you should create a string representation of the sequence, and assign it at the end.
Use Shuffle<T> method from this Q&A:
int min = Convert.ToInt32(textBox.Text);
int max = Convert.ToInt32(textBox2.Text);
if (max < min) return;
var sequence = Enumerable.Range(min, max-min+1).ToList();
Shuffle(sequence);
ecran.Text = string.Join(",", sequence);
Related
I am writing a program that first lets a user enter a number between 1 and 10, and then checks what numbers between 1 and 1000 are dividable by that number.
both variables used are int variables, so for example if a user enters 4, it should read: 1 8 12 16 etc.
thusfar i have the following code:
private void button1_Click(object sender, EventArgs e)
{
int Getal1 = 1;
int Getal2;
Getal2 = int.Parse(textBox1.Text);//textbox1 to getal2
for (Getal1 = 1; Getal1 <= 1000; Getal1++)//// for loop.
{
textBox2.Text = textBox2.Text + "\r\n" + Getal1 / Getal2 + "\r\n";
}
}
the textbook mentions using the following code : Getal1 % Getal2.. i tried adding it after the calculation above, but this didnt work.. math is not my strong point at all..
does someone have an explanation on this?
maybe if Getal1 % Getal2 = 0??.. im really guessing here..
thanks for any help in advance,
Stefan
I tried adding code from the textbook, expecting the program to work correctly, right now it does give a result, but not a correct result.. for example if i enter 2 it starts the sequence with the numbers 123..
for (Getal1 = 1; Getal1 <= 1000; Getal1++)//// for loop.
{
if (Getal1 % Getal2 == 0)
{
textBox2.Text += Getal1.ToString() + Environment.NewLine;
}
}
You can omit the division checking whatsoever by starting with the number introduced by the user and then adding this number in the loop. This way you will never get a number that is not dividable.
For example:
if user inputs 4, you start with 4
than you add 4 to it and get 8
add 4 again, get 12 and so on
private void button1_Click(object sender, EventArgs e)
{
int Getal2 = int.Parse(textBox1.Text);//textbox1 to getal2
for (int Getal1 = Getal2; Getal1 <= 1000; Getal1 += Getal2)//// for loop.
{
textBox2.Text += Getal1 + "\r\n";
}
}
i want to make user input random number example : 5-3-10-50
, system will split " - " and then the result 5 3 10 50
, how to make subtraction from first number minus second number and so on,
like this 5 - 3 = 2 , 2 - 10 = -8 , -8 - 50 = -58
and then system will print the final answer -58
my code :
bool Subtraction = true;
int AskSubtraction = 0;
while (Subtraction)
{
Console.Write("\n" + "input number ( example : 1 - 2 - 3 - 4 ) : ");
var InputNumber = Console.ReadLine();
double Answer = 0;
foreach (var result in InputNumber.Split('-'))
{
if (double.TryParse(result, out _))
{
double NumberResult = Convert.ToDouble(result);
Answer -= NumberResult;
}
else
{
Console.WriteLine("\n" + "Wrong input !");
AskSubtraction++;
}
}
Console.WriteLine("\n" + "subtraction result : " + Answer);
}
i know my code is wrong, im beginner i already try to fix this but i cant fix it until now, i hope someone tell me what's wrong with my code and fix it too, thank you.
The reason yours doesn't work is because you set Answer = 0.
And you used foreach. On the first iteration of the loop, the first number is subtracted from Answer which results in -5.
Use for (int i=1; i<arr.Length; i++)
instead of foreach
Start from index 1, and then subtract the values.
Example:
var arr = InputNumber.Split('-');
double Answer = 0;
if (double.TryParse(arr[0], out _))
{
// We set Answer to the first number, since nothing is subtracted yet
Answer = Convert.ToDouble(arr[0]);
}
// We start index from 1, since subtraction starts from 2nd number on the String array
for (int i=1; i<arr.Length; i++)
{
if (double.TryParse(arr[i], out _))
{
double NumberResult = Convert.ToDouble(arr[i]);
Answer -= NumberResult;
}
}
Tested on Online C# Compiler
You would need a condition inside the foreach loop to check for the first parsed double before you begin subtraction. Also there is no need to call Convert.ToDouble() since the double.TryParse() function already returns the parsed double value, All you would need is a variable to contain the out value of the double.TryParse() function, See example below
bool Subtraction = true;
int AskSubtraction = 0;
while (Subtraction)
{
Console.Write("\n" + "input number ( example : 1 - 2 - 3 - 4 ) : ");
var InputNumber = Console.ReadLine();
double Answer = 0;
double numResult;
foreach (var result in InputNumber.Split('-'))
{
if (double.TryParse(result, out numResult))
{
if(Math.Abs(Answer)>0){
Answer -= numResult;
}
else{
Answer=numResult;
}
}
else
{
Console.WriteLine("\n" + "Wrong input !");
AskSubtraction++;
}
}
Console.WriteLine("\n" + "subtraction result : " + Answer);
}
How can I create a line of code in c# that I will use to give every new product that I add to my product table?I am using MySQL database.
This is what I have tried so far although it's not what I really need.
//auto product number
static string IncrementID(string startValue, int numNonDigits)
{
string nonDigits = startValue.Substring(0, numNonDigits);
int len = startValue.Length - numNonDigits;
int number = int.Parse(startValue.Substring(numNonDigits));
number++;
if (number >= Math.Pow(10, len)) number = 1; // start again at 1
return String.Format("{0}{1:D" + len.ToString() + "}", nonDigits, number);
}
private void Genarate_productcode()
{
product_code.Text = IncrementID("QIEpl/PO/0000009", 9); // produces QIEpl/PO/0000010 // C00011 PCI0001
}
I have a ListBox with X Items in it. An Item is build up like String, double, double. I want that the item with the smalles value of the second double gets shown together with its string in a Label.
An example Item: Name Value1 Value2
So every part is devided by spaces. The code works only for getting the smallest value of the second double yet, but doesnt take the string of that item.
The function of vName doesn't work.
private void bVergleich_Click(object sender, RoutedEventArgs e)
{
if (listBox.Items.Count <= 0)
{
MessageBox.Show("Bitte erst Einträge hinzufügen.");
}
else
{
int anzahl = listBox.Items.Count;
string str = listBox.Items[anzahl].ToString();
string vName = str.Substring(0, str.IndexOf(" ") + 1);
var numbers = listBox.Items.Cast<string>().Select(obj => decimal.Parse(obj.Split(' ').First(), NumberStyles.Currency, CultureInfo.CurrentCulture));
decimal minValue = listBox.Items.Cast<string>().Select(obj => decimal.Parse(obj.Split(' ').Last(), NumberStyles.Currency, CultureInfo.CurrentCulture)).Min();
lVergleich.Content = vName + " " + minValue + "€";
}
}
Any ideas how I can get the string too?
I will try using your code example. You could use the old school approach and run with a for-loop through all entries.
private void bVergleich_Click(object sender, RoutedEventArgs e)
{
if (listBox.Items.Count <= 0)
{
MessageBox.Show("Bitte erst Einträge hinzufügen.");
}
else
{
List<decimal> tmpListe = new List<decimal>();
int anzahl = listBox.Items.Count;
for (int i = 0; i < anzahl; i++)
{
string str = listBox.Items[i].ToString();
// collect all the second double values
tmpListe.Add(decimal.Parse(str.Split(' ').Last(), NumberStyles.Currency, CultureInfo.CurrentCulture));
}
// get the minimal value and its index
decimal minValue = tmpListe.Min();
int index = tmpListe.IndexOf(tmpListe.Min());
// use the index to get the name
string str2 = listBox.Items[index].ToString();
string vName = str2.Substring(0, str2.IndexOf(" ") + 1);
// write down your comparison
lVergleich.Content = vName + " " + minValue + "€";
}
}
This should display you the first lowest value in your List.
personally I would also suggest to use a custom class with 3 properties and an overridden ToString method for display. Then collect all the items in a generic List and bind this List to the ListBox.
You can sort your collection by the desired value and take the first element in sequence
List<string> list = listBox.Items.ToList();
list.Sort((x1, x2) => decimal.Compare(decimal.Parse(x1.Split(' ')[1]), decimal.Parse(x2.Split(' ')[1])));
string x = list.First();
Or just
string result = listBox.Items.OrderBy(y => decimal.Parse(y.Split(' ')[1])).First();
I am new to C # and I am getting stuck on using IEnumerable.Except. What I am trying to do is get the difference of 2 sequences of 100 random dice rolls using 2 die. I have my die rolls and totals good to go. My differences are not showing in my txtDifference textbox at all. I am not sure if I have it placed in the correct spot or if it isn't written correctly. The code itself has no errors and I am not sure how to fix it. Here is my code, any help is greatly appreciated!!
private void btnRoll_Click(object sender, EventArgs e)
{
//create random and lists
randomizer = new Random();
List<int> numbers = new List<int>();
List<int> secondNumbers = new List<int>();
//for loop for 1st sequence
for (i = 1; i < 100; i++)
{
string mssg = string.Empty;
die1 = randomizer.Next(1, 7);
die2 = randomizer.Next(1, 7);
dieRoll1.Text = die1.ToString();
dieRoll2.Text = die2.ToString();
rollValue = die1 + die2;
//add to collection.
numbers.Add(i);
//display results
txtResults.Text += string.Concat(dieRoll1.Text, " ", dieRoll2.Text, " ", rollValue, " ", Environment.NewLine);
}
//loop for second sequence.
for (i = 1; i < 100; i++)
{
string mssg = string.Empty;
die1 = randomizer.Next(1, 7);
die2 = randomizer.Next(1, 7);
dieRoll1.Text = die1.ToString();
dieRoll2.Text = die2.ToString();
rollValue = die1 + die2;
//add to collection.
secondNumbers.Add(i);
//display results in second text box
txtResults2.Text += string.Concat(dieRoll1.Text, " ", dieRoll2.Text, " ", rollValue, " ", Environment.NewLine);
}
// IEnumerable for comparison between the two sequences
IEnumerable<int> onlyInFirstSet = numbers.Except(secondNumbers);
//foreach to display the differences between the sequences
foreach (int number in onlyInFirstSet)
txtDifference.Text = number.ToString();
}
txtDifference.Text = number.ToString(); will show only last number in the set as you are overwriting the value on each iteration.
I think you are looking for showing all of the values:
txtDifference.Text = String.Join(",", onlyInFirstSet);
Both loops iterate from 1 to 100. Then, in both cases, you're adding the value of i to the lists... which means both lists end up with the values 1 to 100 in them.
numbers.Add(i);
secondNumbers.Add(i);
So the following line of code always results in an empty list. It removes the second collection of numbers 1 to 100 from the first collection of numbers 1 to 100.
IEnumerable<int> onlyInFirstSet = numbers.Except(secondNumbers);
Instead, add the rollValue value to your list, not the variable your foreach loop is iterating over:
rollValue = die1 + die2;
//add to collection.
numbers.Add(rollValue);
Same goes for your second loop and collection:
rollValue = die1 + die2;
//add to collection.
secondNumbers.Add(rollValue);