I am a noob, I am stuck on this code.
I am taking input from user in a textbox and saving it in a string. Then I want to run a loop until the string ends and I put if condition for different characters....
string que;
que = textBlock1.Text;
while (!que[i].Equals('\0'))
{
int res;
if (int.TryParse(que[i].ToString(), out res) || que[i].ToString() == "x" || que[i].ToString() == "/" || que[i].ToString() == "^")
{
f[j] = f[j] + que[i].ToString();
}
if (que[i].ToString() == "+" || que[i].ToString() == "-")
j++;
i++;
}
Can someone please guide me? What should I do??
Use:
textBlock1.Text.Lenght
That way you can know the length of the string.
Have you tried foreach(char c in que){ /*your code*/ } ?
If you want to just run through the loop until the end of the string, a simple condition like this should do:
int i = 0;
while (i < que.Length )
{
// Your code
}
Related
when I am entering input like this "12312.-.-.,," program is not working or giving any error
string c = textBox1.Text;
if (c.Contains(".") || c.Contains("-") || c.Contains("1") || c.Contains("2") || c.Contains("3") || c.Contains("4") || c.Contains("5") || c.Contains("6") || c.Contains("7") || c.Contains("8") || c.Contains("9") || c.Contains("0"))
{
if (c.IndexOf('-') == 0 || c.IndexOf('.')==c.Length-1)
{
c = c.Substring(1, c.Length - 1);
if (c.Contains("-") || c.Contains("."))
{
MessageBox.Show("Error");
}
}
}
else { textBox1.Clear(); }```
You really should check input values with regular expressions:
Regex rgx = new Regex(#"^-?\d+(\.\d+)?$");
string test1 = "-123.23";
string test2 = "12312.-.-.,,";
if (!rgx.IsMatch(test1)) MessageBox.Show("Error in test1");
if (!rgx.IsMatch(test2)) MessageBox.Show("Error in test2");
The code doesnt enter your check for string to "not" start with '0' or end with '.' i assume?
if (!(c.IndexOf('-') == 0 || c.IndexOf('.')==c.Length-1))
So I've just been making a basic little calculator made up of buttons and a textbox(tbxSum).
The problem I'm having is that if an invalid sum is input I want my catch block to pick it up(which it does) and replace what's in the textbox with the most recent result in the calculator(which it doesn't).
So say I say:
3+3=6
My calculator will now put 6 in the textbox for the next sum.
So then say I did:
6//3
It's invalid which the calculator picks up, but I want the textbox value to return to 6 from the previous sum.
This is what I've tried:
var myButton = (Button)sender;
if (myButton.Content.ToString() == "=")
{
DataTable dt = new DataTable();
string s = tbxSum.Text;
string result = "";
if (s.Contains("("))
{
s = s.Replace("(", "*(");
}
try
{
var v = dt.Compute(s, "");
tbkSum.Text = s + "=" + v.ToString();
tbxSum.Text = v.ToString();
}
catch
{
MessageBox.Show("Invalid Sum");
tbxSum.Text = result;
}
}
I also have a textblock(tbkSum) which shows the previous sum so I thought maybe I could take everything in there to the right of the equals sign but I have no idea how to do that.
class Calculate(){
private boolean lastGoodValueSet = false;
private int lastGoodValue = 0;
void buttonFunction(){
if (myButton.Content.ToString() == "=")
{
//Your code
try
{
var v = dt.Compute(s, "");
tbkSum.Text = s + "=" + v.ToString();
lastGoodValue = v;
lastGoodValueSet = true;
}
catch
{
MessageBox.Show("Invalid Sum");
tbxSum.Text = result;
if (lastGoodValueSet)
tbxSum.Text = lastGoodValue;
}
}
}
}
This is an example set of code you could use, it's a simple value that you have to store to say if a good computation has been done and if so, at the point of error we want to go back to the computation. Hope that helps! You'll want to put some kind of message to the user, so they know there was an error though.
We have to do this, as at the point of the user pressing the equals button, the value has already changed inside tbkSum, we need it before the user has changed the value, so the best time to grab it is at the point when we update the tbkSum text value at a successful calculation
This is also assuming you do not create a new instance of the Calculate class each time you do your computation. Otherwise you'd need to store the number somewhere else
EDIT
The other way to fix this issue is to instead prevent the duplicate in the first place, I read from your other comments that you control what goes into the text box by buttons on the application. Assuming all buttons go through the same method of buttonFunction() then you could do:
private char[] buttonChars = {'/','*', '+'/*e.t.c*/}
void buttonFunction(){
string buttonPressedStr = myButton.Content.ToString();
char buttonPressed = buttonPressedStr[0];
int pos = Array.IndexOf(buttonChars , buttonPressed);
if (pos > -1)
{
if (tbxSum.Text.Length > 0){
char last = tbxSum.Text[tbxSum.Text.Length - 1];
pos = Array.IndexOf(buttonChars , last);
}
else
pos = 0;
if (pos > -1){
tbkSum.Text += buttonPressedStr;
}
}
There are cleaner ways to do this, but it's an example of how you could have prevented your issue in the first place. Some explanation:
buttonChars is an array of your different button types that would be appended to your text in the box, an example is +, -, and so on
First it checks if the button pressed was in your collection of specified buttonChars
If so, we have to check what the last thing added to the tbxSum was
If the last thing added to tbxSum was again found in the buttonChars array, we don't want to append a string
Otherwise, if the tbxSum was empty or had another character at the end, we can append our character
You can store the old value in a variable declard outside the try block and use this variable in your catch block again:
string oldSumValue = tbxSum.Text;
try
{
// your code
}
catch
{
tbxSum.Text = oldSumValue ;
MessageBox.Show("Invalid Sum");
}
Alternatively I've come up with this to prevent there being:
A)Duplicate of '*' or '/'
B)Sum starting with '*' or '/'
public MainWindow()
{
InitializeComponent();
if (tbxSum.Text == "")
{
btnDiv.IsEnabled = false;
btnMult.IsEnabled = false;
}
}
protected void btnSumClick(object sender, EventArgs e)
{
btnDiv.IsEnabled = true;
btnMult.IsEnabled = true;
var myButton = (Button)sender;
int pos = tbxSum.Text.Length;
if (pos > 0)
{
if ((tbxSum.Text[pos - 1] == '/' || tbxSum.Text[pos - 1] == '*') &&
(myButton.Content.ToString() == "/" || myButton.Content.ToString() == "*"))
{
int location = tbxSum.Text.Length - 1;
tbxSum.Text = tbxSum.Text.Remove(location, 1);
}
}
}
I am currently developing an Excel reader, that is inserting into a database. Things have been going smoothly untill I stumbled on some variation in the Excel sheet.
100 rows, somehwere in the middle of the sheet, have a different style than the rest of the sheet, and my substring fails.
To give some clarification here are how they usually look:
DMK.2003602
DMK.4663501
DMK.3307301
etc.
To get the number I use a substring on the column in the row like this
row[12].ToString().Substring(4).ToString());
Pretty simple. However at some point it changes to this
82AVG.A410201
And my substring does not work and I get a type error when insertion to the database.
Any clue on how to handle such a change during the loop of rows?
Here is my loop,
foreach (var row in albums)
{
if (row.ItemArray.Length == 33 && row.ItemArray[0].ToString() != ""
&& row.ItemArray[1].ToString() != ""
&& row.ItemArray[2].ToString() != ""
&& row.ItemArray[3].ToString() != ""
&& row.ItemArray[4].ToString() != ""
&& row.ItemArray[5].ToString() != "")
{
Order ord = new Order(
1,
maxTrNo +1,
row[6].ToString().Substring(row[6].ToString().Length - 5).ToString(),
1,
numVal,
row[13].ToString(),
"",
row[12].ToString().Substring(4).ToString()); //This is where it fails
orders.Add(ord);
maxTrNo++;
}
}
Use string.IndexOf('.') to get the characters after the dot,
string s = row[i].ToString();
string afterDot = s.Substring(s.IndexOf('.' + 1));
To handle the case when there is no dot
int dot = s.IndexOf('.');
string afterDot = dot == -1 ? string.Empty : s.Substring(dot + 1);
Just to get the part of string after '.', you can use (assuming you want empty string in cases of 'DMK2003602' or 'DMK2003602.')
var str = "DMK.2003602";
var subStr = str.IndexOf('.') > -1 && str.IndexOf('.') < str.Length -1 ? str.Substring(str.IndexOf('.') + 1) : string.Empty;
But for the database insertion error, there might be some other reason.
im working on a editor and i want to replace last comment after the intellisense appears .
further more heres the senario,
i got richtextbox(rtb) which served as the code-editor, and a hidden combobox(lb) which served as the intellisense . everytime i type words from richtextbox(rtb), sample i type "as", combobox will appear (like a intellisense) with keywords that starts from "as" .
all functions are working now except for after i select an item from combobox
sample string(combo box items): asd, asdf, asdfg .
then suppose to be i type as in richtextbox then i select 'asd' from combobox, then when i press enter the output would be:
as asd
instead of:
as (only)
further more heres my keyevents code:
void lb_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
lb.Visible = false;
lb.Items.Clear();
}
if (e.KeyCode == Keys.Enter)
{
int start = 0, end = 0;
String line = rtb.Text.Substring(start, start - end);
int index = start;
string comment = line.Substring(index);
rtb.SelectedText = lb.SelectedText.ToString();
}
}
note: i just write:
rtb.SelectedText = comment + " " + lb.SelectedText.ToString();
for now to see some other function but that line was i the one i want to fix . also i even try:
rtb.SelectedText = comment - lb.SelectedText.ToString();
but it says Operator '-' cannot be applied to operands of type 'string' and 'string'
really thanks for the help in advance .
parameter:
if (token == "letterA" || token.StartsWith("Ab") || token.StartsWith("ab") || token.StartsWith("AB"))
{
int length = line.Length - (index - start);
string commentText = rtb.Text.Substring(index, length);
rtb.SelectionStart = index;
rtb.SelectionLength = length;
lb.Visible = true;
KeyWord keywordsHint = new KeyWord();
foreach (string str in keywordsHint.ab)
{
lb.Items.Add(str);
lb.SelectedIndex = lb.FindStringExact(str);
}
//token.Replace(lb.SelectedText,"");
}
I think this question/answer might be the problem:
ComboBox.SelectedText doesn't give me the SelectedText
Try using:
rbt.SelectedText = comment + " " + lb.Text
instead of SelectedText.
I'm trying to use the following and can't wrap my head around why this IndexOf method isn't working.
foreach (string s in regKey.GetSubKeyNames())
{
RegistryKey sub = Registry.LocalMachine.OpenSubKey(string.Format(#"{0}\{1}", _UninstallKey64Bit, s), false);
if (sub.ValueCount > 0)
{
values = sub.GetValueNames();
if (IndexOf(values, "DisplayName") != -1)
{
string name = (sub.GetValue("DisplayName") != null) ? sub.GetValue("DisplayName").ToString() : string.Empty;
if (!string.IsNullOrEmpty(name) && (name.ToLower() == appName.ToLower()))
if (IndexOf(values, "UninstallString") != -1)
{
uninstallValue = (sub.GetValue("UninstallString") != null) ? sub.GetValue("UninstallString").ToString() : string.Empty;
break;
}
}
}
}
Can anyone lend me a hand with this?
Correct syntax is:
if (Array.IndexOf(values, "DisplayName") != -1)
GetValueNames() returns a string array so you probably are looking for:
if (values.Contains("DisplayName"))
Try
if (values.Any(v => v == "DisplayName")) )
{
...
}
Try changing -
if (IndexOf(values, "UninstallString") != -1)
to
if (Array.IndexOf(values, "UninstallString") != -1)
Try this instead of just IndexOf.
Array.IndexOf(values, "DisplayName")