Morse code converter only outputs one character c# - c#

I am trying to get the outputLabel to be a label control box where the morse code will output to. I am not sure why only the first morse code character is displayed but not the rest of the code. (if I type "cat" I only get first morse code character in outlabel)
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 MorseCode
{
public partial class morseCodeForm : Form
{
public morseCodeForm()
{
InitializeComponent();
}
//Anthony Rosamilia
//Make a key,value system to translate the user text.
//Make sure usertext appears only in lower case to minimise errors.
private void convertButton_Click(object sender, EventArgs e)
{
Dictionary<char, String> morseCode = new Dictionary<char, String>()
{
{'a' , ".-"},{'b' , "-..."},{'c' , "-.-."}, //alpha
{'d' , "-.."},{'e' , "."},{'f' , "..-."},
{'g' , "--."},{'h' , "...."},{'i' , ".."},
{'j' , ".---"},{'k' , "-.-"},{'l' , ".-.."},
{'m' , "--"},{'n' , "-."},{'o' , "---"},
{'p' , ".--."},{'q' , "--.-"},{'r' , ".-."},
{'s' , ".-."},{'t' , "-"},{'u' , "..-"},
{'v' , "...-"},{'w' , ".--"},{'x' , "-..-"},
{'y' , "-.--"},{'z' , "--.."},
//Numbers
{'0' , "-----"},{'1' , ".----"},{'2' , "..----"},{'3' , "...--"},
{'4' , "....-"},{'5' , "....."},{'6' , "-...."},{'7' , "--..."},
{'8' , "---.."},{'9' , "----."},
};
string userText = inputTextBox.Text;
userText = userText.ToLower();
for (int index = 0; index < userText.Length; index++)
{
/* if (index > 0)
{
outLabel.Text = ('/').ToString();
}
*/char t = userText[index];
if (morseCode.ContainsKey(t))
{
outLabel.Text = (morseCode[t]);
}
}
}
private void clearButton_Click(object sender, EventArgs e)
{
inputTextBox.Text = "";
}
private void exitButton_Click(object sender, EventArgs e)
{
this.Close();
}
}
}

outLabel.Text = (morseCode[t]);
You're setting the Text property to a completely new value, not appending. Wouldn't it be odd if that assignment did append a string to what was already there?
You need to preserve the old value:
outLabel.Text += morseCode[t];
That, however, creates a new string every time you append. Better solution; build the string up with a StringBuilder first, i.e., a mutable string.
var sb = new StringBuilder();
for (int index = 0; index < userText.Length; index++)
{
var t = userText[index].ToLower();
string morseValue;
// no need for ContainsKey/[], use a single lookup
if (morseCode.TryGetValue(t, out morseValue))
{
sb.Append(morseValue);
}
}
outLabel.Text = sb.ToString();

Related

Multiline textbox entries not seperated

why other strings other than -ABC12 are not separated?
enter code here
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 multiline_textbox_seperation
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
String[] lines = textBox2.Text.Split(',');
List<string> List = new List<string>();
List.AddRange(lines);
for (int i = 0; i < List.Count; i++)
{
textBox1.Text += List[i] + "\r\n";
}
List<String> PossitiveList = new List<String> { };
List<String> NegativeList = new List<String> { };
for (int i = 0; i < List.Count; i++)
{
if (List[i].StartsWith("-")) { NegativeList.Add(List[i]); }
if (List[i].StartsWith("+")) { PossitiveList.Add(List[i]); }
}
listBox1.DataSource = NegativeList;
listBox2.DataSource = PossitiveList;
}
}
}
the result for the string:
string input = "-ABC12, +ABC12, -BAC12, -ACC12, +EAC12, -BBC12, -CBC12, +GABC12, +ACC12, +CBC12, +BBC12"
typed in textbox2 is:
If you look closely, you have spaces in between.
Instead of doing: List[i].StartsWith("-") or List[i].StartsWith("+"), do a:
List[i].Trim().StartsWith("-")
List[i].Trim().StartsWith("+")
I'd simplify a bit with:
private void button1_Click(object sender, EventArgs e)
{
var values = new List<string>(textBox2.Text.Split(','))
.Select(x => x.Trim()).ToList();
textBox1.Lines = values.ToArray(); // optional
var PositiveList = values.Where(x => x.StartsWith("+")).ToList();
var NegativeList = values.Where(x => x.StartsWith("-")).ToList();
listBox1.DataSource = NegativeList;
listBox2.DataSource = PositiveList;
}

C# - amend values from column1 in DaraGridView and put them in new column

I have a section of code which splits an input string into rows and outputs it into a DataGridView.
These are all populated into column 1.
I want to further split the values in column 1 into column 2 and 3 etc.
The values for column 2 and 3 need to come from column 1 NOT THE ORIGINAL INPUT.
For example:
EDIT: More example inputs
Input String :
abc12, def, 56, jkl78, mno90
Current Code:
private void Button1_Click(object sender, EventArgs e)
{
List<string> eSplit = new List<string>(eInputBox.Text.Split(new string[] { "," }, StringSplitOptions.None));
DataGridViewTextBoxColumn eOutputGrid = new DataGridViewTextBoxColumn();
eOutputGrid.HeaderText = "Section";
eOutputGrid.Name = "Section";
eOutputDGV.Columns.Add(eOutputGrid);
foreach (string item in eSplit)
{
eOutputDGV.Rows.Add(item);
}
}
Desired Output: (if there is no value then it needs to be blank).
Section Letters Numbers
abc12 abc 12
def def
56 56
jkl78 jkl 78
mno90 mno 90
You have to add each column definition to your eOutputDGV and then to pass three parameters to each eOutputDGV.Row:
private void Button1_Click(object sender, EventArgs e)
{
List<string> eSplit = new List<string>(eInputBox.Text.Split(new string[] { "," }, StringSplitOptions.None));
DataGridViewTextBoxColumn eOutputGrid = new DataGridViewTextBoxColumn();
eOutputGrid.HeaderText = "Section";
eOutputGrid.Name = "Section";
eOutputDGV.Columns.Add(eOutputGrid);
eOutputGrid = new DataGridViewTextBoxColumn();
eOutputGrid.HeaderText = "Letters";
eOutputGrid.Name = "Letters";
eOutputDGV.Columns.Add(eOutputGrid);
eOutputGrid = new DataGridViewTextBoxColumn();
eOutputGrid.HeaderText = "Numbers";
eOutputGrid.Name = "Numbers";
eOutputDGV.Columns.Add(eOutputGrid);
foreach (string item in eSplit)
{
eOutputDGV.Rows.Add(item.Trim(), item.Trim().Substring(0, 3), item.Trim().Substring(3));
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace dgvAlphaNumbericSplit
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
dataGridView1.Rows.Clear();
dataGridView1.Rows.Add("abc12", "", "");
dataGridView1.Rows.Add("def", "", "");
dataGridView1.Rows.Add("56", "", "");
dataGridView1.Rows.Add("jkl78", "", "");
dataGridView1.Rows.Add("mno90", "", "");
}
private void Button1_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if(dataGridView1.Rows[row.Index].Cells[0].Value != null)
{
string str = dataGridView1.Rows[row.Index].Cells[0].Value.ToString();
int index = str.IndexOfAny(new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' });
string chars = "";
string nums = "";
if (index >= 0)
{
chars = str.Substring(0, index);
nums = str.Substring(index);
}
else
{
chars = str;
}
dataGridView1.Rows[row.Index].Cells[1].Value = chars;
dataGridView1.Rows[row.Index].Cells[2].Value = nums;
}
}
}
}
}
Here are the results: -
Assuming you have a list of string, you can shape it into the expected result using a linq query:
dataGridView1.DataSource = list.Select(x=>Process(x)).ToList();
And what is the Process method? It's a static method which is responsible to process the input string and convert it to the desired model, let's say you have a model like this:
public class MyModel
{
public string Letters { get; set; }
public int Numbers { get; set; }
public string Section
{
get
{
return $"{Letters}{Numbers}";
}
}
}
Then the process method is something like this:
pubic static MyModel Process(string s)
{
// some logic to extract information form `s`
return new MyModel(){ Letters = ..., Numbers = ... };
}

How do make the code display the information?

I'm trying to debug the C# code but can't find the logic error of why it's not displaying the data and no error message.
To begin with, the code was in large chunks so I then tried splitting the code into smaller methods but still unable to find the issue of where I'm going wrong.
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.IO;
namespace Drivers_license_exam
{
public partial class Form1 : Form
{
private string[] studentAnsArray = new string[20];
private string[] correctAnsArray = { "B", "D", "A", "A", "C", "A","B", "A", "C", "D", "B","C",
"D", "A", "D", "C","C", "B", "D", "A" };
public Form1()
{
InitializeComponent();
}
private void GetFile(out string fileName)
{
if (openFile.ShowDialog() == DialogResult.OK)
{
fileName = openFile.FileName;
}
else
{
fileName = "";
}
}
private void GetAndReadFile(string fileName)
{
string results;
StreamReader inputFile = File.OpenText(fileName);
while (!inputFile.EndOfStream)
{
results = inputFile.ReadLine();
studentAns.Items.Add(results);
//studentAnsArray[index] = inputFile.ReadLine();
//correctAns.Items.Add(studentAnsArray);
}
foreach (string answers in correctAnsArray)
{
correctAns.Items.Add(answers);
}
inputFile.Close();
}
private int TotCorrect()
{
int correct = 0;
for (int index = 0; index < correctAnsArray.Length; index++)
{
if (studentAnsArray[index]== correctAnsArray[index])
{
correctTxt.Text = index.ToString();
correct++;
}
}
return correct;
}
private int TotIncorrect()
{
int incorrect = 0, questNum = 1;
for (int index = 0; index < correctAnsArray.Length; index++)
{
if (studentAnsArray[index] == correctAnsArray[index])
{
incorrectAns.Items.Add("Question: " + questNum);
incorrectAns.Items.Add("Incorrect");
incorrect++;
}
}
return incorrect;
}
private bool PassedTest()
{
bool pass = false;
if (TotCorrect() >= 15)
{
passFailedTxt.Text = "Passed";
}
if (TotIncorrect() < 15)
{
passFailedTxt.Text = "Failed";
}
return pass;
}
private void displayRes_Click(object sender, EventArgs e)
{
string studentAns;
GetFile(out studentAns);
GetAndReadFile(studentAns);
TotCorrect();
TotIncorrect();
PassedTest();
}
private void exit_Click(object sender, EventArgs e)
{
this.Close();
}
private void Clear_Click(object sender, EventArgs e)
{
}
}
}
What I expected the code to do is output the following:
display the incorrect results
display pass or fail in a text box
display the total of correct and incorrect answers in a text box
The output that I'm getting from this code is:
- doesn't display the incorrect answers in the list box
- displays fail although the answers from the text and the array are correct
- doesn't display the total of correct and incorrect answers

Altering string array value with radio button

I'm having an issue with altering the value of a string array based on what radio button is selected, it's written in C# using Visual Studio 2013 professional.
Basically all that needs to happen is if the radio button called "smallCarRadBtn" is selected, then the string array call "carSize" has to hold the word "Small", and likewise for the other two radio buttons "medCarRadBtn" and "largeCarRadBtn".
At the moment it is telling me:
"Cannot implicitly convert type 'char' to 'string[]'
I have 'highlighted' the area that contains the code for this with asterisks'*'. Any help 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.IO;
namespace Assignment2
{
public partial class Form1 : Form
{
TimeSpan daysHiredIn;
DateTime startDate, endDate;
DateTime dateToday = DateTime.Today;
public static string[] names = new string[50];
public static string[] carSize = new string[50];
public static int[] cardNumb = new int[50];
public static int[] cost = new int[50];
public static TimeSpan[] daysHired = new TimeSpan[50];
public static int entryCount = 0, cardNumbIn, carFee = 45, intDaysHired;
public Form1()
{
InitializeComponent();
smallCarRadBtn.Checked = true;
}
private void confirmBtn_Click(object sender, EventArgs e)
{
if (entryCount >= 50)
{
MessageBox.Show("Arrays are Full");//if array is full
}
else if (nameTxtBox.Text == "")
{
MessageBox.Show("You must enter a name");//Nothing entered
}
else if (!int.TryParse(cardNumbTxtBox.Text, out cardNumbIn))
{
MessageBox.Show("You must enter an integer number");
cardNumbTxtBox.SelectAll();
cardNumbTxtBox.Focus();
return;
}
else if (hireStartDatePicker.Value < dateToday)
{
MessageBox.Show("You cannot enter a date earlier than today");
}
else if (hireEndDatePicker.Value < dateToday)
{
MessageBox.Show("You cannot enter a date earlier than today");
}
else
{
*******************************************************************************************
if (smallCarRadBtn.Checked)
{
carSize = ("small"[entryCount]);
}
else if (MedCarRadBtn.Checked)
{
carSize = ("Medium"[entryCount]);
}
else if (largeCarRadBtn.Checked)
{
carSize = ("Large"[entryCount]);
}
*******************************************************************************************
names[entryCount] = nameTxtBox.Text;
cardNumb[entryCount] = cardNumbIn;
endDate = (hireEndDatePicker.Value);
startDate = (hireStartDatePicker.Value);
daysHiredIn = (endDate - startDate);
cost[entryCount] = (carFee * daysHiredIn);
daysHired[entryCount] = daysHiredIn;
entryCount++;
nameTxtBox.SelectAll();
nameTxtBox.Focus();
}
}
private void viewBtn_Click(object sender, EventArgs e)
{
for (entryCount = 0; entryCount < 50; entryCount++)
{
listBox1.Items.Add(names[entryCount]+"\t"+daysHired[entryCount].Days.ToString());
}
}
}
}
carSize is an array of strings but you are trying to assign it a char:
carSize = ("small"[entryCount]);
Here the "small" is a string, and "small"[entryCount] returns the character at the index entryCount
You should change carSize to char[] if you want to stores characters, and set the elements using indexer instead of assigning the array directly. Or if you want to store the text + entryCount then you should concatenate strings:
carSize[index] = "small" + entryCount;
Or if you just want to set carSize[entryCount] then:
carSize[entryCount] = "small";

Find certain text in PDF, then return page number found on to another section NOTE: Uses Docotic.pdf

In the following code, the user will input a search string (barcodedata). That string will then be truncated to the first 5 characters, and used as the jobnumber. The jobnumber, is also the name of the pdf I will be scanning for the barcodedata.
What I would like, is for the 'Find it' button to execute the below code, then return the value found to startpagedata.
I can't tell if the program just isn't actually scanning the PDF for the search string, or if the value simply isn't returning to the program.
using BitMiracle.Docotic.Pdf;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;
using Acrobat;
namespace BarCodeReader
{
public partial class Form1 : Form
{
public string stringsToFind;
public string pathtofile;
public Form1()
{
InitializeComponent();
}
private void barcodedata_TextChanged(object sender, EventArgs e)
{
stringsToFind=barcodedata.Text;
pathtofile = "C:\\" + StringTool.Truncate(barcodedata.Text, 5) + ".pdf";
jobnumberdata.Text = StringTool.Truncate(barcodedata.Text, 5);
}
private void label4_Click(object sender, EventArgs e)
{
}
private void jobnumberdata_TextChanged(object sender, EventArgs e)
{
jobnumberdata.Text = jobnumberdata.Text.TrimStart('0');
Console.WriteLine(jobnumberdata.Text);
}
private void startpagedata_TextChanged(object sender, EventArgs e)
{
Console.WriteLine(startpagedata.Text);
}
private void piecesdata_TextChanged(object sender, EventArgs e)
{
}
private void FindIt_Click(object sender, EventArgs e)
{
PdfDocument pdf = new PdfDocument(pathtofile);
for (int i = 0; i < pdf.Pages.Count; i++)
{
string pageText = pdf.Pages[i].GetText();
int count = 0;
int lastStartIndex = pageText.IndexOf(stringsToFind, 0, StringComparison.CurrentCultureIgnoreCase);
while (lastStartIndex != -1)
{
count++;
lastStartIndex = pageText.IndexOf(stringsToFind, lastStartIndex + 1, StringComparison.CurrentCultureIgnoreCase);
}
if (count != 0)
startpagedata.Text = Convert.ToString(lastStartIndex);
}
}
}
public static class StringTool
{
/// <summary>
/// Get a substring of the first N characters.
/// </summary>
public static string Truncate(string source, int length)
{
if (source.Length > length)
{
source = source.Substring(0, length);
}
return source;
}
/// <summary>
/// Get a substring of the first N characters. [Slow]
/// </summary>
public static string Truncate2(string source, int length)
{
return source.Substring(0, Math.Min(length, source.Length));
}
}
}
What is your problem with this code? If FindIt_Click is not executed on click then probably you don't associate it with the "Find it" button.
The code in FindIt_Click looks quite correct except several things:
It may not do what you expect. It returns the last index in the text of the last page where the search string was found. But may be you expect the index of the last page where the search string was found?
You may use pageText.LastIndexOf method to quickly find lastStartIndex.
Don't forget to Dispose PdfDocument instance. E.g. use using keyword:
using (PdfDocument pdf = new PdfDocument(pathtofile))
{
...
}
In order to use Docotic.pdf you can use Acrobat.dll to find the current page number. First of all open the pdf file and search the string using
Acroavdoc.open("Filepath","Temperory title")
and
Acroavdoc.FindText("String").
If the string found in this pdf file then the cursor moved into the particular page and the searched string will be highlighted. Now we use Acroavpageview.GetPageNum() to get the current page number.
Dim AcroXAVDoc As CAcroAVDoc
Dim Acroavpage As AcroAVPageView
Dim AcroXApp As CAcroApp
AcroXAVDoc = CType(CreateObject("AcroExch.AVDoc"), Acrobat.CAcroAVDoc)
AcroXApp = CType(CreateObject("AcroExch.App"), Acrobat.CAcroApp)
AcroXAVDoc.Open("File path", "Original document")
AcroXAVDoc.FindText("String is to searched", True, True, False)
Acroavpage = AcroXAVDoc.GetAVPageView()
Dim x As Integer = Acroavpage.GetPageNum
MsgBox("the string found in page number" & x)

Categories