第一个应用程序,我曾写过崩溃,我不知道为什么

时间:2015-08-20 20:31:38

标签: c# android xamarin

我已经开始使用Xamarin在C#中编写Android应用程序,但我的应用程序在它甚至做任何事情之前崩溃了。任何人都可以找出原因吗?

该应用程序的目的是简单地采用ax ^ 2 + bx + c形式的二次方程式,找到它的两个解,然后显示这些解。

感谢。

[Activity (Label = "FirstApp", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
    int a = 4;
    int b = 1 ;
    int c = 2;
    int d;
    int s1;
    int s2;
    string fail ="There are no real roots!";


    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);

        // Set our view from the "main" layout resource
        SetContentView (Resource.Layout.Main);

        // Get our button from the layout resource,
        // and attach an event to it
        Button button = FindViewById<Button> (Resource.Id.myButton);
        TextView sol2 = FindViewById<TextView> (Resource.Id.Solution2);
        TextView sol1 = FindViewById<TextView> (Resource.Id.Solution1);

        button.Click += delegate {
            quadratic(a,b,c);

            sol1.Text = string.Format (Convert.ToString(s1));

            sol2.Text = string.Format (Convert.ToString(s2));
        };

    }
    string quadratic (int a, int b, int c)
    {
        d = Convert.ToInt32(Math.Pow (b, 2)) - (4 * a * c);
        if (d < 0) {
            return(fail);
        } else{
            s1 = (-1 * b + Convert.ToInt32(Math.Sqrt (d))) / (2 * a);
            s2 = (-1 * b - Convert.ToInt32(Math.Sqrt (d))) / (2 * a);
            return(Convert.ToString(s1));
        }
    }
}

2 个答案:

答案 0 :(得分:1)

我认为以下几行试图将未定义的int转换为字符串:

n

在我的本地测试中,在 s1 s2 具有值之前,项目不会构建。

sol1.Text = string.Format (Convert.ToString(s1));
sol2.Text = string.Format (Convert.ToString(s2));

答案 1 :(得分:0)

我找到了解决方案! 简单地说,我显然已经开始为android API Level 22开发我的应用程序,并试图在Level 21模拟器上运行它,所以它无法应对它。

下载Level 22图像并修复新模拟器。