If-else construct not working

Rinz

Member
Joined
Apr 9, 2020
Messages
21
Programming Experience
Beginner
I need a volunteer to review a C# code. Just some few issues with if-else construct not flowing as expected. Am very new to programming. Please advise.
 
Welcome to the forums.

Can you post the code that you are having trouble with, so we can take a look?

You can also take a look at the if else logic links in my signature for additional detailed documentation.

Please remember to post your code using the code tags provided by the forum as seen below :

codetags-gif.884
 
C#:
namespace BinaryImage_Console
{
    /// <summary>
    /// Program Class of Console App
    /// </summary>
    class Program
    {
        /// <summary>
        /// Main entry point for Program
        /// </summary>
        /// <param name="args">Argument of main method</param>
        static void Main(string[] args)
        {
          
            Console.WriteLine("Welcome to Binary Image Maker");           
            Console.WriteLine("\nUse following command for help:");
            Console.WriteLine("dotnet ImageBinarizerApp -help");
            args = new String[] { Console.ReadLine() };
            
            //Test if necessary input arguments were supplied.
            if (args.Length < 8)
            {
                if(args.Length == 1 && args[0].Equals("-help"))
                {
                    Console.WriteLine("\nHelp:");
                    Console.WriteLine("\nPass the arguments as following:");
                    Console.WriteLine("\nExample with automatic RGB:\ndotnet ImageBinarizerApp --input-image c:\\a.png --output-image d:\\out.txt -width 32 -height 32");
                    Console.WriteLine("\nExample with explicit RGB:\ndotnet ImageBinarizerApp --input-image c:\\a.png --output-image d:\\out.txt -width 32 -height 32 -red 100 -green 100 -blue 100");
                }
                else
                {
                    Console.WriteLine("\nError: All necessary arguments are not passed. Please pass the arguments first.");
                }
                Console.WriteLine("\nPress any key to exit the application.");
                Console.ReadLine();
                return;
            }
            else
            {
                String inputImagePath = "";
                String outputImagePath = "";
                int imageWidth = 0;
                int imageHeight = 0;
                int redThreshold = -1;
                int greenThreshold = -1;
                int blueThreshold = -1;

                if(args[0].Equals("--input-image") && File.Exists(args[1]))
                {
                    inputImagePath = args[1];
                }
                else
                {
                    Console.WriteLine("\nError: Input file doesn't exist.");
                    Console.WriteLine("\nPress any key to exit the application.");
                    Console.ReadLine();
                    return;
                }

                int separatorIndex = args[3].LastIndexOf(Path.DirectorySeparatorChar);
                if (args[2].Equals("--output-image") && separatorIndex >= 0 && Directory.Exists(args[3].Substring(0, separatorIndex)))
                {
                    outputImagePath = args[3];
                }
                else
                {
                    Console.WriteLine("\nError: Output Directory doesn't exist.");
                    Console.WriteLine("\nPress any key to exit the application.");
                    Console.ReadLine();
                    return;
                }

                if (!args[4].Equals("-width") || !int.TryParse(args[5], out imageWidth))
                {
                    Console.WriteLine("\nError: Image Width should be integer.");
                    Console.WriteLine("\nPress any key to exit the application.");
                    Console.ReadLine();
                    return;
                }

                if (!args[6].Equals("-height") || !int.TryParse(args[7], out imageHeight))
                {
                    Console.WriteLine("\nError: Image Height should be integer.");
                    Console.WriteLine("\nPress any key to exit the application.");
                    Console.ReadLine();
                    return;
                }

                if(args.Length > 8)
                {
                    if(args.Length < 14)
                    {
                        Console.WriteLine("\nError: All three Red, Green and Blue Thresholds should be passed.");
                        Console.WriteLine("\nPress any key to exit the application.");
                        Console.ReadLine();
                        return;
                    }
                    else
                    {
                        if (!args[8].Equals("-red") || !(int.TryParse(args[9], out redThreshold)) || redThreshold < 0 || redThreshold > 255)
                        {
                            Console.WriteLine("\nError: Red Threshold should be in between 0 and 255.");
                            Console.WriteLine("\nPress any key to exit the application.");
                            Console.ReadLine();
                            return;
                        }

                        if (!args[10].Equals("-green") || !(int.TryParse(args[11], out greenThreshold)) || greenThreshold < 0 || greenThreshold > 255)
                        {
                            Console.WriteLine("\nError: Green Threshold should be in between 0 and 255.");
                            Console.WriteLine("\nPress any key to exit the application.");
                            Console.ReadLine();
                            return;
                        }

                        if (!args[12].Equals("-blue") || !(int.TryParse(args[13], out blueThreshold)) || blueThreshold < 0 || blueThreshold > 255)
                        {
                            Console.WriteLine("\nError: Blue Threshold should be in between 0 and 255.");
                            Console.WriteLine("\nPress any key to exit the application.");
                            Console.ReadLine();
                            return;
                        }
                    }                   
                }
                else
                {
                    redThreshold = -1;
                    greenThreshold = -1;
                    blueThreshold = -1;
                }

                Console.WriteLine("\nImage Binarization in progress...");

                try
                {
                    ImageBinarizerApplication obj = new ImageBinarizerApplication();
                    obj.Binarizer(inputImagePath, outputImagePath, imageWidth, imageHeight, redThreshold, greenThreshold, blueThreshold);
                }
                catch (Exception e)
                {
                    Console.WriteLine($"\nError: {e.Message}");
                    Console.WriteLine("\nPress any key to exit the application.");
                    Console.ReadLine();
                    return;
                }

                Console.WriteLine("\nImage Binarization completed.");
                Console.WriteLine("\nPress any key to exit the application.");

                Console.ReadLine();
            }           
        }
    }
}
 
Welcome to the forums.

Can you post the code that you are having trouble with, so we can take a look?

You can also take a look at the if else logic links in my signature for additional detailed documentation.

Please remember to post your code using the code tags provided by the forum as seen below :

codetags-gif.884
Thank you for the concern. The subject code has been posted.
 
Please explain EXACTLY what the issue is, i.e. where it is in the code (what you highlighted is not an `if` statement) as well as what you expect to happen and what actually does happen. What specific data is in play at the time might help too, if the aberrant behaviour is data specific.
 
Please explain EXACTLY what the issue is, i.e. where it is in the code (what you highlighted is not an `if` statement) as well as what you expect to happen and what actually does happen. What specific data is in play at the time might help too, if the aberrant behaviour is data specific.

Once I run the program, am only able to enter arguments till '-help' and after that the console application exits (regardless of entering other valid arguments / parameters). Please find attached the snapshot of the debug console for clarification. I want to be able to enter the arguments as specified in the code and have the program flow behave sequentially depending on the arguments selected per time.
 

Attachments

  • Console_Debug.png
    Console_Debug.png
    37.6 KB · Views: 22
Have you actually debugged the code, i.e. set a breakpoint and stepped through the code line by line, examining the state at each step? If not, you need to do that first. You must have an expectation of what will happen at each step and you can see whether it does happen. As soon as the code behaves differently than expected, you have found a specific issue and you can examine that in more detail. You don't fix issues just by reading the code. you have to watch it in action.
 
Main is normally the starting method of your project set in your Program.Cs file so how exactly are you passing arguments to the Main method?

Ok so on line 18, you have a major issue with your logic. What happens if the user types dotnet ImageBinarizerApp -help? Should that become an argument, because it will? Because you are calling for user feedback. But you are not checking what that feedback is. So that becomes a parameter of your new args. See sample example below :

C#:
        internal static void Main(string[] args)
        {

            new Thread(() => Request_Response(new string[0]))
            {
                Name = "Executor"
            }.Start();
        }
        internal static void Request_Response(string[] args)
        {
            Console.WriteLine("Welcome to Binary Image Maker");
            Console.WriteLine("\nUse following command for help:");
            Console.WriteLine("dotnet ImageBinarizerApp -help");
            args = new String[] { Console.ReadLine() };
        }
What you need to do, is start with the debugger tutorial in my signature (Click the spoiler), read and learn to debug by following the tutorial, and start stepping through the code you have, or the code in my example and you will find why your current code is problematic from the get-go.
 
The problem is on lines 34 and 35 of the code. He programmed a misleading message for the user: "Press any key to exit the application." on line 34. Then on line 35, he programmed a call to Console.ReadLine() which will actually accept any key presses from the user until presses the Enter key. So the effect of all this is that after all the help text is printed out, the user enters a command thinking that they are entering something into the command prompt when it actually just the Console.ReadLine() that is reading in a string until the user presses Enter. After that the program exits.

See image from post #6. Notice that he enters a command after the "Press any key to exit the application." before the final output about the application exiting is displayed.
 
Have you actually debugged the code, i.e. set a breakpoint and stepped through the code line by line, examining the state at each step? If not, you need to do that first. You must have an expectation of what will happen at each step and you can see whether it does happen. As soon as the code behaves differently than expected, you have found a specific issue and you can examine that in more detail. You don't fix issues just by reading the code. you have to watch it in action.

Thank you for the assistance. I was able to set the breakpoint as you directed and was able to rearrange the construct slightly having observed the flow. I made some progress but got stuck at a fresh case. The InputhImagePath on line 41 is inactive despite initializing it at the beginning.
Inactive String variable:
   static void Main(string[] args)
        {
            String inputImagePath = "";
            String outputImagePath = "";
            int imageWidth = 0;
            int imageHeight = 0;
            int redThreshold = -1;
            int greenThreshold = -1;
            int blueThreshold = -1;


            Console.WriteLine("Welcome to Binary Image Maker");
            Console.WriteLine("\nUse following command for help:");
            Console.WriteLine("dotnet ImageBinarizerApp -help");
            args = new String[] { Console.ReadLine() };

            //Test if necessary input arguments were supplied.
            if (args.Length < 8)
            {
                if (args.Length == 1 && args[0].Equals("-help"))
                {
                    Console.WriteLine("\nHelp:");
                    Console.WriteLine("\nPass the arguments as following:");
                    Console.WriteLine("\nExample with automatic RGB:\ndotnet ImageBinarizerApp --input-image c:\\a.png --output-image c:\\out.txt -width 32 -height 32");
                    Console.WriteLine("\nExample with explicit RGB:\ndotnet ImageBinarizerApp --input-image c:\\a.png --output-image c:\\out.txt -width 32 -height 32 -red 100 -green 100 -blue 100");
                }
                else
                {
                    Console.WriteLine("\nError: All necessary arguments are not passed. Please pass the arguments first.");

                    Console.WriteLine("\nPress any key to exit the application.");
                    Console.ReadLine();
                    return;
                }

                            
                args = new String[] { Console.ReadLine() };

                if (args[0].Equals("--input-image") && File.Exists(args[1]))
                {
                    inputImagePath = args[1];
                }
                else
                {
                    Console.WriteLine("\nError: Input file doesn't exist.");
                    Console.WriteLine("\nPress any key to exit the application.");
                    Console.ReadLine();
                    return;
                }

                int separatorIndex = args[3].LastIndexOf(Path.DirectorySeparatorChar);
                if (args[2].Equals("--output-image") && separatorIndex >= 0 && Directory.Exists(args[3].Substring(0, separatorIndex)))
 
Please find attached the Snapshot of the Debug Console. Having supplied the arguments for the file path (line 37), the if-construct jumps to line 43 because the inputImagePath is inactive hence file does not exist. What can be wrong?
 

Attachments

  • Console_Debug II.png
    Console_Debug II.png
    28.9 KB · Views: 14
User your debugger. Look closely at the value of args[0]. Notice that it doesn't match the string you are expecting, so the Boolean expression on line 39 short circuits to false (and therefore does not throw an array out of bounds exception). Since there expression is false, the code goes to the else clause and you seem the error message indicating that the file does not exist.

If you are assuming that putting the call to Console.ReadLine() inside curly braces and assigning it to a string array will automatically parse the input into an array of strings, then as you can see, your assumption is wrong. You only get an array with a single string because ReadLine() on returns a single string.
 
The problem is on lines 34 and 35 of the code. He programmed a misleading message for the user: "Press any key to exit the application." on line 34. Then on line 35, he programmed a call to Console.ReadLine() which will actually accept any key presses from the user until presses the Enter key. So the effect of all this is that after all the help text is printed out, the user enters a command thinking that they are entering something into the command prompt when it actually just the Console.ReadLine() that is reading in a string until the user presses Enter. After that the program exits.

See image from post #6. Notice that he enters a command after the "Press any key to exit the application." before the final output about the application exiting is displayed.
Thank you so much. This helped me to improve the current implementation.
 
User your debugger. Look closely at the value of args[0]. Notice that it doesn't match the string you are expecting, so the Boolean expression on line 39 short circuits to false (and therefore does not throw an array out of bounds exception). Since there expression is false, the code goes to the else clause and you seem the error message indicating that the file does not exist.

If you are assuming that putting the call to Console.ReadLine() inside curly braces and assigning it to a string array will automatically parse the input into an array of strings, then as you can see, your assumption is wrong. You only get an array with a single string because ReadLine() on returns a single string.
Thank you. Please have a look at this snapshot. Do you know why ithe inputImagePath variable inactive?
 

Attachments

  • VS_Debug.png
    VS_Debug.png
    60.7 KB · Views: 15
Back
Top Bottom