I am trying to do a program, that checks if a given .txt file, containing a C# code, has valid brackets.
When i paste a simple code like this:
if(true)
{
Console.WriteLine("Hello");
}
My program says it is valid, which is true. But if i remove a bracket, like this:
if(true)
{
Console.WriteLine("Hello");
It still says it's valid.
Here is my method for checking brackets:
static void CheckBrackets()
{
try
{
Console.Write("You file name (Default path is .....\\netcoreapp2.1\\): ");
Console.ForegroundColor = ConsoleColor.Blue;
string fileName = Console.ReadLine();
Stack openingBrackets = new Stack();
Queue closingBrackets = new Queue();
using (StreamReader reader = new StreamReader(fileName))
{
bool check = true;
string str = reader.ReadToEnd();
char[] code = str.ToCharArray();
foreach (char ch in code)
{
if(ch == '(' || ch == '[' || ch == '{')
{
openingBrackets.Push(ch);
}
else if(ch == ')' || ch == ']' || ch == '}')
{
closingBrackets.Enqueue(ch);
}
}
while (openingBrackets.Count == 0 && closingBrackets.Count == 0)
{
char currentOpeningBracket = (char)openingBrackets.Pop();
char currentClosingBracket = (char)closingBrackets.Dequeue();
if ((currentOpeningBracket == '(' && currentClosingBracket != ')')
|| (currentOpeningBracket == '[' && currentClosingBracket != ']')
|| (currentOpeningBracket == '{' && currentClosingBracket != '}'))
{
check = false;
}
}
if(check == true)
{
Console.WriteLine("Valid.");
}
else
{
Console.WriteLine("Not valid.");
}
}
}
catch (Exception exp)
{
...
}
}
Any ideas why it doesn't work?
You should modify the while
section of your code with this:
if (openingBrackets.Count != closingBrackets.Count)
{
check = false;
}
else
{
while (openingBrackets.Count > 0 && closingBrackets.Count > 0)
{
char currentOpeningBracket = (char)openingBrackets.Pop();
char currentClosingBracket = (char)closingBrackets.Dequeue();
if ((currentOpeningBracket == '(' && currentClosingBracket != ')')
|| (currentOpeningBracket == '[' && currentClosingBracket != ']')
|| (currentOpeningBracket == '{' && currentClosingBracket != '}'))
{
check = false;
}
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments