I have 4 buttons on my form and I want the user to input his word by clicking up, down, left and right on the buttons.
Image of the example form
The user can choose his letter, number or symbol by going up and down.
Left and right will be for going back and forth in the word. Back in case he made a mistake and forward in case he wants to confirm his current letter.
these are the variables
private string word;
private StringBuilder sb = new StringBuilder();
private char[] wordsAndLetters = { ' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', ',', '.', '!', '?' };
Now we need to give the buttons the option to go between the letters, etc.
private int i;
public Form1()
{
InitializeComponent();
tbOutput.Text = word;
}
private void btnUp_Click(object sender, EventArgs e)
{
//We don't want the i to go above the array
if (i <= 39)
{
i = i + 1;
}
tbOutput.Text = word + Convert.ToString(wordsAndLetters[i]);
}
private void btnDown_Click(object sender, EventArgs e)
{
//We don't want the i to go below the array
if (i > 0)
{
i = i - 1;
}
tbOutput.Text = word + Convert.ToString(wordsAndLetters[i]);
}
private void btnRight_Click(object sender, EventArgs e)
{
tbOutput.Text = word;
sb.Append(wordsAndLetters[i]);
word = sb.ToString();
i = 0;
tbOutput.Clear();
tbOutput.Text = word;
}
private void btnLeft_Click(object sender, EventArgs e)
{
int lengthword = sb.Length;
sb.Remove(lengthword -1, 1);
word = sb.ToString();
tbOutput.Clear();
tbOutput.Text = word;
}
}
This is what I have right now and it works but it isn't flawless. Do you guys have any way of making my current program better?
You cannot technically add to an existing string, as they are immutable. Instead, here are a couple simple options:
1) Concatenate the new character each time.
word += wordsAndLetters[i];
//Which is the same as:
//word = word + wordsAndLetters[i];
2) Use a StringBuilder as Jay mentions in his comment to your post.
StringBuilder sb = new StringBuilder();
sb.Append(wordsAndLetters[i]);
word = sb.ToString();
Related
This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 2 years ago.
I'm quite new to C# and I made this method to create random words and it takes in a minimum length and maximum as a parameter. But when I put it in a for loop 20 times I can see that every few in a row are identical. How do I fix this?
static string makename(int min, int max)
{
Random rnd = new Random();
char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
char[] consonants = { 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z' };
int namelength = rnd.Next(min, max);
char twoago = '2';
char oneago = '1';
string name = "";
for (int i = 0; i < namelength; i++)
{
if (oneago != twoago)
{
twoago = oneago;
if (rnd.Next(0, 2) == 1)
{
name = name + vowels[rnd.Next(0, vowels.Count())];
oneago = 'v';
}
else
{
name = name + consonants[rnd.Next(0, consonants.Count())];
oneago = 'c';
}
}
else if (oneago == 'c')
{
name = name + vowels[rnd.Next(0, vowels.Count())];
oneago = 'v';
}
else
{
name = name + consonants[rnd.Next(0, consonants.Count())];
oneago = 'c';
}
if (i == 0)
{
name = name.ToUpper();
}
}
return name;
}
Here is an example of the output (parameters are 4,10) (there was one output before this I cut off):console
When you instantiate the Random (with new Random();) random is being reset to the system clock. Your method is getting called quickly enough that the call is sometimes getting the same system clock time. Random on a computer is never random. It is based on a fairly random mathematical function that behaves fairly randomly as long as it is seeded (started) with a different number each time.
Note, you only need to seed random once for an application run in order for it to behave randomly. It is when you seed it multiple times that you get into trouble.
I have a reshuffle method that is of string type and it takes a char array as an argument it must randomize the characters inside the array each time the Encrypt method is used .. when I tried to call it in another method it gives me the syntax error "Method has some invalid arguments" This is the code
char[] p = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
string reshuffle(char[] alpas)
{
Random random=new Random();
for (int t = 0; t < alpas.Length; t++)
{
char tmp = alpas[t];
int r = random.Next(t, alpas.Length);
alpas[t] = alpas[r];
alpas[r] = tmp;
}
return new string (alpas);
}
public string Encrypt(string pt)
{
reshuffledChars=reshuffle(p[25]);
char[] ch = reshuffledChars.ToCharArray();
char[] buffer = new char[(pt.Length)];
for(int i=0;i<pt.Length;i++)
{
for(int j=0;j<26;j++)
{
if (char.ToUpper(p[j]) == pt[i])
{
buffer[i] = char.ToUpper(ch[j]);
break;
}
else if(char.ToLower(p[j])==pt[i])
{
buffer[i] = char.ToLower(ch[j]);
break;
}
else if(pt[i]==' ')
{
buffer[i] = ' ';
}
}
}
return new string(buffer);
}
Instead of passing reshuffle(p[25]), which is a single char, you should pass the entire array, like so: reshuffle(p).
In this line:
"reshuffledChars=reshuffle(p[25]);"
p[25] returns a char
This line in Encrypt():
reshuffle(p[25]);
should (I'm assuming) be:
reshuffle(p);
You're passing a char not a char[] to reshuffle() -- p[25] is the last char in the array p.
BTW if p should remain unchanged you'll need to copy it before passing to reshuffle.
You are passing wrong parameters instead of reshuffle(p[25]) use reshuffle(p) to send entire array.
If you are looking for a random string generator, this link will help. I have provided a working example in dotnet fiddle.
using System;
using System.Linq;
namespace Rextester
{
public class Program
{
private static Random random = new Random();
public static string RandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!##$%&";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
public static void Main(string[] args)
{
//Your code goes here
Console.WriteLine(RandomString(8));
}
}
}
I am trying to write to a new file (create a new file), and I want everything that is shown in the command console (the 26 shifts) when the program runs to all be shown in the new file. However, when I use file.WriteAllText() it overwrites each shift and then only shows the 26th shift in the new file I create.
using System;
using System.IO;
namespace ceasarAssignment
{
public class caesarShift
{
public static void Main()
{
string file = #"text.txt", // Name of the file that is being read from
encrypted = File.ReadAllText(file), // Reading the file
decrypted = " ";
char character = '0';
int shift = 0;
encrypted = encrypted.ToUpper(); // Puts the string into uppercase
char[] alph = new char[26] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
// The array above is the alphabet (26 characters)
Console.WriteLine("Encrypted text: \n{0}", encrypted);
//Shows the encrypted text before it is decrypted
for (int i = 0; i < alph.Length; i++) //adds a counter so that this for loop will repeat until it has happened 26 times
{
decrypted = "";
foreach (char c in encrypted)
{
character = c;// each letter in the file is now defined as a 'character'
if (!char.IsLetter(c)) {
decrypted += c;
continue;
}
shift = Array.IndexOf(alph, character) - i; //searchs the array for the character then minuses the counter to add the correct shift
if (shift <= 0)
shift = shift + 26;// if the character is at the beginning of the array go to the end
if (shift >= 26)
shift = shift - 26;// if the character is at the end of the array go to the beginning
decrypted += alph[shift];
}
Console.WriteLine("\n Shift {0} \n {1}", i+1, decrypted); //Shows the decrypted code for each 26 shifts
}
}
}
}
You need to use File.AppendAllText(path, appendText)
File.WriteAllText() will overwrite the file each time the loop is run
Question
Take input of 1 character from user. It can be the vowel or consonant.
After the user gives input so it will ask do you want to input the character again for Yes press Y and for No press N.
When the user says No, you have to show how much vowel and how much consonant use has input.
Please do this question using For loop. I think array must be use. I did this code it counting vowel and consonant and spacing. But I cant take the input multiple times.
My code doesnn't run multiple times. I can only write sentence or a character in a line so it will only count that. But I want to ask the user to enter a character again.
I want my code to run multiple times so the user can give input multiple times as I explain my question.
using System;
public class vowelConsonant
{
public static void Main()
{
int vowels = 0;
int consonant = 0;
int space = 0;
Console.WriteLine("Enter a Sentence or a Character");
string v = Console.ReadLine().ToLower();
for (int i = 0; i < v.Length; i++)
{
if (v[i] == 'a' || v[i] == 'e' || v[i] == 'i' || v[i] == 'o' || v[i] == 'u')
{
vowels++;
}
else if (char.IsWhiteSpace(v[i]))
{
space++;
}
else
{
consonant++;
}
}
Console.WriteLine("Your total number of vowels is: {0}", vowels);
Console.WriteLine("Your total number of constant is: {0}", consonant);
Console.WriteLine("Your total number of space is: {0}", space);
Console.ReadLine();
}
}
Thanks
Just put an infinite loop around the whole thing.
using System;
public class vowelConsonant
{
public static void Main()
{
// Infinite loop.
while (true)
{
int vowels = 0;
int consonant = 0;
int space = 0;
Console.WriteLine("Enter a Sentence or a Character");
string v = Console.ReadLine().ToLower();
for (int i = 0; i < v.Length; i++)
{
if (v[i] == 'a' || v[i] == 'e' || v[i] == 'i' || v[i] == 'o' || v[i] == 'u')
{
vowels++;
}
else if (char.IsWhiteSpace(v[i]))
{
space++;
}
else
{
consonant++;
}
}
Console.WriteLine("Your total number of vowels is: {0}", vowels);
Console.WriteLine("Your total number of constant is: {0}", consonant);
Console.WriteLine("Your total number of space is: {0}", space);
}
}
}
This application to count vowels and consonants letters in a sentence.
This is another solution with less line of codes with understanding idea of using loop and nested loop with char arrays.
Application interface with controls names
namespace Program8_4
{
public partial class Form1 : Form
{
// declare the counter variables in field
int iNumberOfVowels = 0;
int iNumberOfConsonants = 0;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// call the methods in this event
GetVowels(txtStringInput.Text);
GetConsonants(txtStringInput.Text);
// show the result in a label
lblOutput.Text = "The number of vowels : " + iNumberOfVowels.ToString() + Environment.NewLine+
"The number of consonants : " + iNumberOfConsonants.ToString();
// assign zero the counters to not add the previous number to new number, and start counting from zero again
iNumberOfVowels = 0;
iNumberOfConsonants = 0;
}
private int GetConsonants(string strFindConsonants)
{
// Declare char array to contain consonants letters
char[] chrConsonants = { 'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'X',
'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'x' };
// loop to get each letter from sentence
foreach (char Consonants in strFindConsonants)
{
// another nested loop to compare each letter with all letters contains in chrConsonants array
for (int index = 0; index < chrConsonants.Length; index++)
{
// compare each letter with each element in charConsonants array
if (Consonants == chrConsonants[index])
{
// If it is true add one to the counter iNumberOfConsonants
iNumberOfConsonants++;
}
}
}
// return the value of iNumberOfConsonants
return iNumberOfConsonants;
}
private int GetVowels(string strFindVowels)
{
// Declare char array to contain vowels letters
char[] chrVowels = { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O','U' };
// loop to get each letter from sentence
foreach (char Vowels in strFindVowels)
{
// another nested loop to compare each letter with all letters contains in chrVowels array
for (int index = 0; index < chrVowels.Length; index++)
{
// compare each letter with each element in chrVowels array
if (Vowels == chrVowels[index])
{
// If it is true add one to the counter iNumberOfVowels
iNumberOfVowels = iNumberOfVowels+1;
}
}
}
// return the value of iNumberOfVowels
return iNumberOfVowels;
}
}
}
We can simply find the required vowels and consonant counts using Regex.Matches() function.
Below is the working code snippet:
public static void Main()
{
Console.WriteLine("Enter a Sentence or a Character");
string input = Console.ReadLine().ToLower();
string vowels = #"[aeiouAEIOU]+"; //regular expression to match vowels
string consonants = #"[^aeiouAEIOU]+"; //regular expression to match consonants
string space = #"[\S]+";
int vowLength = new Regex(vowels).Matches(input).Count;
int conLength = new Regex(consonants).Matches(input).Count;;
int spLength = new Regex(space).Matches(input).Count;;
Console.WriteLine("Your total number of vowels is: {0}", vowLength);
Console.WriteLine("Your total number of constant is: {0}", conLength);
Console.WriteLine("Your total number of space is: {0}", spLength);
}
I have a quick question. I have a keygen to generate random passwords for my app. It generates capital letters and numbers but I want it to be like in some programs that formats their code like this xxxx-xxxx-xxxx. so far my code is this
Random random = new Random(0);
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = getrandomcode();
}
public string getrandomcode()
{
char[] tokens = {'0', '1', '2', '3', '4', '5', '7', '8', '9', 'A', 'B', 'C',
'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
char[] codeArray = new char[24];
for (int i = 0; i < 24; i++)
{
int index = random.Next(tokens.Length - 1);
codeArray[i] = tokens[index];
}
return new String(codeArray);
}
Its something simple not to complex so I hope there is a way to implement the "-" to this code.
thanks in advance!
Include this in your 'for' loop :
if (i % 5 == 4)
{
codeArray[i] = '-';
}
else
{
int index = random.Next(tokens.Length - 1);
codeArray[i] = tokens[index];
}
Or if you want to use regular expression, try this:
textBox1.Text = Regex.Replace(getrandomcode(), #"(\w{4})(\w{4})(\w{4})(\w{4})(\w{4})", "$1-$2-$3-$4-$5")
Try this:
for (int i = 0; i < 24; i++)
{
if (i % 5 == 4) {
codeArray[i] = '-';
} else {
int index = random.Next(tokens.Length - 1);
codeArray[i] = tokens[index];
}
}
If you want your password to have 24 non-dash characters, change the 24 to 29.
But I also have to tell you that using a random function seeded with 0 is not a very secure way to generate passwords. If the application is stopped and restarted, it will generate the same set of passwords the second time that it did the first time. It is better to not pass an initialization argument in which case it will use the time to seed the random number generator.
If these passwords are going to be used for something important or something which the whole world can access (or both), then even this isn't really random enough to be secure. You should look at cryptographic random number generators like System.Security.Cryptography.RNGCryptoServiceProvider