Home > Software engineering >  C# String comparison not evaluating to true even though string value matches as expected
C# String comparison not evaluating to true even though string value matches as expected

Time:04-20

I have a question about the following code I have written for a C# Programming course assignment. Everything seems to be functioning correctly except for the if statement on line 31 which checks if the input string fed into a conversion method matches the requirements given in the if statement.

The logic chain of the if statements is as follows:

  1. If the user entered less than 2 chairs, tell them they must buy at least 2 chairs.
  2. If the user entered 2 or more chairs, proceed to next iteration of loop and check the next else if statement.
  3. If user entered 2 or more chairs and the wood variable is not string "pine", "maple", or "oak, enter this else if block.
  4. Give user a chance to enter a value. Acceptable values are "p", "m", and "o".
  5. Convert single-character string to string with woodType method, which returns "pine", "maple", or "oak" based on what they input.
  6. If user did not enter an acceptable value, return to loop after telling the user to try again.
  7. This is where the hang-up is. If they input a valid value, the logic chain should proceed to the final else if block, but it does not. See commented line 30. Uncomment this line and it returns the name of the wood correctly from the method.
  8. Final else if block: if everything was good, repeat the order to the user, calculate the cost, and return the final cost.

For some reason, the logic is failing at step 7 and remaining in the loop, continuously demanding the user input a valid value even though it has received a valid value. Perhaps there is something wrong with how I am comparing the strings? Obviously, there is something wrong here, but I'm unable to put my finger on it.

Here is the source code:

using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;

public class Tables {
    static int chairs = 0;
    static string wood = string.Empty;
    static bool run = true;
    const double CHAIR_PRICE = 50.00;
    static Dictionary<string, double> PRICES = new Dictionary<string, double> {
        { "pine", 250.00 },
        { "maple", 300.00 },
        { "oak", 350.00 }
    };
    
    public static void Main() {
        while (run == true) {
            if (chairs < 2) {
                Console.WriteLine("Enter the number of chairs: ");
                chairs = chairCount(Console.ReadLine());
                    //Console.WriteLine("{0}", chairs);//Debug
                if (chairs < 2) {
                    Console.WriteLine("You must order at least two chairs.");
                }
            } else if (chairs >= 2 && (wood != "pine" || wood != "maple" || wood != "oak")) {
                Console.WriteLine("Enter the type of wood - [p]ine, [m]aple, or [o]ak: ");
                wood = woodType(Console.ReadLine());
                //Console.WriteLine("{0}", wood);//Debug
                if (wood != "pine" || wood != "maple" || wood != "oak") {
                    Console.WriteLine("You must enter p, m, or o for wood type.");
                }
            } else if (chairs >= 2 && (wood == "pine" || wood == "maple" || wood == "oak")) {
                Console.WriteLine("You have ordered a {0} table with {1} chairs.", wood, chairs);
                Console.WriteLine("Total price is {0}", costCalc(wood, chairs).ToString("C", new CultureInfo("en-us")));
            run = false;
            }
        }
    }

    static int chairCount(string input) {
        return Convert.ToInt32(input);
    }

    static string woodType(string input) {
        if (input == "p") { return "pine"; } 
        else if (input == "m") { return "maple"; }
        else if (input == "o") { return "oak"; } 
        else { return "invalid"; }
    }

    static double costCalc(string wood, int chairs) {
        return PRICES[wood]   (chairs * CHAIR_PRICE);
    }
}

CodePudding user response:

This condition

 (chairs >= 2 && (wood != "pine" || wood != "maple" || wood != "oak"))

is always going to be true if chairs >= 2

you mean

(chairs >= 2 && (wood != "pine" && wood != "maple" && wood != "oak"))

But this code can be made much much simpler

 while(true){
    Console.WriteLine("Enter the number of chairs: ");
    chairs = chairCount(Console.ReadLine());
    if (chairs < 2) {
          Console.WriteLine("You must order at least two chairs.");
    } else {
        break
    }
 }

 while(true){
     Console.WriteLine("Enter the type of wood - [p]ine, [m]aple, or [o]ak: ");
     wood = woodType(Console.ReadLine());
   if (wood != "pine" && wood != "maple" && wood != "oak") {
         Console.WriteLine("You must enter p, m, or o for wood type.");
   } else{
      break;
   }
}

no big outer loop needed

CodePudding user response:

Rather than using '==' to compare strings, always use the .equals method:

if (input.equals("p")) // result code you write here.

The reason for this is because == compares the memory location of the strings rather than the actual values, while the equals method actually compares the values.

  •  Tags:  
  • c#
  • Related