PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, June 26, 2022

[FIXED] How do I check if value exists in array

 June 26, 2022     c#, compiler-errors, try-catch     No comments   

Issue

I'm new to programming and am currently working on a calculator program.

I want the program to give an error message if none of the listed operators are being mentioned in the user input.

Here's my code:

int Number = 0;
string operation = "0";
string[] func = { "+", "-", "*", "/", ":", "x^2", "%", "cos", "bin" };

 while (true)
 {
    try
    {
        Number = Int32.Parse(Console.ReadLine());
        Console.WriteLine("--------------------------------------------");
        Console.WriteLine("Choose your operation: \n \n + \n - \n * \n : \n x^2 \n % \n cos \n bin");
        Console.WriteLine("--------------------------------------------");
        operation = Console.ReadLine();

        if (operation != func)
        {
            throw new Exception();
        }

        Console.WriteLine("--------------------------------------------");
        break;
    }
    catch (Exception)
    {
        Console.Clear();
        Console.WriteLine("Error! Please try again:");
    }
}

But, it says cannot use the != operator with a string and an array. (Compiler Error CS0019)

How can I check if a user input (operator) is in an array, so I can throw a new exception?


Solution

Try

if (!func.contains(operation)) 
{ 
    throw new Exception("");
}


Answered By - Wellerman
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing