How to input a choice that require int and string with console.Read.Line?

FranK Duc 121 Reputation points
2021-12-03T13:56:45.913+00:00

User must input numbers and it will return the largest number and its position in the line. To stop entering numbers i want user to be able to input "N". But N is a string and numbers are int.

using System;


public class HelloWorld {
  public static void Main() {

      int n;
      int pg = 0;
      int x = 1;
      int index = 0;
      string rep;

   Console.WriteLine("Enter numbers, press n to stop:");



while (true)
{

 n = Convert.ToInt32(Console.ReadLine());
rep = (Console.ReadLine().ToUpper());

if (n > pg)
 {
pg = n;
index = x;

}

else if (rep == "N")
{
 break;   // Will work only if largest number is first. 

}
x++;


}


 Console.WriteLine("Largest number is:  {0}  ",  pg);
    Console.WriteLine("Position in line : {0}" , index);
  }
}

How can i allow users to input "N" to stop entering numbers?

Thank you

Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. P a u l 10,761 Reputation points
    2021-12-03T14:05:15.047+00:00

    You could check if the input was "N" before you attempt to parse it as an int:

    int pg = 0;
    int x = 1;
    int index = 0;
    
    Console.WriteLine("Enter numbers, press n to stop:");
    
    while (true) {
        string input = Console.ReadLine();
    
        if (input.Equals("N", StringComparison.OrdinalIgnoreCase)) {
            break;
        }
    
        if (!int.TryParse(input, out var n)) {
            continue; // Wasn't parseable as int, so loop back round.
        }
    
        if (n > pg) {
            pg = n;
            index = x;
        }
    
        x++;
    }
    
    
    Console.WriteLine("Largest number is:  {0}  ", pg);
    Console.WriteLine("Position in line : {0}", index);
    

    This will skip over input that wasn't parseable as int too.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.