- массив в классе
- Пример создания класса для работы с одномерными массивами
- Решение
- Исходный класс — ArrayInt1
- Наследование класса — ArrayIntOne
- Класс RIN — ограниченное целое число
- Arrays (C# Programming Guide)
- Example
- Array overview
- Default value behaviour
- Arrays as Objects
- See also
- Arrays (C# Programming Guide)
- Example
- Array overview
- Default value behaviour
- Arrays as Objects
- See also
массив в классе
Здравствуйте.Подскажите пожалуйста правильное решение.Создаю класс,в нем имеется поле размер массива и массив.Конструктор заполнения массива случайными числами.
В главной функции создаю класс,вызываю конструктор с параметром размера массива.
Пишет ошибку не может инициализировать массив.В чем проблема?
И еще код закоментирован,но если раскоментировать,то тоже ошибка.Не выводит на экран элементы массива.
Спасибо
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace sort_class { public class Massiv { public static int[] nNum; public static int n; public Massiv( int n) { Random r = new Random(); for(int i=0;in;i++) { nNum[i]=r.Next(0, 10); } } } public class Program { static void Main(string[] args) { Console.WriteLine("Вас приветствует программа сортировка масива"); Console.WriteLine("Введите размер масива"); string s = Console.ReadLine();//считываем размер int n = Convert.ToInt32(s);//преобразуем в Int Console.Write('\n'); Massiv myMas; myMas= new Massiv(n);//создание Класса Massiv //for (int i = 0; i < n; i++)// // Console.Write(myMas.nNum[i]); //> Console.Read(); } } }
Пример создания класса для работы с одномерными массивами
Для практики программирования Вам были предложены Задачи 2, содержащие работу со строками, одномерными и двухмерными массивами.
Полезно эти программы писать в стиле ООП, то есть задается некоторый исходный класс, назовем его ArrayIntOne, с использованием которого далее решаются поставленные задачи.
Вы можете добавлять в этот класс новые методы, либо, наследуя от него дочерний класс, создать новый.
Решение
1. Каждый класс будем сохранять как отдельный файл в общем пространстве имен, например, namespace ArrayIntOne, либо через подключение через директиву using.
2. Исходный класс назовем ArrayInt1, который будет содержать некоторые поля, конструкторы и методы. Естественно, что полями класса будут длина массива n и собственно одномерный массив a[]. Конструкторы класса необходимы для создания массивов разными способами (через ввод с клавиатуры, через генераторы случайных чисел). Методы класса — самые простые (задать или извлечь элемент массива, найти максимальный/минимальный элемент, отсортировать массив). тогда получим
Исходный класс — ArrayInt1
using System; namespace ArrayIntOne < class ArrayInt1 < protected int n; // длина массива protected int[] a; // массив целых чисел // пустой конструктор - нужен для дочернего класса public ArrayInt1() < >// конструктор целочисленного массива длиной N. Элементы массива имеют значения по умолчанию public ArrayInt1(int N) < n = N; a = new int[n]; >// конструктор с генератором случайных чисел от 0 до max public ArrayInt1(int N, int max) < Random rnd = new Random(); n = N; a = new int[n]; for (int i = 0; i < n; i++) a[i] = rnd.Next(max + 1); >// конструктор с генератором случайных чисел от min до max public ArrayInt1(int N, int min, int max) < Random rnd = new Random(); n = N; a = new int[n]; for (int i = 0; i < n; i++) a[i] = rnd.Next(min, max + 1); >// Вывод элементов массива с контролем их наличия public virtual void ArrayInt_Out(string info) < Console.WriteLine(info); if (!(a == null)) // число элементов >0 < foreach (int e in a) Console.Write(e.ToString() + "\t"); Console.WriteLine(); >else // число элементов = 0 Console.WriteLine("Нет элементов " + info); > // Поиск минимального элемента (min) и его номера (k) public virtual int N_min_Array(out int min) < min = a[0]; int k = 0; for (int i = 1; i < n; i++) if (a[i] < min) < min = a[i]; k = i; >return k; > // Поиск максимального элемента (max) и его номера (k) public virtual int N_max_Array(out int max) < max = a[0]; int k = 0; for (int i = 1; i < n; i++) if (a[i] >max) < max = a[i]; k = i; >return k; > // Изменить a[k] на заданный elem (нумерация с 0) public virtual void Set_Element(int k, int elem) < if (k >= 0 && k < n) a[k] = elem; >// Извлечь k-й элемент массива (нумерация с 0) public virtual int Get_Element(int k) < if (k >= 0 && k < n) return a[k]; else return Int32.MinValue; >// Пузырьковая сортировка по возрастанию(U)/убыванию(D)/без нее. public virtual void BubbleSort(char d) < int temp; switch (d) < case 'U': // по возрастанию for (int i = 0; i < n; i++) for (int j = n - 1; j >i; j--) if (a[j - 1] > a[j]) < temp = a[j]; a[j] = a[j - 1]; a[j - 1] = temp; >break; case 'D': // по убыванию for (int i = 0; i < n; i++) for (int j = n - 1; j >i; j--) if (a[j - 1] < a[j]) < temp = a[j]; a[j] = a[j - 1]; a[j - 1] = temp; >break; default: // без сортировки break; > > > >
3. Предположим, что нам нужно изменить или что-либо добавить в этот класс. Но им уже пользуются в других проектах, поэтому эти изменения сделаем в дочернем классе, который назовем ArrayIntOne.Три конструктора оставим без изменений, добавим конструктор для чтения из текстового файла.
Пусть файл данных имеет вид:
7
2
4
1
7
6
5
8
где первое число задает количество элементов массива, а далее в каждой строке по одному записываются эти элементы. Присвойте файлу имя, например, M1.txt, разместите его в папке с программой (exe-файлом). Тогда при запросе имени файла Вам будет достаточно указать его имя без расширения — M1.
Для примера также выполним перегрузку метода Get_Element(int k). Тогда получим класс ArrayIntOne, как дочерний класс от ArrayInt1:
Наследование класса — ArrayIntOne
using System; using System.IO; using System.Text; namespace ArrayIntOne < class ArrayIntOne : ArrayInt1 < public delegate bool IsEqual(int x); // делегат от int x ->bool public int Length // свойство "Число элементов массива" < get < return n; >> // конструкторы без изменений содержимого // могут быть перегружены public ArrayIntOne(int n) : base(n) < >public ArrayIntOne(int n, int max) : base(n, max) < >public ArrayIntOne(int n, int min, int max) : base(n, min, max) < >// конструктор для ввода данных из текстового файла public ArrayIntOne(string info) : base() < Console.WriteLine(info); Console.Write("Задайте имя текстового файла данных без расширения: "); string file_name = Console.ReadLine() + ".txt"; StreamReader sr; // поток для чтения try < // Чтение чисел из файла без ошибок // связывание с файлом, кодировка символов Юникода sr = new StreamReader(file_name, UTF8Encoding.Default); // чтение 0-й строки (длина массива) string t = sr.ReadLine(); n = Convert.ToInt32(t); a = new int[n]; int i = 0; // счетчик строк // чтение из файла чисел по строке в массив while ((t != null) && (i < n)) < t = sr.ReadLine(); // чтение строк a[i] = Convert.ToInt32(t); i++; >// закрытие файла для чтения sr.Close(); > catch (Exception ex) // на случай ошибок < Console.WriteLine("ОШИБКА: " + ex.Message); >> // конструктор для ввода массива с клавиатуры (если строковый параметр имеет значение "keyboard") - Автор Эд. // или из строки, в которой целые числа (элементы массива) разделены пробелами. // если в строке чисел меньше, чем длина массива, последние элементы массива получают значение по умолчанию // если в строке чисел больше, чем длина массива, последние числа строки не учитываются // если k-й элемент строки нельзя преобразовать в целое число, k-й элемент массива получает значение по умолчанию public ArrayIntOne(int N, string s) < n = N; a = new int[n]; if (s == "keyboard") < Console.WriteLine("Введите элементов целочисленного массива", n); for (int i = 0; i < n; i++) < Console.Write("a[]: ", i); a[i] = Convert.ToInt32(Console.ReadLine()); > > else < string[] numbers = s.Split(' ', StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < n; i++) < if (i < numbers.Length && Int32.TryParse(numbers[i], out int b)) a[i] = b; >> > // Для иллюстрации перегрузки метода добавлена только печать строки public override int Get_Element(int k) < Console.WriteLine("Перегруженный метод Get_Element()"); return base.Get_Element(k); >// Суммирование элементов массива public int Sum() < int sum = 0; foreach (int e in a) sum += e; return sum; >// метод находит все элементы массива удовлетворяющие условию, заданному делегатом (лямбда-выражением) // и возвращает новый экземпляр класса (массив, состоящий из этих элементов) - автор Эд. public ArrayIntOne Find_All(IsEqual fnc) < int b = 0; // число элементов, удовлетворяющих условию foreach (int i in a) if (fnc(i)) b += 1; ArrayIntOne a1 = new ArrayIntOne(b); // инициализация нового массива // заполнение нового массива по условию, задаваемому предикатом b = 0; for (int i = 0; i < n; i++) if (fnc(a[i])) < a1.Set_Element(b, a[i]); b++; >return a1; > > >
Замечу, что для чтения файла понадобились директивы
using System.IO; using System.Text;
4. В решениях задач по основам C# вы часто использовали различные алгоритмы контроля ввода целых чисел. Ранее был написан класс Restricted Integer Number (RIN) — «Ограниченное целое число», который удобно использовать в нашей тестовой программе:
Класс RIN — ограниченное целое число
NEW: Наш Чат, в котором вы можете обсудить любые вопросы, идеи, поделиться опытом или связаться с администраторами.
Arrays (C# Programming Guide)
You can store multiple variables of the same type in an array data structure. You declare an array by specifying the type of its elements. If you want the array to store elements of any type, you can specify object as its type. In the unified type system of C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object.
Example
The following example creates single-dimensional, multidimensional, and jagged arrays:
class TestArraysClass < static void Main() < // Declare a single-dimensional array of 5 integers. int[] array1 = new int[5]; // Declare and set array element values. int[] array2 = new int[] < 1, 3, 5, 7, 9 >; // Alternative syntax. int[] array3 = < 1, 2, 3, 4, 5, 6 >; // Declare a two dimensional array. int[,] multiDimensionalArray1 = new int[2, 3]; // Declare and set array element values. int[,] multiDimensionalArray2 = < < 1, 2, 3 >, < 4, 5, 6 >>; // Declare a jagged array. int[][] jaggedArray = new int[6][]; // Set the values of the first array in the jagged array structure. jaggedArray[0] = new int[4] < 1, 2, 3, 4 >; > >
Array overview
An array has the following properties:
- An array can be single-dimensional, multidimensional or jagged.
- The number of dimensions and the length of each dimension are established when the array instance is created. These values can’t be changed during the lifetime of the instance.
- The default values of numeric array elements are set to zero, and reference elements are set to null .
- A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null .
- Arrays are zero indexed: an array with n elements is indexed from 0 to n-1 .
- Array elements can be of any type, including an array type.
- Array types are reference types derived from the abstract base type Array. All arrays implement IList, and IEnumerable. You can use the foreach statement to iterate through an array. Single-dimensional arrays also implement IList and IEnumerable .
Default value behaviour
- For value types, the array elements are initialized with the default value, the 0-bit pattern; the elements will have the value 0 .
- All the reference types (including the non-nullable), have the values null .
- For nullable value types, HasValue is set to false and the elements would be set to null .
Arrays as Objects
In C#, arrays are actually objects, and not just addressable regions of contiguous memory as in C and C++. Array is the abstract base type of all array types. You can use the properties and other class members that Array has. An example of this is using the Length property to get the length of an array. The following code assigns the length of the numbers array, which is 5 , to a variable called lengthOfNumbers :
int[] numbers = < 1, 2, 3, 4, 5 >; int lengthOfNumbers = numbers.Length;
The Array class provides many other useful methods and properties for sorting, searching, and copying arrays. The following example uses the Rank property to display the number of dimensions of an array.
class TestArraysClass < static void Main() < // Declare and initialize an array. int[,] theArray = new int[5, 10]; System.Console.WriteLine("The array has dimensions.", theArray.Rank); > > // Output: The array has 2 dimensions.
See also
For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.
Arrays (C# Programming Guide)
You can store multiple variables of the same type in an array data structure. You declare an array by specifying the type of its elements. If you want the array to store elements of any type, you can specify object as its type. In the unified type system of C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object.
Example
The following example creates single-dimensional, multidimensional, and jagged arrays:
class TestArraysClass < static void Main() < // Declare a single-dimensional array of 5 integers. int[] array1 = new int[5]; // Declare and set array element values. int[] array2 = new int[] < 1, 3, 5, 7, 9 >; // Alternative syntax. int[] array3 = < 1, 2, 3, 4, 5, 6 >; // Declare a two dimensional array. int[,] multiDimensionalArray1 = new int[2, 3]; // Declare and set array element values. int[,] multiDimensionalArray2 = < < 1, 2, 3 >, < 4, 5, 6 >>; // Declare a jagged array. int[][] jaggedArray = new int[6][]; // Set the values of the first array in the jagged array structure. jaggedArray[0] = new int[4] < 1, 2, 3, 4 >; > >
Array overview
An array has the following properties:
- An array can be single-dimensional, multidimensional or jagged.
- The number of dimensions and the length of each dimension are established when the array instance is created. These values can’t be changed during the lifetime of the instance.
- The default values of numeric array elements are set to zero, and reference elements are set to null .
- A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null .
- Arrays are zero indexed: an array with n elements is indexed from 0 to n-1 .
- Array elements can be of any type, including an array type.
- Array types are reference types derived from the abstract base type Array. All arrays implement IList, and IEnumerable. You can use the foreach statement to iterate through an array. Single-dimensional arrays also implement IList and IEnumerable .
Default value behaviour
- For value types, the array elements are initialized with the default value, the 0-bit pattern; the elements will have the value 0 .
- All the reference types (including the non-nullable), have the values null .
- For nullable value types, HasValue is set to false and the elements would be set to null .
Arrays as Objects
In C#, arrays are actually objects, and not just addressable regions of contiguous memory as in C and C++. Array is the abstract base type of all array types. You can use the properties and other class members that Array has. An example of this is using the Length property to get the length of an array. The following code assigns the length of the numbers array, which is 5 , to a variable called lengthOfNumbers :
int[] numbers = < 1, 2, 3, 4, 5 >; int lengthOfNumbers = numbers.Length;
The Array class provides many other useful methods and properties for sorting, searching, and copying arrays. The following example uses the Rank property to display the number of dimensions of an array.
class TestArraysClass < static void Main() < // Declare and initialize an array. int[,] theArray = new int[5, 10]; System.Console.WriteLine("The array has dimensions.", theArray.Rank); > > // Output: The array has 2 dimensions.
See also
For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.