Ошибка else не может запускать оператор

kraftov

0 / 0 / 0

Регистрация: 15.04.2021

Сообщений: 6

1

25.04.2021, 12:45. Показов 6973. Ответов 3

Метки else требует оператора, elseif (Все метки)


Студворк — интернет-сервис помощи студентам

При добавлении else к if вылезают куча ошибок, первая из них «else не может запускать оператор»
Код:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using System;
 
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            int nach = 0;
            int konec = 0;
            int dopperm = 0;
            int x = 0;
            int sum = 0;
            int ethapif = 1;
            int ethapwh = 1;
            nach = int.Parse(Console.ReadLine());
            konec = int.Parse(Console.ReadLine());
            if (nach > konec)
            {
                dopperm = konec;
                konec = nach;
                nach = dopperm;
            }
            Console.WriteLine("[" + nach + ";" + konec + "]");
            x = nach;
            Console.WriteLine("Начальный x=" + x);
            while (x <= konec)
            {
                Console.WriteLine();
                Console.WriteLine("Этап(While)=" + ethapwh);
                ethapwh++;
                Console.WriteLine("while x=" + x);
                if ((x % 2 == 1)) ;
                {
 
                    Console.WriteLine("if x=" + x);
                    sum += x;
                    Console.WriteLine("Этап(if)=" + ethapif);
                    ethapif++;
                    Console.WriteLine("if sum=" + sum);
                    x++;
                }else 
 
            }
            
            Console.WriteLine("Итоговая сумма=" + sum);
            Console.ReadKey();
        }
    }
}

p.s. решаю задачу (Программа должна предложить пользователю границы диапазона указав два
целых числа. Необходимо суммировать все нечетные целые числа в диапазоне
указанном пользователем.
Указания:
В коде должен использоваться любой цикл (while, for или foreach)
Диапазон включительно, то есть числа введеные пользователем являются
частью диапазона.
Программа должна работать и в том случае, когда второе число меньше
первого)



0



Пора на C++?

369 / 263 / 99

Регистрация: 10.04.2020

Сообщений: 1,275

25.04.2021, 13:02

2

Цитата
Сообщение от kraftov
Посмотреть сообщение

При добавлении else к if вылезают куча ошибок, первая из них «else не может запускать оператор»

Добавьте код после else.



0



Эксперт .NET

5867 / 4744 / 2940

Регистрация: 20.04.2015

Сообщений: 8,361

25.04.2021, 13:05

3

Лучший ответ Сообщение было отмечено kraftov как решение

Решение

1) уберите ‘;’ в 33-й строке
2) после else нужна хотя бы одна строка, выполняющаяся, если условие в if не выполнится



1



0 / 0 / 0

Регистрация: 15.04.2021

Сообщений: 6

25.04.2021, 13:07

 [ТС]

4

не помогает

Добавлено через 1 минуту
Даценд спасибо!



0



The problem is in

    if (oper == "-") ; // ";" is the culprit
    {
      ...
    }
    else
      ...

fragment. Drop ; it should be

    if (oper == "-")
    {
      ...
    }
    else
      ...

Your current code means:

// if oper == "-" do nothing - ;
if (oper == "-") ;

then {..} block comes which has no connection with if

{
  ...
}

finally, you have orphan else which cause compile time error.

Edit: try avoiding nested if, but use else if

if (oper == "+") {
  ...
}
else if (oper == "-") {
  ...
}
else {
  ...
}

Asked
4 years, 2 months ago

Viewed
17k times

I’m new to programming guys (C#) my code says that the if else statement that I used is causing an error. Idk what the problem is with this. Can someone help me please?

    if(ItemPrice==Soda);
    {
        Console.WriteLine($"Inserted so far: P0 out of P{Soda}");
        break;
    }
    else if(ItemPrice==Juice);
    {
        Console.WriteLine($"Inserted so far: P0 out of P{Juice}");
    }
    else if(ItemPrice==WaterBottle);
    {
        Console.WriteLine($"Inserted so far: P0 out of P{WaterBottle}");
    }

Risto M's user avatar

Risto M

2,9091 gold badge14 silver badges27 bronze badges

asked Apr 11, 2019 at 5:21

Betlogka's user avatar

1

You have semicolons (;) after your if statements, Which gives you these warnings

Compiler Warning (level 3) CS0642

Possible mistaken empty statement

A semicolon after a conditional statement may cause your code to
execute differently than intended.

And this error

Compiler Error CS1513

} expected

The compiler expected a closing curly brace (}) that was not found.

The syntax you needed

if (condition) 
{
   // statement;
}
else if (condition) 
{
   // statement;
}
else if (condition) 
{
   // statement;
}

Additional resources

if-else (C# Reference)

answered Apr 11, 2019 at 5:22

TheGeneral's user avatar

TheGeneralTheGeneral

78.6k9 gold badges99 silver badges139 bronze badges

0

ArtemChidori

0 / 0 / 0

Регистрация: 25.03.2022

Сообщений: 1

1

25.03.2022, 20:46. Показов 1929. Ответов 1

Метки нет (Все метки)


не понимаю что не так с кодом

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
{
            Console.WriteLine("ввод пароля");
 
            string pass1 = Console.ReadLine();
 
            Console.WriteLine("ввод логина");
 
            string login1 = Console.ReadLine();
 
            Console.WriteLine("ввод данных. введите пароль");
 
            string pass2 = Console.ReadLine();
 
            Console.WriteLine("введите логин");
 
            string login2 = Console.ReadLine();
 
            if (pass1 == pass2 & login1 == login2);
            {
                Console.WriteLine("Все данные введены успешно"); 
            }
            else
            {
                Console.WriteLine("Данные введены неверно");
            }
        }
    }
}

ошибки которые у меня появились:
CS8641: «else» не может запускать оператор.
CS1525: недопустимый термин else в выражении
CS1525: недопустимый термин else в выражении
CS1003: синтаксическая ошибка , требуется «(«
CS1026 требуется «)»
CS1002 требуется «;»

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

0

4 / 3 / 1

Регистрация: 25.12.2021

Сообщений: 7

25.03.2022, 21:27

2

Цитата
Сообщение от ArtemChidori
Посмотреть сообщение

if (pass1 == pass2 & login1 == login2);

Не должно быть точки с запятой, а в остальном все работает.

0

IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

25.03.2022, 21:27

Помогаю со студенческими работами здесь

Что не так с кодом?
#include&lt;stdio.h&gt;
#include &lt;iostream&gt;
#include &lt;conio.h&gt;
#include &lt;string&gt;
#include &lt;ctime&gt;…

Что не так с кодом?
Буду благодарен помощи.

#include &lt;iostream&gt;
#include &quot;stdio.h&quot;

using namespace std;

Что не так с кодом?
В некоторых видах спортивных состязаний выступление каждого спортсмена независимо оценивается…

Что не так с кодом
Всем привет, я новенький.
Не могу понять в чем проблема.

#include &lt;string.h&gt;
#include…

что не так с кодом?!!
В каждой строке матрицы D(6, 6) найти элементы, для которых сумма предшествующих элемен-тов больше…

Что не так с кодом?
Console.Title = &quot; Оператор while&quot;;
string Str;
Console.Write(&quot;Введите…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

2

Оператор else не работает, если ввод в консоль не «Камень, ножницы или бумага», сообщение об исключении не отображается. Что является причиной этого.

using System;

namespace Rock__Paper__Scissors_
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Lets play a game of Rock, Paper, Scissors.");
            Console.Write("Enter Rock, Paper or Scissors:");
            string userChoice = Console.ReadLine();

            Random r = new Random();
            int computerChoice = r.Next(3);

            //0 = Scissors
            if (computerChoice == 0)
            {
                if (userChoice == "Scissors")
                {
                    Console.WriteLine("Computer chose scissors!");
                    Console.WriteLine("TIE!");
                }

                else if (userChoice == "Rock")
                {
                    Console.WriteLine("Computer chose Scissors!");
                    Console.WriteLine("You WIN!");
                }

                else if (userChoice == "Paper")
                {
                    Console.WriteLine("Computer chose Scissors");
                    Console.WriteLine("You LOSE!");

                }
            }

            //1 = Rock
            else if (computerChoice == 1)
            {
                if (userChoice == "Scissors")
                {
                    Console.WriteLine("Computer chose Rock!");
                    Console.WriteLine("You LOSE!");
                }

                else if (userChoice == "Rock")
                {
                    Console.WriteLine("Computer chose Rock!");
                    Console.WriteLine("TIE!");
                }

                else if (userChoice == "Paper")
                {
                    Console.WriteLine("Computer chose Rock");
                    Console.WriteLine("You WIN!");
                }
            }

            //2 = Paper
            else if (computerChoice == 2)
            {
                if (userChoice == "Scissors")
                {
                    Console.WriteLine("Computer chose Paper!");
                    Console.WriteLine("You WIN");
                }

                else if (userChoice == "Rock")
                {
                    Console.WriteLine("Computer chose Paper!");
                    Console.WriteLine("You LOSE!");
                }

                else if (userChoice == "Paper")
                {
                    Console.WriteLine("Computer chose Paper");
                    Console.WriteLine("TIE!");
                }
            }

            //3 = Exception Handling
            else
            {
                Console.WriteLine("You must enter Rock, Paper or Scissors");
            }


        }
    }
}

2 ответа

Прежде чем продолжить, проверьте значение или userChoice … Я бы предпочел использовать цикл while

using System;

namespace Rock__Paper__Scissors_
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Lets play a game of Rock, Paper, Scissors.");
            Console.Write("Enter Rock, Paper or Scissors:");
            string userChoice = Console.ReadLine();

            //Check it here in a while loop, until the user gets it 
            //right, the program will not proceed and loop here
            while (userChoice != "Scissors" || userChoice != "Rock" || userChoice != "Paper")
            {
                Console.Write("You must enter Rock, Paper or Scissors");
                userChoice = Console.ReadLine();
            }

            Random r = new Random();
            int computerChoice = r.Next(3);

            //0 = Scissors
            if (computerChoice == 0)
            {
                if (userChoice == "Scissors")
                {
                    Console.WriteLine("Computer chose scissors!");
                    Console.WriteLine("TIE!");
                }

                else if (userChoice == "Rock")
                {
                    Console.WriteLine("Computer chose Scissors!");
                    Console.WriteLine("You WIN!");
                }

                else if (userChoice == "Paper")
                {
                    Console.WriteLine("Computer chose Scissors");
                    Console.WriteLine("You LOSE!");

                }
            }

            //1 = Rock
            else if (computerChoice == 1)
            {
                if (userChoice == "Scissors")
                {
                    Console.WriteLine("Computer chose Rock!");
                    Console.WriteLine("You LOSE!");
                }

                else if (userChoice == "Rock")
                {
                    Console.WriteLine("Computer chose Rock!");
                    Console.WriteLine("TIE!");
                }

                else if (userChoice == "Paper")
                {
                    Console.WriteLine("Computer chose Rock");
                    Console.WriteLine("You WIN!");
                }
            }

            //2 = Paper
            else if (computerChoice == 2)
            {
                if (userChoice == "Scissors")
                {
                    Console.WriteLine("Computer chose Paper!");
                    Console.WriteLine("You WIN");
                }

                else if (userChoice == "Rock")
                {
                    Console.WriteLine("Computer chose Paper!");
                    Console.WriteLine("You LOSE!");
                }

                else if (userChoice == "Paper")
                {
                    Console.WriteLine("Computer chose Paper");
                    Console.WriteLine("TIE!");
                }
            }
        }
    }
}


0

jPhizzle
4 Июл 2019 в 01:50

Добавлено еще несколько операторов if / if else вместо else. Теперь он выплевывает ошибку исключения, которую я хотел.

Цель создания этого заключалась в том, чтобы практиковать / применять методы if, if else и else, поскольку я пытаюсь изучить C # и прорабатываю некоторые учебные пособия в Интернете. Конечно, есть, наверное, лучшие способы сделать эту игру.

-Нужно добавить какие-то петли (когда я научусь их делать). — Компьютер, кажется, генерирует случайное число в предсказуемой последовательности и не кажется таким уж случайным, поэтому мне нужно работать над улучшением этого.

Используя Систему;

namespace Rock__Paper__Scissors_
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Lets play a game of Rock, Paper, Scissors.");
            Console.Write("Enter Rock, Paper or Scissors:");
            string userChoice = Console.ReadLine();

            Random r = new Random();
            int computerChoice = r.Next(2);


            //0 = Scissors
            if (computerChoice == 0)
            {
                if (userChoice == "Scissors")
                {
                    Console.WriteLine("Computer chose scissors!");
                    Console.WriteLine("TIE!");
                }

                else if (userChoice == "Rock")
                {
                    Console.WriteLine("Computer chose Scissors!");
                    Console.WriteLine("You WIN!");
                }

                else if (userChoice == "Paper")
                {
                    Console.WriteLine("Computer chose Scissors");
                    Console.WriteLine("You LOSE!");

                }
            }

            //1 = Rock
            else if (computerChoice == 1)
            {
                if (userChoice == "Scissors")
                {
                    Console.WriteLine("Computer chose Rock!");
                    Console.WriteLine("You LOSE!");
                }

                else if (userChoice == "Rock")
                {
                    Console.WriteLine("Computer chose Rock!");
                    Console.WriteLine("TIE!");
                }

                else if (userChoice == "Paper")
                {
                    Console.WriteLine("Computer chose Rock");
                    Console.WriteLine("You WIN!");
                }
            }

            //2 = Paper
            else if (computerChoice == 2)
            {
                if (userChoice == "Scissors")
                {
                    Console.WriteLine("Computer chose Paper!");
                    Console.WriteLine("You WIN");
                }

                else if (userChoice == "Rock")
                {
                    Console.WriteLine("Computer chose Paper!");
                    Console.WriteLine("You LOSE!");
                }

                else if (userChoice == "Paper")
                {
                    Console.WriteLine("Computer chose Paper");
                    Console.WriteLine("TIE!");
                }
            }


            //Exception Handling
            if (userChoice != "Scissors")
            {
                Console.WriteLine("Choose Rock, Paper or Scissors");
            }

            else if (userChoice != "Rock")
            {
                Console.WriteLine("Choose Rock, Paper or Scissors");
            }

            else if (userChoice != "Paper")
            {
                Console.WriteLine("Choose Rock, Paper or Scissors");
            }


        }
    }
}


0

Thomas Dunbar
4 Июл 2019 в 13:09

using System;

public class SpaceEnginnersThrust { static public void Main () {

/*If you want to find the speed your ship is able to go type speed then enter how many large atmospheric thrusters are on your ship. Then enter it's weight in kilograms.

If you want to know how many large atmospheric thrusters you need on your ship first type thrust then type speed in meters per second. Finally add the weight of your ship in kilograms.

If you want to know how heavy your ship is first type in weight then type your speed in meters per second afterwards enter in how many large atmospheric thrusters your ship has. */

	string thrusters = Console.ReadLine();
  Console.Write("What thrusters do you want to know about? ");
	
	
	
	if (thrusters == "small atmospheric")
	{
	string option = Console.ReadLine();
	Console.Write("Do you want to find weight, speed, or thruster power? ");
	
	
	
	if (option == "weight")
	{
		weight();
	}
	else if (option == "speed")
	{
	speed();
}
else {
	thrust();
}
	
	
}
//Main ends here
static void weight()
{
int kn = 96;
double thrusters1 = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("You have {0} thrusters on your ship.", thrusters1);

double ms1 = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("nYour ship can go {0} meters per second", ms1);


double kg1 = thrusters1 * kn * 1000 / ms1;

Console.WriteLine("nYour ship weighs {0} kilograms.",kg1);
}
static void speed()
{
int kn = 96;
	double thrusters2 = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("You have {0} thrusters on your ship.", thrusters2);

double kg2 = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("rYour ship weighs {0} kilograms.", kg2);


double ms2 = (thrusters2 * kn)/(kg2 / 1000);
Console.WriteLine("Your ship can travel at a speed of {0} meters per second", ms2);
}
static void thrust()
{
int kn = 96;
	double ms3 = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("Your ship can travel at a speed of {0} meters per second",ms3 );

double kg3 = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("rYour ship weighs {0} kilograms.", kg3);


double thruster3 = ms3 * (kg3/1000)/kn;

Console.WriteLine("nYour ship will need exactly {0} thrusters.", thruster3);
}

else if (thrusters == "large atmospheric")
{
    Console.WriteLine("this isnt working");
}
}
}

ArtemChidori

0 / 0 / 0

Регистрация: 25.03.2022

Сообщений: 1

1

25.03.2022, 20:46. Показов 2517. Ответов 1

Метки нет (Все метки)


не понимаю что не так с кодом

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
{
            Console.WriteLine("ввод пароля");
 
            string pass1 = Console.ReadLine();
 
            Console.WriteLine("ввод логина");
 
            string login1 = Console.ReadLine();
 
            Console.WriteLine("ввод данных. введите пароль");
 
            string pass2 = Console.ReadLine();
 
            Console.WriteLine("введите логин");
 
            string login2 = Console.ReadLine();
 
            if (pass1 == pass2 & login1 == login2);
            {
                Console.WriteLine("Все данные введены успешно"); 
            }
            else
            {
                Console.WriteLine("Данные введены неверно");
            }
        }
    }
}

ошибки которые у меня появились:
CS8641: «else» не может запускать оператор.
CS1525: недопустимый термин else в выражении
CS1525: недопустимый термин else в выражении
CS1003: синтаксическая ошибка , требуется «(«
CS1026 требуется «)»
CS1002 требуется «;»

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

0

4 / 3 / 1

Регистрация: 25.12.2021

Сообщений: 9

25.03.2022, 21:27

2

Цитата
Сообщение от ArtemChidori
Посмотреть сообщение

if (pass1 == pass2 & login1 == login2);

Не должно быть точки с запятой, а в остальном все работает.

0

IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

25.03.2022, 21:27

Помогаю со студенческими работами здесь

Что не так с кодом?
#include&lt;stdio.h&gt;
#include &lt;iostream&gt;
#include &lt;conio.h&gt;
#include &lt;string&gt;
#include &lt;ctime&gt;…

Что не так с кодом?
Буду благодарен помощи.

#include &lt;iostream&gt;
#include &quot;stdio.h&quot;

using namespace std;

Что не так с кодом?
В некоторых видах спортивных состязаний выступление каждого спортсмена независимо оценивается…

Что не так с кодом
Всем привет, я новенький.
Не могу понять в чем проблема.

#include &lt;string.h&gt;
#include…

что не так с кодом?!!
В каждой строке матрицы D(6, 6) найти элементы, для которых сумма предшествующих элемен-тов больше…

Что не так с кодом?
Console.Title = &quot; Оператор while&quot;;
string Str;
Console.Write(&quot;Введите…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

2

Asked
3 years, 11 months ago

Viewed
17k times

I’m new to programming guys (C#) my code says that the if else statement that I used is causing an error. Idk what the problem is with this. Can someone help me please?

    if(ItemPrice==Soda);
    {
        Console.WriteLine($"Inserted so far: P0 out of P{Soda}");
        break;
    }
    else if(ItemPrice==Juice);
    {
        Console.WriteLine($"Inserted so far: P0 out of P{Juice}");
    }
    else if(ItemPrice==WaterBottle);
    {
        Console.WriteLine($"Inserted so far: P0 out of P{WaterBottle}");
    }

Risto M's user avatar

Risto M

2,87915 silver badges27 bronze badges

asked Apr 11, 2019 at 5:21

Betlogka's user avatar

1

You have semicolons (;) after your if statements, Which gives you these warnings

Compiler Warning (level 3) CS0642

Possible mistaken empty statement

A semicolon after a conditional statement may cause your code to
execute differently than intended.

And this error

Compiler Error CS1513

} expected

The compiler expected a closing curly brace (}) that was not found.

The syntax you needed

if (condition) 
{
   // statement;
}
else if (condition) 
{
   // statement;
}
else if (condition) 
{
   // statement;
}

Additional resources

if-else (C# Reference)

answered Apr 11, 2019 at 5:22

TheGeneral's user avatar

TheGeneralTheGeneral

77.9k9 gold badges95 silver badges135 bronze badges

0

Возможно, вам также будет интересно:

  • Ошибка eloc на кондиционере
  • Ошибка eeprom что это такое
  • Ошибка elm bmw e46
  • Ошибка eeprom что это кондиционер
  • Ошибка elm bmw e39

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии