Error cs1525 unexpected symbol public

I'm having some trouble fixing this error. I've had it work before but as soon as I added a second GetKeyDown it stopped working. Sorry if I look stupid, I'm an extreme beginner. using UnityEngine;

I’m having some trouble fixing this error. I’ve had it work before but as soon as I added a second GetKeyDown it stopped working. Sorry if I look stupid, I’m an extreme beginner.

using UnityEngine;
using System.Collections;

    // Use this for initialization
    void Start () 
    {
        public int moveSpeed = 5;
    }
    // Update is called once per frame
    void Update () 
    {
        if (Input.GetKeyDown (KeyCode.D))
        {
            transform.Translate (Vector3.right * moveSpeed);
        };

        if (Input.GetKeyDown (KeyCode.A))
        {
            transform.Translate (Vector3.left * moveSpeed);
        };
    }
};

Anas iqbal's user avatar

asked Jul 29, 2015 at 1:13

Sh3lby's user avatar

1

A) You are missing class declaration line (you still have closing bracket for it)

using UnityEngine;
using System.Collections;

public class Stuff : MonoBehaviour { // <-- you need class declaration (it must be the same name as file "Stuff.cs"

    public int moveSpeed = 5; // <-- B) you need to declare this variable at this scope or else Update method won't be able to see it

    // Use this for initialization
    void Start () 
    {

    }

    // Update is called once per frame
    void Update () 
    {
        if (Input.GetKeyDown (KeyCode.D))
        {
            transform.Translate (Vector3.right * moveSpeed);
        }

        if (Input.GetKeyDown (KeyCode.A))
        {
            transform.Translate (Vector3.left * moveSpeed);
        }
    }
} //<-- also - no semicolons after the closing brackets

answered Jul 29, 2015 at 6:53

izeed's user avatar

izeedizeed

1,7212 gold badges16 silver badges15 bronze badges

Why do you have semicolons everywhere? Anyway, thats not the problem.

// Use this for initialization
void Start () 
{
    int moveSpeed = 5; // remove public
}
// Update is called once per frame
void Update () 
{
    if (Input.GetKeyDown (KeyCode.D))
    {
        transform.Translate (Vector3.right * moveSpeed);
    }

    if (Input.GetKeyDown (KeyCode.A))
    {
        transform.Translate (Vector3.left * moveSpeed);
    }

}

Tell me if this works.

answered Jul 29, 2015 at 1:31

Souradeep Nanda's user avatar

Souradeep NandaSouradeep Nanda

3,0262 gold badges34 silver badges43 bronze badges

1

Try changing it to:

public int moveSpeed;

void Start () 
{
    moveSpeed = 5;
}

What I would really recommend is not to set the moveSpeed to 5 in the script but rather in the editor. Once you change the code to what I showed you then moveSpeed will show up in the editor inspector. Set it to whatever you want there. That way you can use the same script for objects with different speeds.

answered Jul 29, 2015 at 5:39

Reasurria's user avatar

ReasurriaReasurria

1,69814 silver badges14 bronze badges

Permalink

Cannot retrieve contributors at this time

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Compiler Error CS1525

Compiler Error CS1525

07/20/2015

CS1525

CS1525

7913f589-2f2e-40bc-a27e-0b6930336484

Compiler Error CS1525

Invalid expression term ‘character’

The compiler detected an invalid character in an expression.

The following sample generates CS1525:

// CS1525.cs  
class x  
{  
   public static void Main()  
   {  
      int i = 0;  
      i = i +   // OK - identifier  
      'c' +     // OK - character  
      (5) +     // OK - parenthesis  
      [ +       // CS1525, operator not a valid expression element  
      throw +   // CS1525, keyword not allowed in expression  
      void;     // CS1525, void not allowed in expression  
   }  
}  

An empty label can also generate CS1525, as in the following sample:

// CS1525b.cs  
using System;  
public class MyClass  
{  
   public static void Main()  
   {  
      goto FoundIt;  
      FoundIt:      // CS1525  
      // Uncomment the following line to resolve:  
      // System.Console.Write("Hello");  
   }  
}  

Проблема с скриптом!

Sniper00766 Дата: Пятница, 09 Марта 2012, 22:53 | Сообщение # 1

частый гость

Сейчас нет на сайте

Написал скрипт на здоров’я( что бы показывало сколько у тебя здоров’я)
Вот он:
using UnityEngine;
using System.Collections;

public class PlayerHealth : MonoBehaviour {
// Блок публичных переменных
public int maxHealth = 100;
// Блок переменных локального пользования
private int _curHealth = 100;
private float healthBarLeaght;

void Start () {
// Ширина бара
healthBarLeaght = Screen.width /2;
if(maxHealth<1) maxHealth=1;
_curHealth=maxHealth;
}

void Update(){

}

void onGUI (){
//Выводится бар состаяния здоров’я
GUI.Box(new Rect(10,10,healthBarLeaght,20),_curHealth + «/» + maxHealth);

public void AddjustCurrentHealth( int adj){
_curHealth = adj;
if(_curHealth < 0) _curHealth =0;
if(_curHealth > maxHealth)_curHealth = maxHealth;
healthBarLeaght = (Screen.width / 2) * (_curHealth / (float)maxHealth);
}
}

И в консоле появляеться такая ошибка:
Assets/Bot_Scripts/PlayerHealth.cs(26,22): error CS1525: Unexpected symbol `public’

И я ничего не могу сделать,
Помогите пожалуста!

Сообщение отредактировал Sniper00766Пятница, 09 Марта 2012, 22:54

Demeron Дата: Пятница, 09 Марта 2012, 23:16 | Сообщение # 2

User created in C++

Сейчас нет на сайте

Попробуй заменить

Code

public class PlayerHealth : MonoBehaviour {

на

Code

class PlayerHealth : MonoBehaviour {

MyACT Дата: Суббота, 10 Марта 2012, 05:33 | Сообщение # 3

C# CODERS

Сейчас нет на сайте

Demeron, это ничего не изменит,т.к это само название скрипта и из-за него не может быть ошибки,там что то на 26 строке…

Добавлено (10.03.2012, 05:29)
———————————————
В 26 строке убери public ,а оставь void и то что далее

Добавлено (10.03.2012, 05:33)
———————————————

Code

using UnityEngine;  
using System.Collections;  

public class PlayerHealth : MonoBehaviour {  
// Блок публичных переменных  
public int maxHealth = 100;  
// Блок переменных локального пользования  
private int _curHealth = 100;  
private float healthBarLeaght;  

void Start () {  
// Ширина бара  
healthBarLeaght = Screen.width /2;  
if(maxHealth<1) maxHealth=1;  
_curHealth=maxHealth;  
}  

void Update(){  
AddjustCurrentHealth();
}  

void onGUI (){  
//Выводится бар состаяния здоров’я  
GUI.Box(new Rect(10,10,healthBarLeaght,20),_curHealth + «/» + maxHealth);  

void AddjustCurrentHealth() {
_curHealth = adj;  
if(_curHealth < 0) _curHealth =0;  
if(_curHealth > maxHealth)_curHealth = maxHealth;  
healthBarLeaght = (Screen.width / 2) * (_curHealth / (float)maxHealth);  
}  
}

Вот так попробуй,у тебя метода обработки вроде нет,попробовал добавить проверь


3дэшечки: https://sketchfab.com/myactyindie
Курентли воркс он: https://myacty.itch.io/raskopnik

Sniper00766 Дата: Суббота, 10 Марта 2012, 10:00 | Сообщение # 4

частый гость

Сейчас нет на сайте

MyACT, Поставил твой скрипт и появилось две такие ошибки:
Assets/Bot_Scripts/PlayerHealth.cs(26,25): error CS1547: Keyword `void’ cannot be used in this context
Assets/Bot_Scripts/PlayerHealth.cs(26,26): error CS1525: Unexpected symbol `(‘, expecting `)’, `,’, `;’, `[‘, or `=’
Что делать?
Просто очень хочеться доделать этот скрипт!

Добавлено (10.03.2012, 10:00)
———————————————
MyACT, Всё я разобрался, я нашел в инете этот скрипт написаный другим челом, если хочешь можешь глянуть:
[code]
// Выводит бар показывающий сосотояние здоровья игрока

using UnityEngine;
using System.Collections;

public class PlayerHealth : MonoBehaviour {
//публичные переменные для настроек
public int maxHealth = 100;

//блок переменных локального пользования
private int _curHealth = 100;
private float healthBarLength;

//производятся начальные расчеты при создании объекта
void Start () {
//задаем начальную ширину бара здоровья
healthBarLength = Screen.width /2;
//предотвращаем ввод неправильного значения
//максимального значения
if(maxHealth<1) maxHealth=1;
_curHealth = maxHealth;
}

void Update () {

}
// Выводится сам бар посредством графического интерфейса
//событие вывода этого интерфейса — стандартое
void OnGUI() {
//выводится бар состояния здоровья и числовые значения его
GUI.Box(new Rect(10,10,healthBarLength,20),_curHealth + «/» +maxHealth);
}
// Производим расчет нужной ширины бара состояния здоровья
//исходя из текущего состояния здоровья
public void AddjustCurrentHealth( int adj){
_curHealth = adj;
//блок по предотвращению неверного состояния здоровья
//меньше нуля и больше максимума
//так как изменяем здоровье из вне
if(_curHealth < 0) _curHealth = 0;
if(_curHealth > maxHealth) _curHealth = maxHealth;
//расчет бара непосредственно
healthBarLength = (Screen.width / 2) * (_curHealth / (float)maxHealth);
}
}

MyACT Дата: Суббота, 10 Марта 2012, 11:51 | Сообщение # 5

C# CODERS

Сейчас нет на сайте

Sniper00766, ну исходи из ошибок в консоли там нет символов,и где то недочет.
Надеюсь ты понял ошибку сравнив те два кода? smile


3дэшечки: https://sketchfab.com/myactyindie
Курентли воркс он: https://myacty.itch.io/raskopnik

Sniper00766 Дата: Суббота, 10 Марта 2012, 14:03 | Сообщение # 6

частый гость

Сейчас нет на сайте

MyACT, Да понял, спасибо за помощь!
rudolf86 Дата: Среда, 14 Марта 2012, 18:45 | Сообщение # 7

частый гость

Сейчас нет на сайте

всем привет ,у меня такая проблема, открываю демо проект а когда нажимаю pley пишет (( all compiler errors have to be fixed before you can enter playmode! )) игра не запускается ..

Добавлено (14.03.2012, 18:45)
———————————————
всем привет ,у меня такая проблема, открываю демо проект а когда нажимаю pley пишет (( all compiler errors have to be fixed before you can enter playmode! )) игра не запускается ..

Добавлено (14.03.2012, 18:45)
———————————————
всем привет ,у меня такая проблема, открываю демо проект а когда нажимаю pley пишет (( all compiler errors have to be fixed before you can enter playmode! )) игра не запускается ..


ajgjdajgadm

05142 Дата: Среда, 14 Марта 2012, 18:56 | Сообщение # 8

постоянный участник

Сейчас нет на сайте

rudolf86, ну так прочитай что написано и исправь эти ошибки.


mecinvader

MyACT Дата: Четверг, 15 Марта 2012, 04:19 | Сообщение # 9

C# CODERS

Сейчас нет на сайте

rudolf86, значит в каком то скрипте неполадка


3дэшечки: https://sketchfab.com/myactyindie
Курентли воркс он: https://myacty.itch.io/raskopnik

Pashko Дата: Воскресенье, 25 Марта 2012, 10:05 | Сообщение # 10

уже был

Сейчас нет на сайте

У меня была такая же ошибка, причем в чистом проекте. Переустановка Unity помогла.
MyACT Дата: Воскресенье, 25 Марта 2012, 13:55 | Сообщение # 11

C# CODERS

Сейчас нет на сайте

Pashko, лол что?!Что за бред ты сказал?


3дэшечки: https://sketchfab.com/myactyindie
Курентли воркс он: https://myacty.itch.io/raskopnik

Jericho Дата: Четверг, 29 Марта 2012, 15:35 | Сообщение # 12

Ubuntu 11.10 user

Сейчас нет на сайте

Pashko, ага не заработала опера снес винду так получается?


Уютненькая страничка Ерихона

xxx: Так вы представляете, у него там фрагмент кода в 15 строк повторяется 37 раз. Если вынести в функцию можно сэкономить полтыщи строк!
yyy: это припев.
© Антон Антоненко

MyACT Дата: Четверг, 29 Марта 2012, 15:46 | Сообщение # 13

C# CODERS

Сейчас нет на сайте

Jericho, да,получается так.Он либо тролль,либо не понял о чем речь


3дэшечки: https://sketchfab.com/myactyindie
Курентли воркс он: https://myacty.itch.io/raskopnik

Сообщение отредактировал MyACTПятница, 30 Марта 2012, 14:36

  • Страница 1 из 1
  • 1

Antoffa

0 / 0 / 0

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

Сообщений: 37

1

10.09.2021, 16:45. Показов 4214. Ответов 14

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


Ошибка на main.cs(25,5): error CS1525: Unexpected symbol `<‘
не запускается , что не так ???

Ошибка main.cs(25,5): error CS1525: Unexpected symbol `<'

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
using System;
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            double x;
            double y;
            double z;
            double F = 0;
            char check;
 
            do
            {
                Console.WriteLine("Введите значение переменной x");
                Console.Write("x =");
                x = double.Parse(Console.ReadLine());
                Console.WriteLine("Введите значение переменной y");
                Console.Write("y =");
                y = double.Parse(Console.ReadLine());
                z = x - y;
                switch (z)
                {
                    case < 0:
                        F = Math.Sin(x) + Math.Cos(y) * Math.Cos(y);
                        break;
                    case 0:
                        F = Math.Log(x);
                        break;
                    case > 0:
                        F = Math.Sin(x) * Math.Sin(x) + Math.Cos(y);
                        break;
                }
                Console.WriteLine("F =" + F);
                Console.WriteLine("Хотите запустить программу вновь? Y/N");
                check = char.Parse(Console.ReadLine());
            } while (check == 'Y' || check == 'y');
        }
    }
}

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



0



Programming

Эксперт

94731 / 64177 / 26122

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

Сообщений: 116,782

10.09.2021, 16:45

Ответы с готовыми решениями:

Ошибка main.cs(17,11): error CS1525: Unexpected symbol `void’, expecting `class’, `delegate’, `enum’, `interface’,
Выскакивает ошибка main.cs(17,11): error CS1525: Unexpected symbol `void’, expecting `class’,…

Ошибка CS1525 Unexpected symbol
Помогите пожалуйста решить ошибку (38,2):error CS1525:Unexpected symbol {
Вот код:
using…

Opencv error :-1: ошибка: main.o: undefined reference to symbol ‘_ZN2cv6String10deallocateEv’
Добрый вечер, только начинаю знакомится с opencv
Появились проблемы при запуске первого примера

error C2601: ‘main’ : local function definitions are illegal fatal error C1004: unexpected end of file found
День добрый люди написал програму выдает 2 ошибки че не так подскажите

error C2601: ‘main’ :…

14

Модератор

Эксперт .NET

13302 / 9586 / 2574

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

Сообщений: 28,283

Записей в блоге: 2

10.09.2021, 17:05

2

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

error CS1525: Unexpected symbol `<‘

case может только сравнить со значением или шаблоном.
Замените switch-case на if-else if-else.



0



zhunshun

603 / 445 / 196

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

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

10.09.2021, 17:13

3

Antoffa, Так нельзя делать
напиши функцию

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
using System;
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            double x;
            double y;
            double z;
            double F = 0;
            char check;
 
            do
            {
                Console.WriteLine("Введите значение переменной x");
                Console.Write("x =");
                x = double.Parse(Console.ReadLine());
                Console.WriteLine("Введите значение переменной y");
                Console.Write("y =");
                y = double.Parse(Console.ReadLine());
                z = x - y;
                switch (returnValue(z))
                {
                    case < 0:
                        F = Math.Sin(x) + Math.Cos(y) * Math.Cos(y);
                        break;
                    case 0:
                        F = Math.Log(x);
                        break;
                    case > 0:
                        F = Math.Sin(x) * Math.Sin(x) + Math.Cos(y);
                        break;
                }
                Console.WriteLine("F =" + F);
                Console.WriteLine("Хотите запустить программу вновь? Y/N");
                check = char.Parse(Console.ReadLine());
            } while (check == 'Y' || check == 'y');
        }
        static int returnValue(int number){
            if(number > 0) return 1;
            if(number < 0) return -1;
            return 0;
        }
    }
}



0



Antoffa

0 / 0 / 0

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

Сообщений: 37

10.09.2021, 17:18

 [ТС]

4

Через if else правильно работает, необходимо преобразовать в switch, такая задача стояла

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
using System;
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            double x;
            double y;
            double F;
            char check;
            do
            {
                Console.WriteLine("Введите значение переменной x");
                Console.Write("x =");
                x = double.Parse(Console.ReadLine());
                Console.WriteLine("Введите значение переменной y");
                Console.Write("y =");
                y = double.Parse(Console.ReadLine());
                if (x < y)
                {
                    F = Math.Sin(x) + Math.Cos(y) * Math.Cos(y);
                }
                else if (x == y)
                {
                    F = Math.Log(x);
                }
                else
                {
                    F = Math.Sin(x) * Math.Sin(x) + Math.Cos(y);
                }
                Console.WriteLine("F =" + F);
                Console.WriteLine("Хотите запустить программу вновь? Y/N");
                check = char.Parse(Console.ReadLine());
            } while (check == 'Y' || check == 'y');
        }
    }
}

Добавлено через 4 минуты
Через if else правильно работает, необходимо преобразовать в switch, такая задача стояла



0



1346 / 835 / 419

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

Сообщений: 2,603

10.09.2021, 17:26

5

Antoffa, Вам же выше написали, что swith не работает с операторами. Может вы не так поняли свою задачу?



0



0 / 0 / 0

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

Сообщений: 37

10.09.2021, 17:34

 [ТС]

6

Первоначально было через if else, но надо было изменить решение этой задачи, и поэтому подумал делать через switch. Как можно еще изменить данное решение ????



0



603 / 445 / 196

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

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

10.09.2021, 17:38

7

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

Как можно еще изменить данное решение ????

А что мои вариант не подходит??



0



1465 / 1006 / 456

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

Сообщений: 2,793

10.09.2021, 17:46

8

Цитата
Сообщение от Элд Хасп
Посмотреть сообщение

case может только сравнить со значением или шаблоном.

В C#9 этот код скомпилируется.

Antoffa, если хотите, чтобы case работал способом, указанным вами, создайте консольное приложение с поддержкой .NET Core и в свойствах проекта укажите целевую рабочую среду .NET 5.0. Или используйте вместо switch/case конструкцию if/else.



0



Элд Хасп

Модератор

Эксперт .NET

13302 / 9586 / 2574

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

Сообщений: 28,283

Записей в блоге: 2

10.09.2021, 18:32

9

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

В C#9 этот код скомпилируется.

Ну, очевидно же, что TC не использует эту версию.

Добавлено через 3 минуты

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

Как можно еще изменить данное решение ????

Примените условный оператор:

C#
20
21
22
23
24
    F = x < y
        ? Math.Sin(x) + Math.Cos(y) * Math.Cos(y)
        : x == y
        ? Math.Log(x)
        : Math.Sin(x) * Math.Sin(x) + Math.Cos(y);



0



1465 / 1006 / 456

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

Сообщений: 2,793

10.09.2021, 18:33

10

Цитата
Сообщение от Элд Хасп
Посмотреть сообщение

Ну, очевидно же, что TC не использует эту версию.

Однако код написал правильно. Это легко сделать, загуглив описание использования switch в справке Microsoft, к примеру.
https://docs.microsoft.com/ru-… statements

А вот то, что надо и соответствующую версию языка использовать при этом, уже не так очевидно.

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

Через if else правильно работает, необходимо преобразовать в switch, такая задача стояла

Элд Хасп, к тому же в задании четко сказано, что нужно использовать для этого switch, а, значит, лекции могли проводиться по этой версии языка.

Конечно, возможно все это мои догадки.



0



Модератор

Эксперт .NET

13302 / 9586 / 2574

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

Сообщений: 28,283

Записей в блоге: 2

10.09.2021, 18:38

11

Antoffa, но уточните у преподавателя на каком платформе и версии Шарпа допустимо выполнять задание.
Если допустима версия 9, то, как выше написал QuakerRUS, в ней скомпилируется и вариант с switch-case.

Добавлено через 2 минуты

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

к тому же в задании четко сказано, что нужно использовать для этого switch

Когда я отвечал, этого не было сказано.
Кроме того, постом позже TC поправляется, в задании нужно сделать «по другому».
А switch — это его попытка другой реализации.



1



1465 / 1006 / 456

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

Сообщений: 2,793

10.09.2021, 18:44

12

Цитата
Сообщение от Элд Хасп
Посмотреть сообщение

Кроме того, постом позже TC поправляется, в задании нужно сделать «по другому».

Тогда может быть все банальнее, например, преподавателю не понравилось, что расчет формулы не вынесен в отдельный метод.

Добавлено через 4 минуты
Antoffa, вы бы для начала узнали, что именно не понравилось преподавателю.



1



Antoffa

0 / 0 / 0

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

Сообщений: 37

10.09.2021, 19:31

 [ТС]

13

Вот так ???

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
using System;
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            double x;
            double y;
            double z;
            double F = 0;
            char check;
 
            do
            {
                Console.WriteLine("Введите значение переменной x");
                Console.Write("x =");
                x = double.Parse(Console.ReadLine());
                Console.WriteLine("Введите значение переменной y");
                Console.Write("y =");
                y = double.Parse(Console.ReadLine());
                z = x - y;
                 F = x < y
        ? Math.Sin(x) + Math.Cos(y) * Math.Cos(y)
        : x == y
        ? Math.Log(x)
        : Math.Sin(x) * Math.Sin(x) + Math.Cos(y);
 
                Console.WriteLine("F =" + F);
                Console.WriteLine("Хотите запустить программу вновь? Y/N");
                check = char.Parse(Console.ReadLine());
            } while (check == 'Y' || check == 'y');
        }
        static int returnValue(int number){
            if(number > 0) return 1;
            if(number < 0) return -1;
            return 0;
        }
    }
}



0



Модератор

Эксперт .NET

13302 / 9586 / 2574

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

Сообщений: 28,283

Записей в блоге: 2

10.09.2021, 19:33

14

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

Вот так ???

Да.

Добавлено через 21 секунду
Antoffa, по интерфейсу Форума:

 Комментарий модератора 
При обращении к другому пользователю указывайте его ник в тегах [NICK][/NICK] или цитируйте часть сообщения на которое отвечаете.
В противном случае ему не придёт уведомление о вашем обращении и вы можете не дождаться ответа на своё сообщение.

Для вставки ника: введите ник, выделите его и нажмите кнопку «Динамик» на панели редактора сообщений.
Или кликните по нику автора сообщения в панели слева от текста его сообщения.

Для вставки цитаты: выделите нужную цитату, должна появиться всплывающая кнопка «Цитировать», нажмите её.

Добавлено через 35 секунд
Antoffa, и заключайте код в теги.
Для этого есть кнопки в панели редактора сообщений.



0



Antoffa

0 / 0 / 0

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

Сообщений: 37

10.09.2021, 19:48

 [ТС]

15

А можно данный вариант решить еще через цикл??

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

C#
23
24
25
26
27
                 F = x < y
        ? Math.Sin(x) + Math.Cos(y) * Math.Cos(y)
        : x == y
        ? Math.Log(x)
        : Math.Sin(x) * Math.Sin(x) + Math.Cos(y);

Добавлено через 1 минуту
Ну или данную задачу

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

А можно данный вариант решить еще через цикл??



0



Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Li Yu

I am sure that every «{» has its equally paired «}» in my code, but the compiler keep telling me that Program.cs(20,40): error CS1525: Unexpected symbol `}’.
I wonder where my mistake is, and how can I fix it?


Program.cs

using System;

namespace Treehouse.CodeChallenges
{
    class Program
    {
        static void Main()
        {
            while(true)  //loop started
            {
                Console.Write("Enter the number of times to print "Yay!": ");
                string entry = Console.ReadLine();

                    if(entry.ToLower()=="quit")
                    {
                        break;
                    }
                    else
                    {
                        int time = int.Parse(entry);  //turn "string" into "int"
                        int k;
                        for(k = 0; k < time)  //make the loop run k times
                        {
                            Console.Write("Yay!");
                            k = k + 1;
                            continue;
                        }    
                    }

                break;  //leave the "while loop" since "for" is not satisfied
            }    
        }
    }
}

2 Answers

Steven Parker

:point_right: Your program «works», but deviates from the instructions.

This is a great example of how something that works (will compile an run) might not be what was asked for (satisfies the requirements). This has been a topic of many previous questions, but I’ll repost the info here:

People often over-think this one and get too creative, and their answer is rejected for a variety of reasons (some which don’t seem to make any sense).

Here are the secret «rules» you must follow for success on this one:

  • Your program must ask for and accept input ONE TIME ONLY
  • If the input validates, your program will perform exactly as in Task 1
  • If the input does not validate, it will print the error message and exit
  • Validation must be done by exception catching. There are other perfectly good methods that can be used for validation, but they will not pass this challenge

It looks like you have an extra loop that is violating the first and third «rule».

Avan Sharma

using System;

namespace Treehouse.CodeChallenges
{
    class Program
    {
        static void Main()
        {
                              Console.Write("Enter the number of times to print "Yay!": ");
                                    int entry = int.Parse(Console.ReadLine());
                            for(int i=0;i<entry;i++)
                           {
                                 Console.WriteLine("Yay!");
                            }
         }
    }
}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlaerMufment : MonoBehaviour {

    CharacterController cc;
    Vector3 moveVec;

    float speed = 5;

    int laneNamber = 1,
        lanesCount = 2;

    public float FirstlanePos,
                 LaneDistance,
                 SideSpeed;


    void Start()
    {
        cc = GetComponent<CharacterController>();
        moveVec = new Vector3(1, 0, 0);
    }

    


    void Update()
    {
        moveVec.x *= speed;
        moveVec *= Time.deltaTime;

        float imput = Input.GetAxis("Horizontal");

        if (Mathf.Abs(input) >.if);
        {
            laneNamber += (int)Matht.Sign(input);
            laneNamber = Mathf.Clamp(laneNamber, 0, lanesCount);
        }

        Vectore3 newPos = transfore.position;
        newPos.z = Mathf.Lerp(newPos.z, FirstLanePos + (laneNamber * LaneDistance), Time.deltaTime * SideSpeed);
        transform.position = newPos;

        cc.Move(moveVec);
    }
}

AssetsSkriptPlaerMufment.cs(36,31): error CS1525: Invalid expression term ‘.’
AssetsSkriptPlaerMufment.cs(36,32): error CS1001: Identifier expected
AssetsSkriptPlaerMufment.cs(36,32): error CS1026: ) expected
AssetsSkriptPlaerMufment.cs(36,34): error CS1003: Syntax error, ‘(‘ expected
AssetsSkriptPlaerMufment.cs(36,34): error CS1525: Invalid expression term ‘)’

Понравилась статья? Поделить с друзьями:
  • Error cs1525 unexpected symbol end of file
  • Error cs1525 invalid expression term unity
  • Error cs1525 invalid expression term string
  • Error cs1525 invalid expression term int
  • Error cs1520 method must have a return type unity