Как исправить cs0103

Только сегодня начал изучать C#, и вот столкнулся с ошибкой CS0103, Имя “а” не существует в текущем контексте. Гугл решение не рассказал, на удивление.

using System;

namespace C_Sharp

{
    class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Hi! Type your name here: ");
            try
            {
                int a = int.Parse(Console.ReadLine());
            }
            catch (Exception) {
                Console.WriteLine("Can't convert");
            }
            Console.WriteLine($"Thanks, {a}!");
            Console.ReadKey();
        }
    }
}

задан 5 мая 2020 в 19:56

Werflame Xij's user avatar

Переменная a у вас определена внутри блока try. Вне его она не видна.

Можно весь код поместить внутри блока:

public static void Main(string[] args)
{
    Console.WriteLine("Hi! Type your name here: ");
    try
    {
        int a = int.Parse(Console.ReadLine());
        Console.WriteLine($"Thanks, {a}!");
        Console.ReadKey();
    }
    catch (Exception) {
        Console.WriteLine("Can't convert");
    }
}

Или определить a до блока try-catch

public static void Main(string[] args)
{
    Console.WriteLine("Hi! Type your name here: ");
    int a;
    try
    {
        a = int.Parse(Console.ReadLine());
    }
    catch (Exception) {
        Console.WriteLine("Can't convert");
        return;
    }
    Console.WriteLine($"Thanks, {a}!");
    Console.ReadKey();
}

ответ дан 5 мая 2020 в 20:05

Кирилл Малышев's user avatar

Кирилл МалышевКирилл Малышев

10.8k1 золотой знак18 серебряных знаков34 бронзовых знака

Asked
4 years, 5 months ago

Viewed
5k times

I am working on a project that creates a simple perimeter and area calculator based on the values the user inputs. (For finding window perimeter and glass area). However, I’m stuck with 4 errors… all of which are CS0103. Can anyone help me fix these errors or clean up my code. I’m trying to separate everything into methods so I would like to keep the code in that general format.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            double totalLength, totalWidth, windowPerimeter, glassArea;

            //display instructions
            DisplayInstructions();

            // ask for width
            totalWidth = AskDimension();

            //ask for lenght
            totalLength = AskDimension();

            // calculate window Perimeter
            windowPerimeter = (2 * totalWidth) * (2 * totalLength);

            //calculate the area of the window & display output
            glassArea = totalWidth * totalLength;

            //calculate and display outputs

            Console.WriteLine("the lenth of the wood is " + windowPerimeter + " feet");
            Console.WriteLine("the area of the glass is " + glassArea + " square feet");
            Console.ReadKey();

            Console.ReadKey();
        }

        //display instructions
        public static void DisplayInstructions()
        {
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("This app will help you calculate the amount of wood and glass needed for your new windows!");
            Console.WriteLine("   ");
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("*Note* Please enter a height/width value between 0.01 - 100, all other values will cause a system error.");
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("   ");
        }

        //ask for width
        public static double AskDimension()
        {
            double totalWidth;
            const double MAX_HEIGHT = 100.0;
            const double MIN_Height = 0.01;
            string widthString;
            Console.WriteLine("please enter your height of the window");
            widthString = Console.ReadLine();
            totalWidth = double.Parse(widthString);
            if (totalWidth < MIN_Height)
            {
                Console.WriteLine("you enter vaule less than min width n" + "using minimum one");
                totalWidth = MIN_Height;
            }
            if (totalWidth > MAX_HEIGHT)
            {
                Console.WriteLine("you enter value grater than Max heightn" + "using maximum one");
                totalWidth = MAX_HEIGHT;
            }

            return AskDimension();
        }

        //ask for height
        public static double AskDimension(string dimension)
        {
            double totalLength;
            const double MAX_HEIGHT = 100.0;
            const double MIN_Height = 0.01;
            string heightString;
            Console.WriteLine("please enter your height of the window");
            heightString = Console.ReadLine();
            totalLength = double.Parse(heightString);
            if (totalLength < MIN_Height)
            {
                Console.WriteLine("you enter vaule less than min width n" + "using minimum one");
                totalLength = MIN_Height;
            }
            if (totalLength > MAX_HEIGHT)
            {
                Console.WriteLine("you enter value grater than Max heightn" + "using maximum one");
                totalLength = MAX_HEIGHT;
            }

            return AskDimension();
        }
        //calculate and display outputs
        public static double AskDimesnion(string windowPerimeter,
                                          string glassArea,
                                          string widthString,
                                          string heightString)

        {

            windowPerimeter = 2 * (totalWidth + totalLength);
            glassArea = (totalWidth * totalLength);
            Console.WriteLine("the lenth of the wood is " + windowPerimeter + " feet");
            Console.WriteLine("the area of the glass is " + glassArea + " square feet");
            Console.ReadKey();
            return AskDimension();
        }
}
}

Screenshot of errors in the method:
Screenshot of errors in the method

dymanoid's user avatar

dymanoid

14.7k4 gold badges36 silver badges64 bronze badges

asked Dec 11, 2018 at 16:30

7

Your totalWidth variable is not defined anywhere in your scope. It should be defined somewhere. Depending on where you exactly want to define it, you can do it internally in your AskDimension method or more globally. It seem by your logic it should be an input parameter of your method. Also you have other errors in your code. Your method is called AskDimesnion but you are calling it in your code by AskDimension (hopefully the correct method name…)

For variable scope, you can check Microsoft’s own documentation

answered Dec 11, 2018 at 16:36

Alfredo A.'s user avatar

Alfredo A.Alfredo A.

1,6873 gold badges30 silver badges43 bronze badges

1

The initial problem was that your variables weren’t class scoped and also the calculations seem a bit crazy to me. But from pasting your code in to my editor I’ve had a quick tidy up and come out with the following:

using System;

namespace TestConsoleApplication
{
    class Program
    {
        static double _totalLength, _totalWidth, _windowPerimeter, _glassArea;

        static void Main(string[] args)
        {
            DisplayInstructions();
            _totalWidth = AskDimension("Height");
            _totalLength = AskDimension("Width");
            _windowPerimeter = (2 * _totalWidth) + (2 * _totalLength);
            _glassArea = _totalWidth * _totalLength;
            Console.WriteLine("The length of the wood is " + _windowPerimeter + " feet");
            Console.WriteLine("The area of the glass is " + _glassArea + " square feet");
            Console.ReadKey();
        }

        private static void DisplayInstructions()
        {
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("This app will help you calculate the amount of wood and glass needed for your new windows!");
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("*Note* Please enter a height/width value between 0.01 - 100, all other values will cause a system error.");
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine();
        }

        private static double AskDimension(string dimensionType)
        {
            const double maxDimension = 100.0;
            const double minDimension = 0.01;

            Console.WriteLine($"Please enter your {dimensionType} of the window");

            var dimensionString = Console.ReadLine();
            var dimension = double.Parse(dimensionString);

            if (dimension < minDimension)
            {
                DisplayDimensionErrorAndExit("Min");
            }
            else if (dimension > maxDimension)
            {
                DisplayDimensionErrorAndExit("Max");
            }

            return dimension;
        }

        private static void DisplayDimensionErrorAndExit(string dimensionToShow)
        {
            Console.WriteLine($"You entered a value less than {dimensionToShow} dimension");
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
            Environment.Exit(0);
        }
    }
}

If a user enters invalid input the program will terminate, apart from that the calculations work and the correct output displayed.
If you’ve got any questions about it at all just ask me 🙂

answered Dec 11, 2018 at 17:01

Coops's user avatar

CoopsCoops

2613 silver badges7 bronze badges

2

C# Compiler Error

CS0103 – The name ‘identifier’ does not exist in the current context

Reason for the Error

You will usually receive this error when you are trying to use a identifier name in C# that doesnot exist with-in the current scope. One of the simple example of this error is when you declare a variable with-in a try block and try to access it in the catch block.

In the below example, the variable i is declared inside the try block, so its scope is restricted to the try block. When you try accessing it in the catch block is when you will receive the error.

using System;

public class DeveloperPublish
{
    public static void Main()
    {       
        try
        {
            int i = 1;
            int j = 0;
            int result = i / j;
        }
        catch(DivideByZeroException)
        {
            string message = i + " is divivided by zero";
            Console.WriteLine(message);
        }

    }
}

Error CS0103 The name ‘i’ does not exist in the current context ConsoleApp1 C:UsersSenthilsourcereposConsoleApp1ConsoleApp1Program.cs 16 Active

Solution

To fix the error move the declaration of the identifier that is causing the error to a higher scope so that it is available when it is accessed.

For example, to fix the error in the above code snippet, we just need to move the declaration of the identifier outside of the try block.

using System;

public class DeveloperPublish
{
    public static void Main()
    {
        int i = 1;
        try
        {          
            int j = 0;
            int result = i / j;
        }
        catch(DivideByZeroException)
        {
            string message = i + " is divivided by zero";
            Console.WriteLine(message);
        }

    }
}

Почему ошибка AssetsScriptsEnemy.cs(69,25): error CS0103: The name ‘startTimeBtwAttack’ does not exist in the current context
я нуб

вот код:

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

public class Enemy : MonoBehaviour
{
private float timeBtwAttack;
public float startTimeBrwAttack;
public int health;

public float speed;
public GameObject deathEffect;
public int damage;
private float stopTime;
public float startStopTime;
public float normalSpeed;
private Player player;
private Animator anim;

private void Start()
{
anim = GetComponent<Animator>();
player = FindObjectOfType<Player>();
normalSpeed = speed;
}

private void Update()
{
if(stopTime<= 0)
{
speed = normalSpeed;
}
else
{
speed = 0;
stopTime -= Time.deltaTime;
}
if(health <= 0)
{
Destroy(gameObject);
}
transform.Translate(Vector2.left * speed * Time.deltaTime);
}

public void TakeDamage(int damage)
{
stopTime = startStopTime;
Instantiate(deathEffect, transform.position, Quaternion.identity);
health -= damage;
}
public void OnTriggerStay2D(Collider2D other)
{
if(other.CompareTag(“Player”))
{
if(timeBtwAttack <= 0)
{
anim.SetTrigger(“attack”);
}
else
{
timeBtwAttack -= Time.deltaTime;
}
}
}
public void OnEnemyAttack()
{
Instantiate(deathEffect, player.transform.position, Quaternion.identity);
player.health -= damage;
timeBtwAttack = startTimeBtwAttack;
}
}

  • Remove From My Forums
  • Question

  • User397255882 posted

    My asp.net page runs fine in VWD Express 2010 but on the server i get this error:

    error CS0103: The name 'DropDownList_Nodes' does not exist in the current context
    If anyone can help me I would appreciate it.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;
    using System.Data.SqlClient;
    
    namespace OrionNodeEvent
    {
        public partial class _Default : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {     
                if (!this.IsPostBack)//only do on 1st page load
                {
                    FillListBox();
                }            
            }//end Page_Load
    
            protected void Submit_Click(object sender, EventArgs e)
            {
                string connectionString = @"data source=****;initial catalog=****;user id=*****;" +
                        "password=****;packet size=4096;persist security info=False;connect timeout=30000; Trusted_Connection=yes";            
                string insertSQL;
                DateTime currentTime = DateTime.UtcNow; 
                insertSQL = @"USE **** INSERT INTO ***** (";
                insertSQL += "Node_Name, Event, Solution, Time) ";
                insertSQL += "VALUES ('";            
                insertSQL += DropDownList_Nodes.SelectedItem.ToString()  + "', '";
                insertSQL += TextBox_Event.Text + "', '";
                insertSQL += TextBox_Solution.Text + "', '";
                insertSQL += currentTime + "')";
    
                SqlConnection sql_connection = new SqlConnection(connectionString);
                SqlCommand sql_command = new SqlCommand(insertSQL, sql_connection);
    
                int added = 0;//counter for rows inserted to DB
                try
                {                
                    sql_connection.Open();
                    added = sql_command.ExecuteNonQuery();
                    Label_Info.Text = added.ToString() + " records inserted.";
                }
                catch(Exception error)
                {
                    Label_Info.Text = error.Message;                
                }
                finally
                {
                    sql_connection.Close();
                    sql_connection.Dispose();
                }
                 
            }//end Submit_Click
            protected void FillListBox()
            {
                string connectionString = @"data source=****;initial catalog=****;user id=****;" +
                        "password=****;packet size=4096;persist security info=False;connect timeout=30000; Trusted_Connection=yes";
                
                DropDownList_Nodes.Items.Clear();
                string selectSQL = @"USE **** SELECT ***, *** FROM *** ORDER BY ***";
    
                SqlConnection sql_connection = new SqlConnection(connectionString);
                SqlCommand sql_command = new SqlCommand(selectSQL, sql_connection);
                SqlDataReader sql_reader;
                  try
                {                
                    sql_connection.Open();
                    sql_reader = sql_command.ExecuteReader();
                    while (sql_reader.Read())
                    {
                        ListItem newitem = new ListItem();
                        newitem.Text = sql_reader["****"].ToString();
                        newitem.Value = sql_reader["****"].ToString();
                        DropDownList_Nodes.Items.Add(newitem);
                    }//end while
                    sql_reader.Close();
                    sql_reader.Dispose();
                }//end try
                catch(Exception error)
                {
                    Label_Info.Text = error.Message;               
                }
                finally
                {
                    sql_connection.Close();
                    sql_connection.Dispose();
                }
            }//end FillListBox
      	public override void VerifyRenderingInServerForm(Control control)
            {
                return;
            }
        }//end public partial class _Default : System.Web.UI.Page
    }//end namespace OrionNodeEvent
    
    // ASP PAGE ***************************************
    
    <%@  Language="C#"  AutoEventWireup="true"
        CodeBehind="OrionNodeEvent.aspx.cs" Inherits="OrionNodeEvent._Default" Src="OrionNodeEvent.aspx.cs" %>    
    
        <html>
        <head>
        <title>Orionz</title>
        </head>
        <body>
    
        <h2>Select a Node to add an event and resolution.</h2>   
        <p><asp:DropDownList ID="DropDownList_Nodes" runat="server"></asp:DropDownList></p>
       <p><strong>Event</strong><asp:TextBox ID="TextBox_Event" runat="server" style="margin-left: 25px" 
                Width="500px" Height="150px" TextMode="MultiLine" MaxLength="8000"></asp:TextBox></p>
       <p><strong>Solution</strong><asp:TextBox ID="TextBox_Solution" runat="server" 
                style="margin-left: 10px" Width="500px" Height="150px" TextMode="MultiLine" MaxLength="8000"></asp:TextBox> </p>         
       <p><asp:Button ID="Button_Submit" runat="server" Text="Submit" OnClick="Submit_Click"/></p>
        <p><asp:Label ID="Label_Info" runat="server" Text="" ></asp:Label> </p>
        </body>
        </html>
    
    

Answers

  • User397255882 posted

    SOLVED:

    Added these control statements to the Default.aspx.cs:

    protected global::System.Web.UI.HtmlControls.HtmlForm form1;
    protected System.Web.UI.WebControls.Label Label_Info; 
    protected System.Web.UI.WebControls.DropDownList DropDownList_Nodes;
    protected System.Web.UI.WebControls.TextBox TextBox_Event;
    protected System.Web.UI.WebControls.TextBox TextBox_Solution;
    protected System.Web.UI.WebControls.Button Button_Submit;

    The server was ignoring the designer file.

    Now it loads!

    • Marked as answer by

      Thursday, October 7, 2021 12:00 AM

Добавить комментарий