How to Array Result on a Label in C# Windows Form - c#

I'm making a simple program that computes the cube of the input number. I want to array the result from 1 up to the given number but I don't how to manipulate the label control.
Here's my coding:
int num = 0;
int cube;
string result;
private void input()
{
num = Convert.ToInt32(txtn­um.Text);
}
Private void btncompute_Click(obj­ect sender, EventArgs e){
input();
int i = 0;
do
{
cube = num * num * num ;
i++;
result = i + " and cube of the " + i + " is :" + cube;
} while (i < num);
lbloutput.Text = result;
}
The only output here is the cube of the input number. I want to get the result from index 0 and display it on a label through array. For instance, for input 3, output should be something like this:
1 and the cube of the 1 is 1
...
3 and the cube of the 3 is 27
Your help will be greatly appreciated. Thank you.

A couple of things, the current logic won't give you what you want.
You want to multiply by i, not by num, for instance if num = 3, cube will always be 27. Based on your output you want all cubes up to and including your number.
You want to set i to 1 initially to start at 1, other you are starting at 0
You want to calculate the cube of num also, which means you have to change your loop to include num, thus i <= num
Change your code to the following:
int num = 0;
int cube;
string result = String.Empty;
private void input()
{
num = Convert.ToInt32(txtn­um.Text);
}
private void btncompute_Click(obj­ect sender, EventArgs e)
{
input();
int i = 1;
do
{
cube = i* i* i;
result = result + String.Format("{0} and cube of the {0} is : {1}\r\n", i, cube);
i++;
}
while (i <= num);
lbloutput.Text = result.ToString();
}

The biggest part of your problem is that a label is not the appropriate control for displaying multiple lines of text. It doesn't size or scroll based on the size of the content. You would probably be better served with a multi-line text-box. You can make it read-only if you don't want it editable (like a label).
In that case, you would want to call
mytextBox.Clear()
before the loop to clear any existing text. And then after building your result string in the loop, call
mytextbox.AppendText(result);
to add the next iteration to the content.
Implementation left as an exercise for the reader ;)

Related

Unicode have different width when printing

I am developing a chess engine in C#/Unity and want to print the board on a nice format. Preferably I want to print with some Unicode pieces but they end up making the board uneven, see image below:
The same seems to go for normal numbers since each row starts slightly off one another, row 1 starts more left than the others for example.
Why does my Debug.Log/prints end up like this, and how can I print them so that each character takes up the same amount of space?
EDIT:
Here is the code I use to Debug.Log the board if that helps:
public static void PrintBitboard(ulong bitboard)
{
string zero = " 0 ";
string one = " 1 ";
string printString = "";
// Loop through all squares and print a 1 if piece and 0 if not a piece on the square
for (int row = 0; row < 8; row++)
{
// Add numbering on the left side
printString += (8 - row) + " ";
for (int col = 0; col < 8; col++)
{
int currentSquare = row * 8 + col;
printString += BitOperations.GetBit(bitboard, currentSquare) != 0 ? one : zero;
}
// Change to new row
printString += "\n";
}
// Print bottom letters
printString += "\n" + " a b c d e f g h";
// Send message to the console
Debug.Log(printString);
}
What you are looking for is not "unicode" but monospace
-> As GiacomoCatenazzi already said, the only thing responsible for that is the font you are using
As a "quick and dirty" fix / alternative you could try and simply use tabs (\t) instead of spaces like (in general for larger string based concatenations I would recommend to use a StringBuider)
public static void PrintBitboard(ulong bitboard)
{
const string zero = "0\t";
const string one = "1\t";
var stringBuilder = new StringBuilder();
// Loop through all squares and print a 1 if piece and 0 if not a piece on the square
for (int row = 0; row < 8; row++)
{
// Add numbering on the left side
stringBuilder.Append((8 - row)).Append('\t');
for (int col = 0; col < 8; col++)
{
int currentSquare = row * 8 + col;
stringBuilder.Append(BitOperations.GetBit(bitboard, currentSquare) != 0 ? one : zero);
}
// Change to new row
stringBuilder.Append('\n');
}
// Print bottom letters
stringBuilder.Append("\n \ta\tb\tc\td\te\tf\tg\th");
// Send message to the console
Debug.Log(stringBuilder.ToString());
}
See .Net Fiddle which in the Unity console would look like
(in both I had to tricks a bit since I don't know what BitOperations implementation you are using)

how to increase array element by multiplying

Textbox2 has some 60 ids and i want to increase it to 250....
So i use following code increase the elements.
when i click the size button textbox2 should have 300 ids(now it has 60 only)..
lately i need to reduce it to 250 ids
. But it is getting exceptions
private void Size_Click(object sender, System.EventArgs e)
{
string[] vlist = textBox1.Text.Split('\n');
int size = (Convert.ToInt32(textBox2.Text)) / Convert.ToInt32(vlist) +1;
int p = Convert.ToInt32(textBox2.Text) * size;
textBox2.Text = p.ToString();
}
Please tell me what should i do in this?
private void Size_Click(object sender, System.EventArgs e)
{
List<string> vlist = new List<string>(textBox2.Text.Split('\n'));
int currentLineNumber = vlist.Count;
int targetLineNumber = Int32.Parse(textBox1.Text);
if (targetLineNumber == currentLineNumber)
return; //nothing to change
else if (targetLineNumber > currentLineNumber) //increase number of line
{
for (int i = currentLineNumber; i < targetLineNumber; ++i)
vlist.Add(vlist[(i - currentLineNumber) % currentLineNumber]);
}
else //reduce number of line
vlist = vlist.GetRange(0, targetLineNumber);
if (vlist.Count == 0)
textBox2.Text = String.Empty;
else
{
string result = vlist[0];
for (int i = 1; i < targetLineNumber; ++i)
result += String.Format("\n{0}", vlist[i]);
textBox2.Text = result;
}
}
The logic is quite simple. First, get number of line in textbox1 and target line number in textbox2. (This assume textbox1 is not empty though)
For increasing in size, we just keep adding id to the list until it reaches target size. For reducing size, it is even simpler, just take the first N lines from the list. After resizing, just reconnect all the lines together and set textBox1.Text to it.
You cannot change the array size.
If you want to have dynamic size you should use collections like List<T>
...
string[] vlist = textBox1.Text.Split('\n');
int size = (Convert.ToInt32(textBox2.Text)) / Convert.ToInt32(vlist.Length) +1;
string newString = "";
for(int i=0;i<size;i++){
newString = String.Join("\n",vlist);
textBox2.Text += newString + "\n";
}
...
This way, you append to the textbox the information you already got there (vlist), the number of times you need (size). I haven't tested it but probably this would repeat those IDs once more tan desired, in that case, remove the "+1" from the size variable definition
For the reduction to 250, you should specify which criteria are you following... if they are only the first 250, you could do that easily in a for loop with 250 as the break condition / top value

Adding +1 to integer value

I cannot think of what i'm doing wrong here, the code is very simple, i'm trying to increment an intenger by +1 everytime a button is pressed, instead of doing for example: 5 + 1 which is 6, the label prints 51.
Code:
// update count here...
lblCount.Text = lblCount.Text + 1;
The label holds the initial value, i thought just adding what the label was currently then just doing +1 would be enough but it's not working as i thought.
any helpwould be appreciated.
Convert to int and then convert to String
var total = int.Parse(lblCount.Text) + 1;
lblCount.Text = total.ToString();
Yeah that is because output of label.Text is a String use it like this
int x = Int32.Parse(lblCount.Text);
Then add x + 1
This will increment when conversion is successful.
In C# 7 code:
if (int.TryParse(lblCount.Text, out int currentValue))
{
var result = currentValue + 1;
lblCount.Text = result.ToString();
};
if (int.TryParse(lblCount.Text, out int currentValue))
{
currentValue += currentValue 1;
lblCount.Text = currentValue.ToString();
};
lblCount.Text holds a text in it(better to say String) and now your are trying to make arithmatic calculation with integer.
It at first holds it's value and add the next value as a string(like concatination). To avoid this,
First you have to convert it to integer before adding the 1.
you do that like this lblCount.Text = int.Parse(lblCount.Text) + 1;
As you already notice your problem is that current value saved as a string. So you can not do mathematical operation on a string.
Instead of parsing string to integer every time you want add 1 - save current value in local variable of type integer and do all operations on this variable.
private int count;
// update count here...
count = count + 1;
lblCount.Text = count.ToString();
int counter;
public void Yourbutton_Click(object sender, EventArgs e)
{
counter + 1;
lblCount.Text =counter.ToString();
}

Increase chances of name being picked from Array

For my program, I've prompted the user to put 20 names into an array (the array size is 5 for testing for now), this array is then sent to a text document. I need to make it so that it will randomly pick a name from the list and display it (which I have done). But I now need to make it increase the chances of a name being picked, how would I go about doing this?
Eg. I want to increase the chances of the name 'Jim' being picked from the array.
class Programt
{
static void readFile()
{
}
static void Main(string[] args)
{
string winner;
string file = #"C:\names.txt";
string[] classNames = new string[5];
Random RandString = new Random();
Console.ForegroundColor = ConsoleColor.White;
if (File.Exists(file))
{
Console.WriteLine("Names in the text document are: ");
foreach (var displayFile in File.ReadAllLines(file))
Console.WriteLine(displayFile);
Console.ReadKey();
}
else
{
Console.WriteLine("Please enter 5 names:");
for (int i = 0; i < 5; i++)
classNames[i] = Console.ReadLine();
File.Create(file).Close();
File.WriteAllLines(file, classNames);
Console.WriteLine("Writing names to file...");
winner = classNames[RandString.Next(0, classNames.Length)];
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("\nThe winner of the randomiser is: {0} Congratulations! ", winner);
Thread.Sleep(3000);
Console.Write("Completed");
Thread.Sleep(1000);
}
}
}
There's two ways of doing this. You can either produce a RNG with a normal distribution targeting one number.
Or the simpler way is a translational step. Generate in the range 0-100 and then produce code which translates to the answer in a biased way e.g.
0-5 : Answer 1
6-10: Answer 2
11-90: Answer 3
91-95: Answer 4
96-100: Answer 5
This gives an 80% chance of picking Answer 3, the others only get a 5% chance
So where you currently have RandString.Next(0, classNames.Length) you can replace that with a function something like GetBiasedIndex(0, classNames.Length, 3)
The function would look something like this (with test code):
public Form1()
{
InitializeComponent();
int[] results = new int[5];
Random RandString = new Random();
for (int i = 0; i < 1000; i++)
{
var output = GetBiasedIndex(RandString, 0, 4, 3);
results[output]++;
}
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 5; i++)
{
builder.AppendLine(results[i].ToString());
}
label1.Text = builder.ToString();
}
private int GetBiasedIndex(Random rng, int start, int end, int target)
{
//Number between 0 and 100 (Helps to think percentage)
var check = rng.Next(0, 100);
//There's a few ways to do this next bit, but I'll try to keep it simple
//Allocate x% to the target and split the remaining y% among all the others
int x = 80;//80% chance of target
int remaining = 100 - x;//20% chance of something else
//Take the check for the target out of the last x% (we can take it out of any x% chunk but this makes it simpler
if (check > (100 - x))
{
return target;
}
else
{
//20% left if there's 4 names remaining that's 5% each
var perOther = (100 - x) / ((end - start) - 1);
//result is now in the range 0..4
var result = check / perOther;
//avoid hitting the target in this section
if (result >= target)
{
//adjust the index we are returning since we have already accounted for the target
result++;
}
//return the index;
return result;
}
}
and the output:
52
68
55
786
39
If you're going to call this function repeatedly you'll need to pass in the instance of the RNG so that you don't reset the seed each call.
If you want to target a name instead of an index you just need to look up that name first and have an else condition for when that name isn't found

C# GUI application that stores an array and displays the highest and lowest numbers by clicking a button

Background:This is updated from 13 hours ago as I have been researching and experimenting with this for a few. I'm new to this programming arena so I'll be short, I'm teaching myself C# And I'm trying to learn how to have integers from a user's input into a textbox get calculated from a button1_Click to appear on the form. Yes, this is a class assignment but I think I have a good handle on some of this but not all of it; that's why I'm turning to you guys.
Problem:
I'm using Microsoft Visual Studio 2010 in C# language, Windows Forms Application and I need to create a GUI that allows a user to enter in 10 integer values that will be stored in an array called from a button_Click object. These values will display the highest and lowest values that the user inputted. The only thing is that the array must be declared above the Click() method.
This is what I have come up with so far:
namespace SmallAndLargeGUI
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void inputText_TextChanged(object sender, EventArgs e)
{
this.Text = inputText.Text;
}
public void submitButton_Click(object sender, EventArgs e)
{
int userValue;
if(int.TryParse(inputText.Text, out userValue))
{
}
else
{
MessageBox.Show("Please enter a valid integer into the text box.");
}
int x;
x = Convert.x.ToString();
int squaredResults = squared(x);
int cubedResults = cubed(x); squared(x);
squaredLabel.Text = x.ToString() + " squared is " + squaredResults.ToString();
cubedLabel.Text = x.ToString() + " cubed is " + cubedResults.ToString();
}
public static int squared(int x)
{
x = x * x;
return x;
}
public static int cubed(int x)
{
x = x * squared(x);
return x;
}
}
}
Now I can't run this program because line 38 shows an error message of: 'System.Convert' does not contain a definition for 'x' Also I still have to have an array that holds 10 integers from a textbox and is declared above the Click() method. Please guys, any help for me? This was due yesterday.
This looks like homework, so you should try a bit more than that. Here is what you could do: parse the string (say it's a comma-separated list of numbers), cast each value to int and populate your array. You can either call .Max() / .Min() methods or loop through the values of the array and get the max / min value. Here is a bit of code:
int n = 10;
int[] numbers = (from sn in System.Text.RegularExpressions.Regex.Split(inputText.Text, #"\s*,\s*") select int.Parse(sn)).ToArray();
int max = numbers.Max();
int min = numbers.Min();
//int max = numbers[0];
//int min = numbers[0];
//for(int i = 1; i < n; i++)
//{
// if(max < numbers[i])
// {
// max = numbers[i];
// }
// if(min > numbers[i])
// {
// min = numbers[i];
// }
//}
This in all probability being a homework I will not provide entire solution but just provide a hint.
Task to me seems to be to some how accept 10 integers and then show smallest and largest of them. For this there is no need to maintain an array (off-course only if maintaining an array is itself not part of the problem). You just need to keep track of current minimum and current maximum.
As and when you receive an input compare it with the current minimum and maximum and update them accordingly. e.g.
if(num < curr_min) curr_min = num;

Categories