using System;
//Find the square root of a number for 10 values from user
class forLoop
{
static void Main
{
double x;
for(int i=10; i>0 && x>=0; i--)
{
Console.WriteLine("You have {0} remaining calculations left", i);
Console.Write("Please enter a positive number: ");
x = double.Parse((Console.ReadLine());
x = Math.Sqrt(x);
Console.WriteLine("The square root is {0}", x);
Console.WriteLine("");
}
Console.WriteLine("You have 0 remaining calculations left");
}
}
I need help on this C# problem: Why does the error: «A get or set accessor expected» come up at compile time?
Cᴏʀʏ
104k20 gold badges165 silver badges192 bronze badges
asked Nov 3, 2014 at 1:40
1
You missed the ()
in method declaration. Thus, the compiler thinks at some level that you’re declaring a Property (albeit it would then throw an error about the void
type), not a Method
// Property
public int Property
{
get { return _field; }
set { _field = value; }
}
// Property, albeit a get-only property
public int Property => _field;
// Method
public int Method()
{
return _field;
}
// Method
public int Method() => _field;
UPDATE: Since this is still being seen, I’ve updated the example values to better reflect their underlying types, and included examples of expression bodies introduced with C# 6
answered Nov 3, 2014 at 2:02
DavidDavid
10.3k1 gold badge26 silver badges40 bronze badges
You need parentheses (()
) in the method declaration.
answered Nov 3, 2014 at 1:42
SLaksSLaks
857k175 gold badges1886 silver badges1956 bronze badges
0
Parentheses is required to differentiate a method from a property that requires the get/set syntax
answered Feb 24, 2015 at 17:57
madhu131313madhu131313
6,7917 gold badges38 silver badges52 bronze badges
- Remove From My Forums
-
Question
-
Hi!
I am currently working on a project but i get this error: «a get or set accessor expected».What kind of changes i should do to fix that error?
Here’s the code:public static object xard
{
if (button1.Enabled == false)
{
Application.DoEvents();}
if (button1.Enabled == true)
{stopwatch.Stop();
LogWrite(«Time= » + stopwatch.ElapsedMilliseconds);
}
}-
Edited by
Thursday, November 14, 2013 8:44 PM
-
Edited by
Answers
-
Since the «xard» identifier is not followed by parenthesis, the compiler assumes that «xard» is a property. Properties are structured as follows:
public static object xard { get { // "get" accessor code here } set { // "set" accessor code here } }
Your code does not use those «get» and «set» keywords, so the compiler is raising the error.
If «xard» is a method, then you need to add parenthesis after the identifier:
public static object xard() { if (button1.Enabled == false) { Application.DoEvents(); } if (button1.Enabled == true) { stopwatch.Stop(); LogWrite("Time= " + stopwatch.ElapsedMilliseconds); } }
-
Proposed as answer by
Christopher84
Friday, November 15, 2013 7:35 AM -
Marked as answer by
Waltor123
Friday, November 15, 2013 3:11 PM
-
Proposed as answer by
Maray 4 / 4 / 4 Регистрация: 03.01.2015 Сообщений: 449 |
||||
1 |
||||
16.05.2016, 20:29. Показов 2046. Ответов 3 Метки нет (Все метки)
Добрый день! Помогите, пожалуйста исправить ошибку
Добавлено через 5 минут Добавлено через 1 минуту
__________________
0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
16.05.2016, 20:29 |
Ответы с готовыми решениями: Как исправить ошибку «Не удается преобразовать из «System.Windows.Forms.TextBox» в «bool»? Proxy.Set(new WebProxy("ip адрес", порт)); Хочу сделать что бы данные выводились из… Как исправить ошибку: Неявное преобразование типа «void» в «string» невозможно? Как исправить «преобразование типа из «string» в «System.Net.IPEndPoint» невозможно»? Выдает ошибку — «Не удалось привести тип объекта «TheMaze.FormLevel1» к типу «System.Windows.Forms.Label».» Вот код: 3 |
6187 / 2439 / 717 Регистрация: 11.04.2015 Сообщений: 3,948 Записей в блоге: 43 |
|
17.05.2016, 11:36 |
2 |
В классе D куча ошибок. Имена переменных совпадают с именами свойств, а акцессоры свойств ссылаются на необъявленные имена. C# — регистрозависимый язык, не надо об этом забывать.
1 |
Maray 4 / 4 / 4 Регистрация: 03.01.2015 Сообщений: 449 |
||||||||||||
17.05.2016, 19:45 [ТС] |
3 |
|||||||||||
Вот до этого делал программу, и все работает
Переделал вот так, все равно ошибки
Добавлено через 21 минуту
Добавлено через 41 секунду
0 |
332 / 295 / 134 Регистрация: 14.03.2015 Сообщений: 1,087 Записей в блоге: 1 |
|
17.05.2016, 22:22 |
4 |
осталась все та же ошибка
A get or set accessor expected На каком моменте появляется ошибка? Брейкпоинтами отследите чтоль. Не по теме: Большие участки кода помещайте в блок Код [SPOILER] ваш код здесь [/SPOILER]
0 |
Формулировка задачи:
using System; using System.IO; using System.Text; using System.Threading; namespace optimizationMethods { public class MethodSegmentIntoThree { public static readonly double EPS = 0.0001; public static double f (double x) { return (Math.Sqrt(x*x + 25) + Math.Sqrt ((20-x)*(20-x)+100) +0.1); } public static double[] setSegment() throws IOException //просит поставить // точку с запятой перед throws error CS1002: ; expected { double[] x = new double[4]; //выдаёт error CS1014: A get or set // accessor expected BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); Console.WriteLine("Введите отрезок [a; b], на котором будем искать стационарную точку"); Console.WriteLine("x1 = "); x[0] = Double.parseDouble(reader.readLine()); x[1] = 0; x[2] = 0; Console.WriteLine("x4= "); x[3] = Double.parseDouble(reader.readLine()); System.out.prinln("Ищем стационарную точку..."); return x; } public static double segIntoThree (double[] x) { while ( Math.Abs(x[3] - x[0] ) >=EPS ) { x[1]=x[0]+(x[3]-x[0])/3; x[2]=x[3]-(x[3]-x[0])/3; if (f(x[1]) < f(x[2])) x[3]= x[2]; else x[0] = x[1]; } return (x[0] + x[3] ) / 2; } public static void main(string[] args) { try { double[] x = setSegment(); Console.WriteLine("Точка минимума z = " + segIntoThree(x)); Console.WriteLine("f(z) = " +f(segIntoThree(x))); Console.WriteLine("Значение функции(для проверки): f(z) = f(3) = " +f(6.6667)); } catch (IOException e) { e.printStackTrace(); } } } }
Код к задаче: «Причина ошибки «A get or set accessor expected»»
textual
using System; using System.IO; using System.Text; using System.Threading; namespace optimizationMethods { public class MethodSegmentIntoThree { public static readonly double EPS = 0.0001; public static double f (double x) { return (Math.Sqrt(x*x + 25) + Math.Sqrt ((20-x)*(20-x)+100) +0.1); } public static double[] setSegment() { double[] x = new double[4]; BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); //error CS1041: Identifier expected; 'in' is a keyword // the type of namespace bufferedreader could not be found // the type of namespace InputStreamReader could not be found // error CS1525: Invalid expression term 'in Console.WriteLine("Введите отрезок [a; b], на котором будем искать стационарную точку"); Console.WriteLine("x1 = "); x[0] = Double.parseDouble(reader.readLine()); x[1] = 0; x[2] = 0; Console.WriteLine("x4= "); x[3] = Double.parseDouble(reader.readLine()); System.out.prinln("Ищем стационарную точку..."); return x; } public static double segIntoThree (double[] x) { while ( Math.Abs(x[3] - x[0] ) >=EPS ) { x[1]=x[0]+(x[3]-x[0])/3; x[2]=x[3]-(x[3]-x[0])/3; if (f(x[1]) < f(x[2])) x[3]= x[2]; else x[0] = x[1]; } return (x[0] + x[3] ) / 2; } public static void main(string[] args) { try { double[] x = setSegment(); Console.WriteLine("Точка минимума z = " + segIntoThree(x)); Console.WriteLine("f(z) = " +f(segIntoThree(x))); Console.WriteLine("Значение функции(для проверки): f(z) = f(3) = " +f(6.6667)); } catch (IOException e) { e.printStackTrace(); //error CS1061: //'System.IO.IOException' does not contain a definition for 'printStackTrace' and no extension method 'printStackTrace' //accepting a first argument of type 'System.IO.IOException' could be found (are you missing a using directive or an //assembly reference?) } } } }
Полезно ли:
5 голосов , оценка 3.600 из 5
using System.Collections.Generic;
using UnityEngine;
public class playercombat : MonoBehaviour
{
public Animator animator;
public Transform attackPoint;
public float attackRange = 0.5f;
public LayerMask enemyLayers;
public float AttackRange { get => attackRange; 0.5f => attackRange = 0.5f; }
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Q))
{
Attack();
}
}
void Attack()
{
animator.SetTrigger("Attack");
Physics2D.OverlapCircleAll(attackPoint.postion, AttackRange, enemyLayers);
foreach (Collider2D enemy in hitEnemies)
{
Debug.lot("Hit" + enemy.name);
}
}
void OnDrawGizmosSelected()
{
if (attackPoint == null)
return;
Gizmos.DrawWireSphere(attackPoint.position, AttackRange);
}
}
A get or set accesssor expected. What does that mean and how should I fix it?
Assetsplayercombat.cs(13,52): error CS1014: A get or set accessor expected
Assetsplayercombat.cs(13,60): error CS1014: A get or set accessor expected
Your setter on AttackRange is weird. KYL3R’s answer implies that you want to set attackRange to 0.5f whenever you set it, no matter what you set it to. That seems equally weird. I think you want
public float AttackRange { get => attackRange; set => attackRange = value; }