Вы обвиваете все, что хотите повторить. Не забудьте предоставить способ вырваться из этого:
class Program
{
static void Main(string[] args)
{
while(true) { //run forever, we'll break out if the user wants to quit
Console.WriteLine("What is the Height of the Painting?");
string input = Console.ReadLine();
int height;
if ("int.TryParse(input, out height))
{
Console.WriteLine("Invalid number. Please make it an integer... e.g 1-9");
}
else
{
Console.WriteLine("What is the Width of the Painting?");
string input2 = Console.ReadLine();
int width;
if (!int.TryParse(input2, out width))
{
Console.WriteLine("Invalid number. Please make it an integer... e.g 1-9");
}
else
{
var orientation = (height > width ? Orientation.Landscape : Orientation.Portrait);
Console.WriteLine("Your Painting is currently in the: " + orientation + " orientation");
}
}
Console.WriteLine("Do another? Enter yes to do another");
string input = Console.ReadLine();
if(input != "yes")
{
break; //exit loop
}
} //end of while loop
}
public enum Orientation
{
Landscape,
Portrait
}
}
}
Если вас уже научили писать собственные методы, вы можете использовать их для уменьшения повторения кода:
с использованием системы;
class Program
{
static void Main(string[] args)
{
int height = AskForInt("What is the Height of the Painting?");
int width = AskForInt("What is the Width of the Painting?");
var orientation = (height > width ? Orientation.Landscape : Orientation.Portrait);
Console.WriteLine("Your Painting is currently in the: " + orientation + " orientation");
}
static int AskForInt(string question) {
Console.WriteLine(question);
while (true) //use a loop to keep asking the user if they didn't provide a valid answer
{
string input = Console.ReadLine();
int answer;
if (!int.TryParse(input, out answer))
{
Console.WriteLine("Not a valid integer. Please enter an integer: ");
}
else
{
return answer; //exit this method, returning the int
}
}
}
public enum Orientation
{
Landscape,
Portrait
}
}
Я оставлю этот последний пример зацикленным на себе как упражнение для читателя:)