Click here to Skip to main content
15,885,898 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
int ans;
Console.Write("2+3+1= ");
ans=Convert.ToInt32(Console.ReadLine());
if(ans==6) {
Console.WriteLine("Correct");
}else{
Console.WriteLine("wrong");
}
Problems:
A local variable or function named 'ans' is already defined in this scope
Use of unassigned local variable 'ans'

What I have tried:

i removed all the text and wrote them again didnt work.
Posted
Updated 21-May-21 5:31am

1 solution

That isn't all your code: that code on it's own generates no errors, and runs, doing what you expected it to:
C#
using System;
using System.Collections.Generic;
using System.IO;

public class Program
    {
    public static void Main()
        {
        int ans;
        Console.Write("2+3+1= ");
        ans=Convert.ToInt32(Console.ReadLine());
        if(ans==6) 
            {
            Console.WriteLine("Correct");
            }
        else
            {
            Console.WriteLine("wrong");
            }
        }
    }
Somewhere else in the same scope in your code, you are declaring something called "ans" - a variable, constant, or even a method!

And don't use Convert methods on user input - they will cause you app to crash if the user enters a non-numeric character. Use the TryParse methods instead: Int32.TryParse Method (System) | Microsoft Docs[^]. They return a bool "OK / Failed" result so you can give them another chane.
 
Share this answer
 
Comments
Suleman Malik 21-May-21 11:41am    
thank you
OriginalGriff 21-May-21 12:02pm    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900