I am working on a Reverse polish notation calculator. I created a method that will take care of the calculations but there are three lines in my code that are causing an error. After every = an operation is performed and then displayed. I am trying to grab the string from TxtInputBox and convert to integers but it always shows the catch message Please check the input. Then nothing gets calculated or display. I am sure that my first if statement will check for actual integers and avoid the characters. My ultimate goal is to input a formula in rpn format and have the result display in the multiline textbox.
Sample Input 5 6 -=
Code
namespace rpncalc
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void RPNCalc(TextBox TxtBoxInputbox, TextBox TxtBoxOutputbox)
{
Stack<int> stackone = new Stack<int>();
stackone.Clear();
string[] inputarray = TxtBoxInputbox.Text.Split();
int end = inputarray.Length - 1;
int numinput;
int i = 0;
do
{
if(inputarray[i] != "=" && inputarray[i] != "+" && inputarray[i] != "-" && inputarray[i] != "*" && inputarray[i] != "/")
{
try
{
numinput = Convert.ToInt32(inputarray[i]);
stackone.Push(numinput);
}
catch
{
MessageBox.Show("Please check the input");
}
}
else if (inputarray[i]== "+")
{
try
{
int store1 = stackone.Pop();
int store2 = stackone.Pop();
stackone.Push(store2 + store1);
}
catch
{
}
}
else if (inputarray[i]== "-")
{
try
{
int store1 = stackone.Pop();
int store2 = stackone.Pop();
stackone.Push(store2 + store1);
}
catch
{
}
}
else if (inputarray[i]== "+")
{
try
{
int store1 = stackone.Pop();
int store2 = stackone.Pop();
stackone.Push(store2 + store1);
}
catch
{
}
}
else if (inputarray[i]== "*")
{
try
{
int store1 = stackone.Pop();
int store2 = stackone.Pop();
stackone.Push(store2 + store1);
}
catch
{
}
}
else if (inputarray[i]== "/")
{
try
{
int store1 = stackone.Pop();
int store2 = stackone.Pop();
stackone.Push(store2 + store1);
}
catch
{
}
}
}
while(i < end && inputarray[i]!= "=" && stackone.Count != 0);
string txtout = TxtInputBox + " " + stackone.Pop().ToString() + Environment.NewLine;
TxtOutputBox.AppendText(txtout);
TxtInputBox.Clear();
}
private void Btn_Calc_Click(object sender, EventArgs e)
{
RPNCalc(TxtInputBox, TxtOutputBox);
}
}
}
The Split command, with no argument, is splitting the string on spaces and other whitespace.
There is no space in the input between -= so it is treated as one token that doesn't match the tests in the if statement.
Original answer incorrectly suggested that Split with no argument was splitting into individual characters.
What are you doing to increment i after each iteration of your do loop? I tried out your code and it seems like i is never incremented. Also, when you catch and run
catch
{
MessageBox.Show("Please check the input");
}
You could perhaps change it to:
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
so you could be sure of just what you're catching, and why.
Edit:
Here's my version of your code, now working correctly:
i is incremented in each iteration
Fixed the typo in the minus, multiplication and division operators that made them do addition instead
Removed the redundant addition operator
namespace rpncalc {
public partial class Form1 : Form {
public Form1 () {
InitializeComponent();
}
private void RPNCalc (TextBox TxtBoxInputbox, TextBox TxtBoxOutputbox) {
Stack<int> stackone = new Stack<int>();
stackone.Clear();
string[] inputarray = TxtBoxInputbox.Text.Split();
int end = inputarray.Length - 1;
int numinput;
int i = 0;
do {
if (inputarray[i] != "=" && inputarray[i] != "+" && inputarray[i] != "-" && inputarray[i] != "*" && inputarray[i] != "/") {
try {
numinput = Convert.ToInt32(inputarray[i]);
stackone.Push(numinput);
} catch (Exception e) {
MessageBox.Show(e.ToString());
}
} else if (inputarray[i] == "+") {
try {
int store1 = stackone.Pop();
int store2 = stackone.Pop();
stackone.Push(store2 + store1);
} catch {
}
} else if (inputarray[i] == "-") {
try {
int store1 = stackone.Pop();
int store2 = stackone.Pop();
stackone.Push(store2 - store1);
} catch {
}
} else if (inputarray[i] == "*") {
try {
int store1 = stackone.Pop();
int store2 = stackone.Pop();
stackone.Push(store2 * store1);
} catch {
}
} else if (inputarray[i] == "/") {
try {
int store1 = stackone.Pop();
int store2 = stackone.Pop();
stackone.Push(store2 / store1);
} catch {
}
}
}
while (i++ < end && inputarray[i] != "=" && stackone.Count != 0);
string txtout = TxtInputBox.Text + " " + stackone.Pop().ToString() + Environment.NewLine;
TxtOutputBox.AppendText(txtout);
TxtInputBox.Clear();
}
private void Btn_Calc_Click (object sender, EventArgs e) {
RPNCalc(TxtInputBox, TxtOutputBox);
}
}
}
Related
This question already has answers here:
C# - Read in a large (150MB) text file into a Rich Text Box
(2 answers)
Closed 1 year ago.
I have a large text files for example 39000 lines and above , i want to load it into richtextbox , using normal way like this:
Richtextbox1.Text=File.ReadAllLines(file);
or
Richtextbox1.LoadFile(...);
it take long time and freeze the UI even i use BackgroundWorker, so i decide to split file into parts each part is 1000 lines and append them to the richtextbox , i mean i read 1000 lines from file into string and then append it to the richtextbox, here is my code:
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
StreamReader reader = null;
try
{
//
int ProgressPercentage = 0;
//enable stop Correct button
BTN_Send_Ref.Invoke((MethodInvoker)(() =>
{
BTN_Send_Ref.Enabled = true;
}));
string[] Lines = File.ReadAllLines(InputTextFile);
//MessageBox.Show("Lines : " + Lines.Length);
int i= 0;
int j = 0;
string LinesCollection = "";
while (true)
{
if (worker.CancellationPending)
{
if (reader != null)
{
reader.Close();
reader = null;
}
e.Cancel = true;
//cancel backgroundworker
return;
}
LinesCollection = "";
if (i > Lines.Length ||
j >= Lines.Length)
{
break;
}
i += 1000;
if (i >= Lines.Length)
{
i = Lines.Length ;
}
while ( j < i)
{
if (worker.CancellationPending)
{
if (reader != null)
{
reader.Close();
reader = null;
}
e.Cancel = true;
//cancel backgroundworker
return;
}
if (j < Lines.Length)
{
if (LinesCollection == "")
{
LinesCollection = Lines[j];
}
else
{
LinesCollection += Environment.NewLine + Lines[j];
}
}
ProgressPercentage = (int)Math.Round((((double)j) / Lines.Length) * 100);
if (ProgressPercentage < 100)
{
//report progress
worker.ReportProgress(ProgressPercentage);
}
ProgressPercentage++;
j++;
}
RichTXT_OutText_Ref.Invoke((MethodInvoker)(() =>
{
RichTXT_OutText_Ref.AppendText(LinesCollection +Environment.NewLine);
}));
LBL_CountOfChars_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfChars_Ref.Text = "(" + RichTXT_OutText_Ref.Text.Length + ") Char";
LBL_CountOfChars_Ref.Update();
}));
LBL_CountOfLines_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfLines_Ref.Text = "(" + RichTXT_OutText_Ref.Lines.Length + ") Line";
LBL_CountOfLines_Ref.Update();
}));
}
/*int Tmp_Count = 0;
if (RichTXT_OutText_Ref.InvokeRequired)
{
RichTXT_OutText_Ref.Invoke((MethodInvoker)(() =>
{
RichTXT_OutText_Ref.LoadFile(InputTextFile, RichTextBoxStreamType.PlainText);
}));
}
else
{
RichTXT_OutText_Ref.LoadFile(InputTextFile, RichTextBoxStreamType.PlainText);
}
LBL_CountOfChars_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfChars_Ref.Text = "(" + RichTXT_OutText_Ref.Text.Length + ") Char";
LBL_CountOfChars_Ref.Update();
}));
LBL_CountOfLines_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfLines_Ref.Text = "(" + RichTXT_OutText_Ref.Lines.Length + ") Line";
LBL_CountOfLines_Ref.Update();
}));
*/
/*reader= File.OpenText(InputTextFile);
string Line = "";
int LinesCounter = 0;
while ((Line = reader.ReadLine()) != null)
{
if (worker.CancellationPending)
{
if (reader != null)
{
reader.Close();
reader = null;
}
e.Cancel = true;
//cancel backgroundworker
return;
}
if(LinesCounter >0 && LinesCounter <= 1000)
{
RichTXT_OutText_Ref.Invoke((MethodInvoker)(() =>
{
RichTXT_OutText_Ref.AppendText(LinesCollection);
}));
LinesCollection = "";
LinesCounter = 0;
}
else
{
if (LinesCollection == "")
{
LinesCollection= Line;
}
else
{
LinesCollection += Environment.NewLine + Line;
}
}
LBL_CountOfChars_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfChars_Ref.Text = "(" + RichTXT_OutText_Ref.Text.Length + ") Char";
LBL_CountOfChars_Ref.Update();
}));
LBL_CountOfLines_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfLines_Ref.Text = "(" + RichTXT_OutText_Ref.Lines.Length + ") Line";
LBL_CountOfLines_Ref.Update();
}));
//calculate progress value
ProgressPercentage = (int)Math.Round((((double)PercentageCounter) / Lines.Length) * 100);
if (ProgressPercentage < 100)
{
//report progress
worker.ReportProgress(ProgressPercentage);
}
TempCount++;
PercentageCounter++;
Tmp_Count++;
}
*/
if (reader != null)
{
reader.Close();
reader = null;
}
//disable Correct button because
//we are out of loop
if (BTN_Send_Ref != null)
{
//we call this btn Correct
//from another thread
//so we must use Invoke
BTN_Send_Ref.Invoke((MethodInvoker)(() =>
{
BTN_Send_Ref.Enabled = false;
}));
}
}
catch (Exception ex)
{
if (reader != null)
{
reader.Close();
reader = null;
}
MessageBox.Show(ex.Message+"\n"+ex.StackTrace.ToString());
throw ex;
}
}
the problem is that the code work fine with some file say less than 1000 but when i use large file has size greater than 1000,the count of lines is less than actual file lines
for example i attach text file
my text file
which has size 62077 but the after use my code the richtextbox lines is 62028, and count of characters also is less the actual count of characters of file, but the start and the end of content in richtextbox and file are the same, i do not know where is the error, all i want is to read text file , combine every 1000 lines in one string append it the richtextbox repeat the operation until end of file content.
i do not want to use Richtextbox1.LoadFile(...)and Richtextbox1.Text=File.ReadAllLines(file); because they freeze and hung the UI this happen when using large files more than 39000 lines,
i want to know what is the wrong with code?why dose not get right result?
i hope you help me.
i use this code and it work fine:
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
try
{
//
int ProgressPercentage = 0;
BTN_Send_Ref.Invoke((MethodInvoker)(() =>
{
BTN_Send_Ref.Enabled = true;
}));
string[] Lines = File.ReadAllLines(InputTextFile);
string LinesCollection = "";
for(int x = 0; x < Lines.Length; x++)
{
if (worker.CancellationPending)
{
e.Cancel = true;
//cancel backgroundworker
return;
}
LinesCollection += Lines[x] + Environment.NewLine;
if (x>0 && x % 1000 == 0)
{
RichTXT_OutText_Ref.Invoke((MethodInvoker)(() =>
{
RichTXT_OutText_Ref.AppendText(LinesCollection );
}));
LinesCollection = "";
LBL_CountOfChars_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfChars_Ref.Text = "(" + RichTXT_OutText_Ref.Text.Length + ") Char";
LBL_CountOfChars_Ref.Update();
}));
LBL_CountOfLines_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfLines_Ref.Text = "(" + RichTXT_OutText_Ref.Lines.Length + ") Line";
LBL_CountOfLines_Ref.Update();
}));
}
if(x==Lines.Length-1 && LinesCollection != "")
{
RichTXT_OutText_Ref.Invoke((MethodInvoker)(() =>
{
RichTXT_OutText_Ref.AppendText(LinesCollection.TrimEnd(Environment.NewLine.ToCharArray()) );
}));
LinesCollection = "";
LBL_CountOfChars_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfChars_Ref.Text = "(" + RichTXT_OutText_Ref.Text.Length + ") Char";
LBL_CountOfChars_Ref.Update();
}));
LBL_CountOfLines_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfLines_Ref.Text = "(" + RichTXT_OutText_Ref.Lines.Length + ") Line";
LBL_CountOfLines_Ref.Update();
}));
}
ProgressPercentage = (int)Math.Round((((double)x) / Lines.Length) * 100);
if (ProgressPercentage < 100)
{
//report progress
worker.ReportProgress(ProgressPercentage);
}
}
//disable Correct button because
//we are out of loop
if (BTN_Send_Ref != null)
{
BTN_Send_Ref.Invoke((MethodInvoker)(() =>
{
BTN_Send_Ref.Enabled = false;
}));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message+"\n"+ex.StackTrace.ToString());
throw ex;
}
}
i use the Asynchronous socket Client event to receive message from server.
i receive message from client DataIn(my Event Name) and add to list box ,but not happen to show on UI!
protected void WebSocketClientControl1_OnChatNotification(List < SocketUi > sender) {
ClientScript.RegisterStartupScript(GetType(), "hwa", "javascript:__doPostBack('WebSocketClientControl1','')", true);
}
i cant use the (Response.Redirect & Server.Transfer).
this 2 function have error run time.
i call the javaScript function to show message , not happen on screen.
its my Socket code
public delegate void OnChatNotification(List<SocketUi> sender);
public class WebSocketClientControl : System.Web.UI.Control, IPostBackDataHandler
{
public static ClientService _internalClientService = new ClientService(DServerConfig.ServerAddress.ToString(),
DServerConfig.ServerSoketPort);
public event OnChatNotification OnChatNotification = delegate { };
public WebSocketClientControl()
{
_internalClientService.OnChat += _internalClientService_OnChat;
}
public void Connect(long userID, SocketEnums.EntityType usertype, string username, string key)
{
_internalClientService.Connect(userID, usertype, username, key);
}
private void _internalClientService_OnChat(List<SocketUI.SocketUi> sender)
{
if (OnChatNotification != null)
OnChatNotification(sender);
}
public bool LoadPostData(string postDataKey, NameValueCollection postCollection)
{
String presentValue = postDataKey;
String postedValue = postCollection[postDataKey];
if (presentValue == null || !presentValue.Equals(postedValue))
{
return true;
}
return false;
}
public void RaisePostDataChangedEvent()
{
}
}
its my ui Code
private void WebSocketClientControl1_OnChatNotification(List<SocketUI.SocketUi> sender)
{
foreach (SocketUi socketUi in sender)
{
switch (socketUi.DSocketType)
{
case SocketEnums.DSocketType.Chat:
foreach (SocketUI.tb_Chat chatUi in socketUi.Chats)
{
for (int i = 0; i < ASPxPageControl1.TabPages.Count; i++)
{
if (ASPxPageControl1.TabPages[i].Name == "uxTabPage_" + _channels[i].ID.ToString())
{
switch (chatUi.ChatMessegeType)
{
case (int)Enums.ChatMessegeType.Message:
SetNewMessageOnUi(HelperD.UiChat_To_Tb_Chat(chatUi));
break;
case (int)Enums.ChatMessegeType.Readed:
break;
case (int)Enums.ChatMessegeType.OnLinedUser:
break;
case (int)Enums.ChatMessegeType.OffLinedUser:
break;
case (int)Enums.ChatMessegeType.JoinChannle:
case (int)Enums.ChatMessegeType.LeftChannle:
GetUserChannel(chatUi.ChannelID.ID);
break;
case (int)Enums.ChatMessegeType.TypingUser:
for (int j = 0; j < ASPxPageControl1.TabPages[i].Controls.Count; j++)
{
if (ASPxPageControl1.TabPages[i].Controls[j] is System.Web.UI.WebControls.Label &&
ASPxPageControl1.TabPages[i].Controls[j].ID ==
"uxLabel_Status" + ASPxPageControl1.TabPages[i].DataItem.ToString())
{
System.Web.UI.WebControls.Label uxLabel_StatusTemp = new System.Web.UI.WebControls.Label();
uxLabel_StatusTemp = (System.Web.UI.WebControls.Label)ASPxPageControl1.TabPages[i].Controls[j];
uxLabel_StatusTemp.Text = " درحال تایپ " + socketUi.UserName + "...";
// timer1.Start();
}
}
break;
}//End For
// listBox_Message.Items.Add("Me:=>" + chatUi.Message + "\n\r");
}
}
}//End For
break;
}
}
}
private void SetNewMessageOnUi(UiSideLanguage.Database.Chat.tb_Chat item)
{
ASPxTextBox_Message.Text = "";
for (int i = 0; i < ASPxPageControl1.TabPages.Count; i++)
{
for (int j = 0; j < ASPxPageControl1.TabPages[i].Controls.Count; j++)
{
if (ASPxPageControl1.TabPages[i].Controls[j] is System.Web.UI.WebControls.ListBox && ASPxPageControl1.TabPages[i].Controls[j].ID == "uxListView_Chat" + ASPxPageControl1.TabPages[i].DataItem.ToString())
{
System.Web.UI.WebControls.ListBox userListView = (System.Web.UI.WebControls.ListBox)ASPxPageControl1.TabPages[i].Controls[j];
System.Web.UI.WebControls.ListItem listViewItemTemp = new System.Web.UI.WebControls.ListItem();
if (item.AddUser.ID == Language.CacheEntity.CurrentUser.ID)
{
listViewItemTemp.Text = " :من " + item.Message;
// listViewItemTemp.ForeColor = Color.DarkCyan;
}
else
{
listViewItemTemp.Text = item.AddUser.UserName + " : " + item.Message;
// listViewItemTemp.ForeColor = Color.DarkRed;
}
listViewItemTemp.Value = item.MessageFlagID.ToString();
System.Web.UI.WebControls.ListItem isHaveChatItem = null;
foreach (System.Web.UI.WebControls.ListItem chatitemListView in userListView.Items)
{
if (Language.HelperD.GetLong(chatitemListView.Value) == item.MessageFlagID)
{
isHaveChatItem = chatitemListView;
break;
}
}
if (isHaveChatItem != null)
{
if (item.AddUser.ID == Language.CacheEntity.CurrentUser.ID)
{
isHaveChatItem.Text = " :من " + item.Message;
// isHaveChatItem.ForeColor = Color.DarkCyan;
}
else
{
isHaveChatItem.Text = item.ToUser.UserName + " : " + item.Message;
// isHaveChatItem.ForeColor = Color.DarkRed;
}
isHaveChatItem.Value = item.MessageFlagID.ToString();
}
else
{
userListView.Items.Add(listViewItemTemp);
}
}
}
}
}
This function for Update UI >>> SetNewMessageOnUi
I Create Objects on Runtime.
this code is worked
userListView.Items.Add(listViewItemTemp);
and ListView Have Item But On UI Not set.
all objects in the UpdatePanle
I'm having a problem on an assignment, I can't clear the array. Also in my MessageBox when it displays the scores I get a zero as the first number no matter what I do. I can't figure out what to change so zero is not the first element.
public partial class Form1 : Form
{
int scoreTotal = 0;
int scoreCount = 0;
decimal average = 0;
int[] scoreTotalArray = new int[1];
public Form1()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
if (IsValidData())
{
Int32 score = Convert.ToInt32(txtScore.Text);
scoreTotalArray[scoreCount] = score;
Array.Resize(ref scoreTotalArray, scoreTotalArray.Length + 1);
scoreTotal += score; //accumulator
scoreCount++; //counter
average = scoreTotal / (decimal)scoreCount;//average
txtScoreCount.Text = scoreCount.ToString();//display in score count txtbox
txtScoreTotal.Text = scoreTotal.ToString(); //display in score total txtbox
txtAverage.Text = average.ToString("n2"); //display in average text box
txtScore.Clear();
txtScore.Focus();
}
}
catch (Exception ex) //catches all other exceptions
{
MessageBox.Show(ex.Message, ex.GetType().ToString());
}
}
public bool IsValidData()
{
return
IsPresent(txtScore, "Score:") &&
IsInt32(txtScore, "Score:") &&
IsWithinRange(txtScore, "Score:", 0, 100);
}
public bool IsPresent(TextBox textBox, string name)
{
if (textBox.Text == "")
{
MessageBox.Show(name + " is a required field, please enter a number between 0 and 100.", "Entry Error");
textBox.Focus();
return false;
}
return true;
}
public bool IsInt32(TextBox textBox, string name)
{
try
{
Convert.ToInt32(textBox.Text);
return true;
}
catch (FormatException)
{
MessageBox.Show(name + "must be a number between 0 and 100.", "Entry Error");
textBox.Focus();
return false;
}
}
public bool IsWithinRange(TextBox textBox, string name, decimal min, decimal max)
{
decimal number = Convert.ToDecimal(textBox.Text);
if (number < min || number > max)
{
MessageBox.Show(name + " must be between " + min + " and " + max + ".", "Entry Error");
textBox.Focus();
return false;
}
return true;
}
private void btnDisplayScore_Click(object sender, EventArgs e)
{
Array.Sort(scoreTotalArray);
string scoreCountString = "\n";
for(int i = 0; i < scoreCount; i++)
scoreCountString += scoreTotalArray [i] + "\n";
MessageBox.Show(scoreCountString + "\n", "Sorted Scores");
}
private void btnClearScores_Click(object sender, EventArgs e)
{
txtScore.Clear();
txtScoreTotal.Clear();
txtScoreCount.Clear();
txtAverage.Clear();
txtScore.Focus();
}
Your int array scoreTotalArray is always one element to big. That extra element contains the 0 you want to get rid of ;-)
Clearing the scores can be done by resizing your array to 0.
That said: You should probably consider using a List instead of an int array.
I have a .NET Winforms-based program I wrote in C# where I programmatically select text within a TextBox using the Select() method. I can see the selected text on the screen and the SelectionLength member reports an accurate amount of selected characters, but the SelectedText member doesn't contain any text:
int indexPeriod = strLectureText.IndexOfAny(terminators, indexStart);
thisTextbox.Focus();
if (indexPeriod > -1)
{
thisTextbox.Select(indexStart, (indexPeriod - indexStart) + 1);
}
else
{
thisTextbox.Select(indexStart, thisTextbox.Text.Length);
}
Log.Debug("jtext len=" + thisTextbox.SelectionLength + " txt=" + thisTextbox.SelectedText);
thisTextbox.ScrollToCaret();
What's going on?
Update Nov 16 2013
I am adding additional code per #KingKing's request:
delegate void delegateMoveToNextTextFragment(ref TextBox thisTextbox, char[] terminators);
private void MoveToNextTextFragment(ref TextBox thisTextbox, char[] terminators)
{
string strLectureText = String.Empty;
strLectureText = thisTextbox.Text;
int currentStartPos = thisTextbox.SelectionStart + thisTextbox.SelectionLength - 1
// search the rest of the buffer after the currently-selected string to find the next period
int skipLastChar = 0;
// don't include last selected character in search
try
{
if ((thisTextbox.SelectionLength > 0) & (strLectureText[currentStartPos] != '.'))
{
skipLastChar = 1;
}
}
catch (Exception ex)
{
Debug.WriteLine("exception caught! ex=" + ex.Message);
skipLastChar = 0;
}
int indexStart = 0;
if (currentStartPos == 0)
{
indexStart = 0;
}
else
{
indexStart = currentStartPos + 1;
}
int indexPeriod = strLectureText.IndexOfAny(terminators, indexStart);
if (indexPeriod > -1)
{
thisTextbox.Select(indexStart, (indexPeriod - indexStart) + 1);
}
else
{
thisTextbox.Select(indexStart, thisTextbox.Text.Length);
}
thisTextbox.Focus();
Log.Debug("jtext len=" + thisTextbox.SelectionLength + " txt=" + thisTextbox.SelectedText);
thisTextbox.ScrollToCaret();
}
I am currently working with Reverse Polish Notation. I have able to perform all operation in exception of exponential math. I am aware that C# sharps performs exponential math with Math.Pow but using that in my code is giving me an error 'System.Collections.Generic.Stack<T>.Push(T)' is a 'method', which is not valid in the given context. You can find the specific issue in the last if else statement. Any idea how I can properly correct or create a way to perform exponential math?
Code
private string inputValue = "";
private void RPNCalc(string rpnValue)
{
Stack<int> stackCreated = new Stack<int>();
stackCreated.Clear();
string[] inputArray = rpnValue.Split();
int end = inputArray.Length - 1;
int numInput;
int i = 0;
do
{
if ("=+-*/%^".IndexOf(inputArray[i]) == -1)
{
try
{
numInput = Convert.ToInt32(inputArray[i]);
stackCreated.Push(numInput);
}
catch
{
MessageBox.Show("Please check the input");
}
}
else if (inputArray[i]== "+")
{
try
{
int store1 = stackCreated.Pop();
int store2 = stackCreated.Pop();
stackCreated.Push(store2 + store1);
}
catch
{
}
}
else if (inputArray[i]== "-")
{
try
{
int store1 = stackCreated.Pop();
int store2 = stackCreated.Pop();
stackCreated.Push(store2 - store1);
}
catch
{
}
}
else if (inputArray[i]== "%")
{
try
{
int store1 = stackCreated.Pop();
int store2 = stackCreated.Pop();
stackCreated.Push(store2 % store1);
}
catch
{
}
}
else if (inputArray[i]== "*")
{
try
{
int store1 = stackCreated.Pop();
int store2 = stackCreated.Pop();
stackCreated.Push(store2 * store1);
}
catch
{
}
}
else if (inputArray[i]== "/")
{
try
{
int store1 = stackCreated.Pop();
int store2 = stackCreated.Pop();
stackCreated.Push(store2 / store1);
}
catch
{
}
}
else if (inputArray[i] == "^")
{
try
{
int store1 = stackCreated.Pop();
int store2 = stackCreated.Pop();
stackCreated.Push.Math.Pow(store1, store2);
}
catch
{
}
}
}
while(i++ < end && inputArray[i]!= "=" && stackCreated.Count != 0);
string result = inputValue + " " + stackCreated.Pop().ToString() + Environment.NewLine;
TxtOutputBox.AppendText(result);
TxtInputBox.Clear();
}
Should be:
stackCreated.Push((int)Math.Pow(store1, store2));
This will perform the power operation, and then push the result onto the stack.
Its like doing:
int tmp = (int)Math.Pow(store1, store2);
stackCreated.Push(tmp);
Also note that Math.Pow works on doubles. Your ints (store1 and store2) will be automatically converted up to a double, but you need to tell the compiler to cast the result back down to an int.