LINUX.ORG.RU

mono


0

0

В процессе изучения C# под mono, написал программу сортирующую одномерный массив.
Все работало до тех пор пока не решил сделать обработку исключений на некорректный ввод.

Исходники:

using System;

namespace lab1
{

	public class Program
	{
		static int Main()
		{
			Console.Write("Введите количество элементов массива: ");

			try
			{
				int count = Convert.ToInt32( Console.ReadLine() );
				int[] mas = new int[count];
			}
			catch (Exception e)
			{
				Console.WriteLine("Ошибка: {0}", e);
				return 1;
			}

			for (int i=0 ; i < count ; i++)
			{
				try
				{
					Console.Write("Введите значение {0}-го элемента: ", i);
					mas[i] = Convert.ToInt32( Console.ReadLine() );
				}
				catch (Exception e)
				{
					Console.WriteLine("Ошибка: {0}", e);
					return 1;
				}
			}

			int buf;
			for (int i=0 ; i < (count - 1) ; i++)
				for (int j=i ; j < count ; j++)
					if (mas[j] < mas[i])
					{
						buf = mas[j];
						mas[j] = mas[i];
						mas[i] = buf;
					}

			Console.Write("Отсортированный массив:");
			for (int i=0 ; i < count ; i++)
				Console.Write("{0} ", mas[i]);

			return 0;
		}
	}
}

Ошибки:

 ~ $ mcs lab1.mcs
lab1.mcs(15,11): warning CS0219: The variable `mas' is assigned but its value is never used
lab1.mcs(23,23): error CS0103: The name `count' does not exist in the context of `lab1.Program'
lab1.mcs(28,6): error CS0103: The name `mas' does not exist in the context of `lab1.Program'
lab1.mcs(38,24): error CS0103: The name `count' does not exist in the context of `lab1.Program'
lab1.mcs(39,24): error CS0103: The name `count' does not exist in the context of `lab1.Program'
lab1.mcs(40,10): error CS0103: The name `mas' does not exist in the context of `lab1.Program'
lab1.mcs(42,13): error CS0103: The name `mas' does not exist in the context of `lab1.Program'
lab1.mcs(43,16): error CS0103: The name `mas' does not exist in the context of `lab1.Program'
lab1.mcs(43,7): error CS0103: The name `mas' does not exist in the context of `lab1.Program'
lab1.mcs(44,7): error CS0103: The name `mas' does not exist in the context of `lab1.Program'
lab1.mcs(48,23): error CS0103: The name `count' does not exist in the context of `lab1.Program'
lab1.mcs(49,27): error CS0103: The name `mas' does not exist in the context of `lab1.Program'
Compilation failed: 11 error(s), 1 warnings
 ~ $

Проблема точно в обработке исключений, так как если ее закомментировать,
то программа компилируется нормально.
Не могли бы вы сказать в чем дело?
anonymous

>Проблема точно в обработке исключений, так как если ее закомментировать, то программа компилируется нормально

А как по поводу области видимости локальных переменных?

anonymous
()
Ответ на: комментарий от anonymous

О, спасибо, добрый человек!
Как-то сразу и не подумал.

Тогда уж попинайте мой код пожалуйста. Что написано некрасиво/криво, что лучше написать по-другому?

Лаба простенькая, но может я уже допускаю какие-то ошибки?
Вот исправленное:

using System;

namespace lab1
{

	public class Program
	{
		static int Main()
		{
			Console.Write("Введите количество элементов массива: ");
			int[] mas;
			int count;

			try
			{
				count = Convert.ToInt32( Console.ReadLine() );
				mas = new int[count];
			}
			catch (Exception e)
			{
				Console.WriteLine("Ошибка: {0}", e);
				return 1;
			}

			for (int i=0 ; i < count ; i++)
			{
				try
				{
					Console.Write("Введите значение {0}-го элемента: ", i);
					mas[i] = Convert.ToInt32( Console.ReadLine() );
				}
				catch (Exception e)
				{
					Console.WriteLine("Ошибка: {0}", e);
					return 1;
				}
			}

			int buf;
			for (int i=0 ; i < (count - 1) ; i++)
				for (int j=i ; j < count ; j++)
					if (mas[j] < mas[i])
					{
						buf = mas[j];
						mas[j] = mas[i];
						mas[i] = buf;
					}

			Console.Write("Отсортированный массив:");
			for (int i=0 ; i < count ; i++)
				Console.Write("{0} ", mas[i]);

			return 0;
		}
	}
}

anonymous
()
Ответ на: комментарий от anonymous

Весь ввод лучше завернуть в один try-блок. Так сказать, обобщим обработку ошибок, одновременно с этим улучшиться читабельность. К тому же, ослабим нагруку на код в цикле, если компилятор не делает в этом месте оптимизацию.

anonymous
()
Ответ на: комментарий от anonymous

using System;

namespace lab1
{

	public class Program
	{
		static int Main()
		{
			Console.Write("Введите количество элементов массива: ");
			int[] mas;
			int count;

			try
			{
				count = Convert.ToInt32( Console.ReadLine() );
				mas = new int[count];

				for (int i=0 ; i < count ; i++)
				{
					Console.Write("Введите значение {0}-го элемента: ", i);
					mas[i] = Convert.ToInt32( Console.ReadLine() );
				}
			}
			catch (Exception e)
			{
				Console.WriteLine("Ошибка: {0}", e);
				return 1;
			}

			int buf;
			for (int i=0 ; i < (count - 1) ; i++)
				for (int j=i ; j < count ; j++)
					if (mas[j] < mas[i])
					{
						buf = mas[j];
						mas[j] = mas[i];
						mas[i] = buf;
					}

			Console.Write("Отсортированный массив:");
			for (int i=0 ; i < count ; i++)
				Console.Write("{0} ", mas[i]);

			return 0;
		}
	}

}

Так? В общем-то логично.
Вы не против, если я напишу что-нибудь посерьезней и кину сюда, а вы все дружно попинаете код?

Хочется выявить ошибки, дурные привычки и т.п.

anonymous
()

Для начала чтоило бы зарегестрироватся. А кидать ИМХО стоит в Talks, хотя можно и сюда. Смотря как подаш=)

Motiv_studenta ★★
()
Вы не можете добавлять комментарии в эту тему. Тема перемещена в архив.