Home > Software design >  Can I compare a value from a method and another from a variable?
Can I compare a value from a method and another from a variable?

Time:07-13

I need to identify if password is equal to Pin(), I don't know if the problem is comparing a method inside a method

public static string Pin(int size = 4) {
    StringBuilder sb = new StringBuilder(size);
    
    while (sb.Length < size) {
        var key = Console.ReadKey(true);
        
        if (key.KeyChar >= '0' && key.KeyChar <= '9') {
            sb.Append(key.KeyChar);
            Console.WriteLine('*');
        }
    }

    return sb.ToString(); 
}

static void Card() {
    Console.WriteLine("Enter the 4 Digits Password");
    int password = int.Parse(Console.ReadLine());

    if (password == Pin()) {
        // Is going to do something
    }
}

CodePudding user response:

You cannot compare string (Pin() result) and int (password) directly. Either convert password to string string password = Console.ReadLine();, either add int.Parse to the Pin() function result.

if (password == int.Parse(Pin()))
{
   // Is going to do something
}

CodePudding user response:

I suggest implementation like this. For reading Pin we can put

// Since Pin is integer, let's return int, not string
public static int Pin(int size = 4) {
  if (size <= 0 || size >= 9)
    throw new ArgumentOutOfRangeException(nameof(size));
  
  StringBuilder sb = new StringBuilder(size);

  while (sb.Length != size) {
    var position = Console.GetCursorPosition();

    char letter = Console.ReadKey().KeyChar;

    Console.SetCursorPosition(position.Left, position.Top);

    if (letter >= '0' && letter <= '9') {
      Console.Write('*');

      sb.Append(letter);
    }
    else {
      Console.Write(' ');
      Console.SetCursorPosition(position.Left, position.Top);
    }
  }

  return int.Parse(sb.ToString());
}

Let's extract ReadInteger as well:

public static int ReadInteger(string title) {
  while (true) {
    if (!string.IsNullOrWhiteSpace(title))
      Console.WriteLine(title);

    if (int.TryParse(Console.ReadLine(), out int result))
      return result;

    Console.WriteLine("Syntax error, incorrect integer value. Please, try again.");
  }
}

Then you can use the routine as simple as

static void Card() {
  int password = ReadInteger("Enter the 4 Digits Password");

  if (password == Pin()){
     // Is going to do something
  }
}
  • Related