简体   繁体   中英

c# why can't I use else here?

Basically it tells me that tal2--; else tal1 = 56; it's an error "invalid expression of else", how come?

Cheers.

using System;

class Program
{
    static void Main(string[] args)
    {
        int tal1, tal2;
        int slinga;

            tal2 = Convert.ToInt32(Console.ReadLine());
        for (slinga = 0; slinga < 2; slinga++)
        {
            if (tal1 == 56)
                Console.WriteLine(Addera(slinga, tal1));
            tal2--;
            else tal1 = 56;

        }
    }
    static int Addera(int tal1, int tal2)
    {
        return tal1 + tal2;
    }
}

If "if clause" has to span more than one lines of code you have to surround it with curly brackets "{}". Change your code to :

using System;

class Program
{
    static void Main(string[] args)
    {
        int tal1, tal2;
        int slinga;

        tal2 = Convert.ToInt32(Console.ReadLine());
        for (slinga = 0; slinga < 2; slinga++)
        {
            if (tal1 == 56)
            {
                Console.WriteLine(Addera(slinga, tal1));
                tal2--;
            }
            else
                tal1 = 56;
        }
    }
    static int Addera(int tal1, int tal2)
    {
        return tal1 + tal2;
    }
}

Following code lines are wrong

if (tal1 == 56)
      Console.WriteLine(Addera(slinga, tal1));
    tal2--;
 else tal1 = 56;

You need to update it to

if (tal1 == 56){
     Console.WriteLine(Addera(slinga, tal1));
     tal2--;
}
 else {
    tal1 = 56;
}

Reason : You need { } for multi-lined if-else conditions

MSDN says

Both the then-statement and the else-statement can consist of a single statement or multiple statements that are enclosed in braces ({}). For a single statement, the braces are optional but recommended.

So you need { } since it's multi-lined

Change

        if (tal1 == 56)
            Console.WriteLine(Addera(slinga, tal1));
            tal2--;
        else tal1 = 56;

to

        if (tal1 == 56)
        {
            Console.WriteLine(Addera(slinga, tal1));
            tal2--;
        }
        else tal1 = 56;

The {} tells the compiler that the code between those brackets is part of the same logic branch.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM