Home > Mobile >  Setting a max and min value for user number input in console
Setting a max and min value for user number input in console

Time:04-18

Console.WriteLine("     **************************************");
Console.WriteLine("     ****** Reviewer Awarding Points ******");
Console.WriteLine("     **************************************");
Console.WriteLine();
string[]properties= { "Clarity", "Orginality", "Difficulty" };
        
int[] a = new int[3];
int[] b = new int[3];
        
for(int i = 0; i < 3; i  )
{ 
    Console.WriteLine("     ***"   properties[i] "***");
    Console.Write(" Alice:   ");
            
    a[i] = Convert.ToInt16(Console.ReadLine());
    if(a[i]>100 || a[i] < 1)
        Console.Write("   Bob:   ");
    b[i] = Convert.ToInt16(Console.ReadLine());
    Console.WriteLine();
}
Console.Read();
}

I want user to enter a value between 1 and 100(including 1 and 100).So what I am gonna do?

CodePudding user response:

your question is not clear try

   int value;
   do{
   Console.Write("Enter a value");
   value=int.parse(Console.ReadLine());
   }while(value<1 || value>100);

CodePudding user response:

Make a method that checks the result for being in range:

public int AskInt(string question, int min, int max){

  while(true){
    Console.WriteLine(question);
    string input = Console.ReadLine();

    if(int.Tryparse(input, out int value) && value >= min && value <= max) 
        return value;
  }
}

The only way to escape the loop is to enter a valid number that is in range, otherwise the question just repeats

Then you can use it multiple times in your code:

int age = AskInt("Enter an age between 10 and 100: ", 10, 100);
int weight = AskInt("Enter a weight between 100 and 350: " 100, 350);

CodePudding user response:

Try this:

if(a[i]>=100 || a[i] <= 1)

You can learn about C# operators at this site: https://www.w3schools.com/cs/cs_operators.php

  • Related