【问题标题】:Calculator Total failing计算器总失败
【发布时间】:2014-02-21 05:28:42
【问题描述】:

我正在使用 C# 编写一个计算器。

namespace Calculator
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        public void Total(string num)   
        {
            lblTotal.Content = Convert.ToString(lblTotal.Content) + num;
        }
        private void one_Click(object sender, RoutedEventArgs e)
        {
            Total( Convert.ToString(1) );
        }
        private void two_Click(object sender, RoutedEventArgs e)
        {
            Total( Convert.ToString(2) );
        }
        private void three_Click(object sender, RoutedEventArgs e)
        {
            Total( Convert.ToString(3) );
        }
        private void four_Click(object sender, RoutedEventArgs e)
        {
            Total( Convert.ToString(4) );
        }
        private void five_Click(object sender, RoutedEventArgs e)
        {
            Total( Convert.ToString(5) );
        }
        private void six_Click(object sender, RoutedEventArgs e)
        {
            Total( Convert.ToString(6) );
        }
        private void seven_Click(object sender, RoutedEventArgs e)
        {
            Total( Convert.ToString(7) );
        }
        private void eight_Click(object sender, RoutedEventArgs e)
        {
            Total( Convert.ToString(8) );
        }
        private void nine_Click(object sender, RoutedEventArgs e)
        {
            Total( Convert.ToString(9) );
        }
        private void ten_Click(object sender, RoutedEventArgs e)
        {
            Total( Convert.ToString(10) );
        }
        private void zero_Click(object sender, RoutedEventArgs e)
        {
            Total( Convert.ToString(0) );
        }

        private void add_Click(object sender, RoutedEventArgs e)
        {
            Total("+");
        }

        private void subtract_Click(object sender, RoutedEventArgs e)
        {
            Total("-");
        }

        private void multiply_Click(object sender, RoutedEventArgs e)
        {
            Total("*");
        }

        private void divide_Click(object sender, RoutedEventArgs e)
        {
            Total("/");
        }

        private void total_Click(object sender, RoutedEventArgs e)
        {
            int calculate;
            string content;

            content = Convert.ToString(lblTotal.Content);
            calculate = Convert.ToInt32(content);

        }

    }

}

因此,当用户单击总计按钮时,它应该打开 lblTotal.Content 并获取计算所需的数学并将 lblTotal.Content 设置为答案。

我收到此错误:

System.FormatException was unhandled
  _HResult=-2146233033
  _message=Input string was not in a correct format.
  HResult=-2146233033
  IsTransient=false
  Message=Input string was not in a correct format.
  Source=mscorlib
  StackTrace:
       at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
       at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
       at System.String.System.IConvertible.ToInt32(IFormatProvider provider)
       at System.Convert.ToInt32(Object value)
       at Calculator.MainWindow.total_Click(Object sender, RoutedEventArgs e) in c:\Users\Administrator\Documents\Visual Studio 2013\Projects\Calculator\Calculator\MainWindow.xaml.cs:line 100
       at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
       at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
       at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
       at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
       at System.Windows.Controls.Primitives.ButtonBase.OnClick()
       at System.Windows.Controls.Button.OnClick()
       at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
       at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e)
       at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
       at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
       at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
       at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
       at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
       at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)
       at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
       at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
       at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
       at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
       at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
       at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
       at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
       at System.Windows.Input.InputManager.ProcessStagingArea()
       at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
       at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
       at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
       at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
       at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
       at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
       at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
       at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
       at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
       at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
       at System.Windows.Threading.Dispatcher.Run()
       at System.Windows.Application.RunDispatcher(Object ignore)
       at System.Windows.Application.RunInternal(Window window)
       at System.Windows.Application.Run(Window window)
       at System.Windows.Application.Run()
       at Calculator.App.Main() in c:\Users\Administrator\Documents\Visual Studio 2013\Projects\Calculator\Calculator\obj\Debug\App.g.cs:line 0
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

我希望有一个修复。当我点击总按钮时,程序崩溃,然后我得到上面的错误。

【问题讨论】:

  • 这个计算发生在哪里,在你的代码中看不到任何计算,从代码只能告诉你转换为整数失败
  • 内容是否是整数?
  • @Hassan..lblContent 是什么> 是标签吗?
  • @Hassan,您不会尝试使用Convert.ToInt322+5 转换为7,对吧?因为那不是那个函数的作用......
  • Convert.ToString(1) 的意义何在?为什么不直接传递字符串文字? Total("1")

标签: c# wpf


【解决方案1】:

您正在尝试使用Convert.ToInt322+5 转换为7。这不是Convert.ToInt32 所做的。 Convert.ToInt32int.Parse 接受一个表示数字的字符串(12345-1245)并将其转换为整数。

您可能应该先查看data types,然后再进行其他操作。

您需要自己解析表达式,或使用表达式解析器。见I need a fast runtime expression parserHow would you create an expression parser in c#?

有关如何在 WPF 中制作计算器的示例不解析表达式,请参阅 MSDN Sample calculator

【讨论】:

  • 这可能是最相关的答案(包括我的)。他正试图在那个标签上做数学。
  • 我是 C# 的新手,我正在努力学习东西,不胜感激!
  • @Hassan,你读过我链接的文章吗?解析表达式不是 5 行操作...
  • @Hassan 我们知道您是新手。从小处着手。通过查看上面更新的代码,您需要从小处着手并了解数据类型,正如 Mitch 所提到的;以及适用于它们的基本方法。您在这里尝试一次做太多事情,这会导致您更加困惑。
  • @Hassan 既然你说你刚刚开始使用c#,这相当于在不知道如何游泳的情况下跳入游泳池的深处,这是一种非常不标准的创建方式一个计算器,试着想象当你使用一个实际的计算器并尝试模仿它时会发生什么。
【解决方案2】:

使用链接中给出的Int32.TryParse (MSDN)。

【讨论】:

【解决方案3】:

lblTotal.Content 可能是您的问题,因为它可能不是存储为字符串的数字,或者该字符串中可能有其他字符。

【讨论】:

  • 它有运算符也有数字
  • @Hassan 请将 lblTotal.Content 的内容示例发布到您的答案中
  • @MarkHall 我用整个源代码更新了主帖
【解决方案4】:
private void total_Click(object sender, RoutedEventArgs e)
{
    int content ;
    int.TryParse(convert.ToString(lblTotal.Content), out content );
    int calculate = content;
    lblTotal.Content =convert.ToString( calculate);
}

【讨论】:

  • 错误 1 ​​'int.TryParse(string, out int)' 的最佳重载方法匹配有一些无效参数 c:\users\administrator\documents\visual studio 2013\projects\calculator\calculator\ mainwindow.xaml.cs 99 13 计算器
【解决方案5】:

从这里的调用堆栈中, 在 System.Convert.ToInt32(对象值)。 似乎说您对 Convert.ToInt32 的输入类型不正确。我不确定您的 lblTotal.Content 类型,因为您没有在此处放置相关代码,但我想它可能不是字符串,您能看一下吗?我猜如果 lblTotal.Content 是一个容器,它应该使用 lblTotal.Content.Text 之类的东西

【讨论】:

  • 我没有使用 cmd 行来使用“系统”。
  • @Hassan System 是 C# 中的命名空间,我认为从调用堆栈来看,这意味着您输入的 ToInt32 函数不正确。有点迷茫,完成后请告诉我解决方法,谢谢。
【解决方案6】:

如何获取标签的 Content 属性。对于 Labell 内容属性在 win 表单中不存在。

如果它对你可用,则使用 ToString() 函数将字符串值分配给 Content。

private void total_Click(object sender, RoutedEventArgs e) {

lblTotal.Content=Convert.ToInt32(lblTotal.Content).ToString();

}

【讨论】:

    【解决方案7】:

    这应该会给你一个提示:输入字符串的格式不正确。

    从 string 到 int 的转换失败了。使用 Int32.TryParse 或在您的代码中添加一些异常处理:

    int calculate;
    int content;
    
    if (Int32.TryParse(lblTotal.Content, out content))
    {
        calculate = content;
        lblTotal.Content = calculate.ToString();
    }
    else
    {
        lblTotal.Content = String.Format("Error converting {0}", lblTotal.Content);
    }
    

    上面的代码在这方面完全没有做任何事情,顺便说一下,你取 lblTotal 的内容,将其转换为 int,分配给计算并将 lblTotal 的内容设置为相同的值。

    【讨论】:

    • 在哪里?你有堆栈跟踪吗?
    • 我用完整的源更新了主帖,请查看! @HåkanFahlstedt
    • 我认为米奇有相关的答案。调用 Total_Click 时 lblTotal.Content 的值如何?
    • 它类似于 5+5?
    • 是的,不能用 Convert.ToInt32 和 Int32.TryParse 来解析。您只能解析整数,而不是可以计算为整数的表达式,即 5、234、0 可以正常工作,但 5+5、3*4、2/3 不能。
    【解决方案8】:

    这应该可行:

            int content;
            if (Int32.TryParse(lblTotal.Content.ToString(), out content))
            {
                int calculate = content;
                lblTotal.Content = calculate;
            }
    

    如果条件是true,数值将被分配给content,然后你的方法的其余部分执行。

    如果您不想在该标签内进行数学运算,那当然是这样。

    编辑:

    这里有一篇对你很有帮助的文章:

    http://code.msdn.microsoft.com/windowsdesktop/Simple-Calculator-d1d8cf4c/view/SourceCode#content

    点击Browse Code标签并浏览代码。

    【讨论】:

    • 堆栈跟踪显示异常发生在 Convert.ToInt32
    • @panoptical 嗯,真的。可能是数值输入失败所致。
    • 不会崩溃但不会计算
    • @Hassan Right...您需要更具体地提出问题。我想我们都终于弄清楚你是在尝试在标签中编写表达式并从中得到结果。请参阅 Mitch 关于表达式的回答。
    • 是的,可以吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-11
    • 2022-01-05
    • 2019-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多