morqw666
29 сен 2021 20:14
class Program{ public static void ShowName(string[] yourString) { for (int i = 0; i< yourString.Length; i++) { if (i != (yourString.Length - 1)) { Console.Write(yourString[i] + ", "); } else { Console.WriteLine(yourString[i]); } } } public static void ShowName(string[] yourString, char x){ for (int i = 0; i< yourString.Length; i++) { if (i != (yourString.Length - 1)) { Console.Write(yourString[i] + x + " "); } else { Console.WriteLine(yourString[i]); } } } static void Main(string[] args) { string[] names = new string[] { "Vova", "Vlad", "Oleg", "Olya", "Andrey", "Alex" }; ShowName(names); Console.WriteLine("Choose new symbol:"); int i = 0; char newChar = ' '; while (i < 1) { try { newChar = Convert.ToChar(Console.ReadLine()); i++; } catch(FormatException) { Console.WriteLine("Need to choose one char only"); } } ShowName(names, newChar); Console.ReadKey(); } }
|
Altum
16 сен 2021 21:55
class Program { class SomeClass { public static void ShowNames(string[] strings) { string s = ""; foreach(String name in strings) { s += name + ','; } Console.WriteLine(s.Remove(s.Length - 1)); }
public static void ShowNames(string[] strings, char divider) { string s = ""; foreach (String name in strings) { s += name + divider; } Console.WriteLine(s.Remove(s.Length - 1)); //обрезаю последний элемент строки, чтобы не выводился символ-разделитель после последнего слова в массиве } } static void Main(string[] args) { String[] devices = { "Смартфон", "Ноутбук", "Геймпад", "Умная колонка", "Смарт-часы" }; String[] animals = { "Барсик", "Рекс", "Муму" };
SomeClass.ShowNames(devices); SomeClass.ShowNames(devices, '|'); SomeClass.ShowNames(animals, '+');
Console.ReadKey(); } }
|
Галина Шмелева
15 авг 2021 20:49
using System; namespace Methods_Classes { class Names { List<string> ListNames = new List<string>() {"Андрей","Борис","Владимир"}; public void Print() { string result = ""; foreach(string e in ListNames ) { result = result + e + ","; }
Console.WriteLine(result); } public void Print(string s) { string result = ""; foreach (string e in ListNames) { result = result + e + s; }
Console.WriteLine(result); }
}
//Имеется список имен. //Создайте метод, который будет выводить на экран эти имена через запятую. //Перегрузите этот метод так, чтобы можно было изменять разделитель – вместо запятых между именами любой символ, переданный параметром.
static void Main(string[] args) { Names N = new Names(); N.Print(); N.Print(":");
}
} }
|
Navi
03 сен 2019 10:51
class ReloadMethod { public void ShowList(string name, int num) { Console.Write(name + num + " "); } public void ShowList(string name, string symbol) { Console.Write(name + symbol); } } class Program {
static void Main(string[] args) { string[] ListOfNames = { "Sergeii", "Andrii", "Ivan", "Petro", "Roman", "Vasya" }; ReloadMethod rel = new ReloadMethod();
for (int i = 0; i < ListOfNames.Length; i++) { rel.ShowList(ListOfNames[i], 1); }
for (int i = 0; i < ListOfNames.Length; i++) { rel.ShowList(ListOfNames[i], "; "); } } }
|
Yahor
01 июл 2019 16:17
namespace overload { class Program { public static void Separator(List<string>names) { for (int i = 0; i < names.Count; i++) { Console.WriteLine(names[i]+ ','); } }
public static void Separator(List<string> names, char b) { for (int j = 0; j < names.Count; j++) { Console.WriteLine(names[j] + b); }
}
static void Main(string[] args) { List<string> names = new List<string>() { "fefd", "feaf", "efaf", "aewf", "dwad" };
Separator(names); Console.WriteLine("Insert new separator here:"); char new_separator = Convert.ToChar(Console.ReadLine()); Separator(names, new_separator);
} } }
|
dwebm@mail.ru
23 сен 2018 16:53
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO;
namespace ConsoleApp13 { class Program { string[] names = { "Коля", "Валера", "Витя" };
public void Symbol() { for (int i = 0; i < names.Length; i++) { if(i < names.Length-1) Console.Write(names[i] + ", "); else Console.Write(names[i] + "\n");
} }
public void Symbol(char c) { for (int i = 0; i < names.Length; i++) { if (i < names.Length - 1) Console.Write(names[i] + c.ToString() + " "); else Console.Write(names[i] + "\n"); } }
static void Main() { Program p = new Program(); p.Symbol(); p.Symbol('#'); } } }
|
dwebm@mail.ru
23 сен 2018 16:53
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO;
namespace ConsoleApp13 { class Program { string[] names = { "Коля", "Валера", "Витя" };
public void Symbol() { for (int i = 0; i < names.Length; i++) { if(i < names.Length-1) Console.Write(names[i] + ", "); else Console.Write(names[i] + "\n");
} }
public void Symbol(char c) { for (int i = 0; i < names.Length; i++) { if (i < names.Length - 1) Console.Write(names[i] + c.ToString() + " "); else Console.Write(names[i] + "\n"); } }
static void Main() { Program p = new Program(); p.Symbol(); p.Symbol('#'); } } }
|
tantarin
26 авг 2018 13:00
using System.IO; using System; using System.Collections.Generic;
class Program { public static void method(List<string>Names){ string names = Names[0] + ", "; for (int i = 1; i<Names.Count; i++){names += Names[i]+", ";} Console.WriteLine(names); }
public static void method(List<string>Names, string Seprtr){ string names = Names[0] + Seprtr; for (int i = 1; i<Names.Count; i++){names += Names[i] + Seprtr;} Console.WriteLine(names); }
static void Main(string[] args) { List<string> Names = new List<string>(){"Ira", "Oleg", "Sergey", "Tanya"}; method(Names); method(Names, ";"); }
|
Lemon Party
18 июл 2018 14:28
class method { public void Method1(string[] array) { for (int i = 0; i < array.Length; i++) if(i<array.Length - 1) { Console.Write(array[i] + ','); } else { Console.Write(array[i]); } }
public void Method2(string[] array, string tochka) { for(int i = 0; i < array.Length; i++) { if (i < array.Length - 1) { Console.Write(array[i] + tochka); } else { Console.Write(array[i]); } } } } class Program { static void Main(string[] args) { string[] array = { "Alex", " Stephen", " Ev", " John " }; method method = new method(); method.Method1(array); Console.WriteLine(); method.Method2(array,"."); Console.ReadKey(); } } }
|
Lemon Party
18 июл 2018 10:50
Это же как у конструкторов.
|
sadaction
21 дек 2017 20:36
2 Alexey 09 дек 2017 09:07
последний разделитель можно удалить для красоты
for (byte i = 1; i<Names.Count; i++){names += Names[i]+", ";} names = names.Remove (names.Length - 2, 2); // ", " - два знака Console.WriteLine(names); }
public static void AddAndDisplay(List<string>Names, string Seprtr){ string names = Names[0] + Seprtr; for (byte i = 1; i<Names.Count; i++){names += Names[i] + Seprtr;} names = names.Remove (names.Length - Seprtr.Length, Seprtr.Length); ...
|
Alexey
09 дек 2017 09:07
если использовать только то, что было в пройденных уроках, то получается вот так:
using System.IO; using System; using System.Collections.Generic;
class Program { public static void AddAndDisplay(List<string>Names){ string names = Names[0] + ", "; for (byte i = 1; i<Names.Count; i++){names += Names[i]+", ";} Console.WriteLine(names); }
public static void AddAndDisplay(List<string>Names, string Seprtr){ string names = Names[0] + Seprtr; for (byte i = 1; i<Names.Count; i++){names += Names[i] + Seprtr;} Console.WriteLine(names); }
static void Main(string[] args) { List<string> Names = new List<string>(){"Ivan", "Oleg", "Sergey", "Maksim"}; AddAndDisplay(Names); AddAndDisplay(Names, "///"); } }
|
Кирюха
23 ноя 2017 10:11
using System; namespace peregryzka_Metodov { class programm { static void Metod(string a) { Console.WriteLine("Bill "+ a + "Bob "+ a +"Katy "+ a +"Jessi "); } static void Metod(int a) { Convert.ToString(a); Console.WriteLine("Bill "+ a + "Bob "+ a +"Katy "+ a +"Jessi "); } static void Main (string[] args) { Metod(","); Console.WriteLine("Каким символом заменить запятую?"); Metod(Console.ReadLine()); } } }
|
Александр
28 авг 2017 15:07
using System; using System.Collections.Generic;
namespace Lesson23 { class Name { public void name(string[] names) { for (int i = 0; i < names.Length; i++) { if (i < names.Length - 1) Console.Write(names[i] + ", "); else Console.Write(names[i]+ "\n"); } } public void name(string[] nam, string symbol) { for (int i = 0; i < nam.Length; i++) { if (i < nam.Length - 1) Console.Write(nam[i] + symbol + " "); else Console.Write(nam[i] + "\n"); } } }
class MainClass { public static void Main(string[] args) { string[] array = { "John", "Oleg", "Alex" }; Name N = new Name(); N.name(array); Console.WriteLine("Введдите символ, которым хотите заменить запятую"); string a = Convert.ToString(Console.ReadLine()); N.name(array, a); Console.ReadKey(); } } }
|
Andrey
08 янв 2017 20:34
static void Main(string[] args) { List<string> Imy = new List<string>(); Imy.Add("Андрей"); Imy.Add("Иван"); Imy.Add("Вася"); Imy.Add("Петя"); Imy.Add("Настя"); Imy.Add("Лена"); Imy_to_string_proc(Imy); Imy_to_string_proc(Imy, ","); Imy_to_string_proc(Imy, 9); Console.ReadKey(); } public static void Imy_to_string_proc(List<string> imy,int separator) { string stroka = ""; foreach (string imy_item in imy) {stroka =stroka+ imy_item + separator;} Console.WriteLine(stroka); } public static void Imy_to_string_proc(List<string> imy, string separator) { string stroka = ""; foreach (string imy_item in imy) {stroka = stroka + imy_item + separator;} Console.WriteLine(stroka); } public static void Imy_to_string_proc(List<string> imy) { string stroka = ""; foreach (string imy_item in imy) {stroka = stroka + imy_item + "[]";} Console.WriteLine(stroka); }
|
Юрец
14 ноя 2016 22:28
namespace reloadMeth { class myMethReload { public static void nameMas (string [] m)//создаем основной метод вывода имен из массива { for (int i = 0; i <= m.Length-1; i++)//выводим значиния из массива с проверкой, последний элемент выводим без запятой { if (i < m.Length - 1) Console.Write(m[i] + ", "); else Console.Write(m[i]+"\n"); } }
public static void nameMas(string[] m, string sim)//создаем перегруженный метод { for (int i = 0; i <= m.Length - 1; i++)//выводим значиния из массива с проверкой, последний элемент выводим без запятой { if (i < m.Length - 1) Console.Write(m[i] + sim);//разделитель добавляем символ пользователя else Console.Write(m[i]); } } }
class Program { static void Main(string[] args) { string[] names = { "Юра", "Кристина", "Ира" };
myMethReload.nameMas(names);//вызов основного метода
Console.WriteLine("Каких символом разделить имена ?"); string r = Console.ReadLine();
myMethReload.nameMas(names, r);//вызов перегруженного метода
Console.ReadKey(); } } }
|
Александр Михалев
21 май 2016 13:54
class Program { string[] mas = { " Alex, Brian, Robby, Dilan " }; // список имен
public void Vivod() // базовый метод { foreach (string f in mas) // цикл для вывода массива имен { Console.WriteLine(f); Console.WriteLine("Нажмите Enter что бы продолжить.."); Console.ReadLine(); Console.Clear(); } } public void Vivod(string izmenal) // Перегруженый метод. Сюда передается "s" из main иначе была бы ошибка. { try { Console.WriteLine("Введите символ на который будет произведена замена "); var zam = Console.ReadLine(); // для любых типов. Что бы небыло привязки к int, string и т.п. /*do // хотел сделать условие завершения свича и его повторов но не вышло :( {*/ Console.WriteLine("1.вставка вместо запятых 2. вставка между именами"); int izm = Convert.ToInt32(Console.ReadLine()); switch (izm) { case 1: foreach (string f in mas) { Console.WriteLine(f.Replace(",", zam)); // замена символа "," на символ введенный пользователем } break; case 2: foreach (string f in mas) { Console.WriteLine(f.Replace(" ", zam)); // замена символа пробела на символ введенный пользователем } break; default: Console.WriteLine("Вы ввели неверный номер."); Console.ReadLine(); break; } // } //while (izm < 1 || izm > 2); } catch (FormatException) // блок оператора try-catch который указывает на ошибку пользователю { Console.WriteLine("Вы ввели не число"); } Console.WriteLine("Нажмите Enter что бы продолжить.."); Console.ReadLine(); Console.Clear(); } static void Main(string[] args) { int menu = 10; // переменная для switch. Присвоено значения для возможности завершить программу пользователю Program program = new Program(); // ссылка на класс для вывода методов do // цикл do-while { Console.WriteLine("Выберите вариант: 1. Обычный вывод списка 2.Замена символа 3.Закрыть программу"); try // блок оператора try-catch для отлова ошибок { menu = Convert.ToInt32(Console.ReadLine()); switch (menu) { case 1: program.Vivod(); // первый метод. Просто вывод массива break; case 2: program.Vivod("s"); // второй метод. Перегруженый первый. "s" - нужно было для отдачи параметра в перегруж. метод. break; case 3: menu = 0; // условие ложно: "while (menu != 0);" и программа завершается break; default: // дефолтный кейс если было введено число больше 3 и меньше 1 Console.WriteLine("Вы ввели неверный номер. \nБудет выбран вариант по умолчанию (Обычный вывод списка)\n Нажите клавишу Enter.."); Console.ReadLine(); program.Vivod(); break; } } catch (FormatException) // блок оператора try-catch который указывает на ошибку пользователю { Console.WriteLine("Вы ввели не число"); } } while (menu != 0); // Меню будет зациклено пока не выполнится это условие Console.WriteLine("Нажите Enter что бы продолжить.."); Console.ReadLine(); Console.Clear(); } }
|
ahtem
17 май 2016 18:21
class Program { static void Main() { string f; lool lol = new lool(); string[] namesp = { "Masha", "Dasha", "Liza", "Nastya" }; lol.lol(namesp); Console.WriteLine(); f = Convert.ToString(Console.ReadLine()); lol.lol(namesp,f); Console.Read(); }
class lool { public void lol(string[] namesp) { string s = ","; for (int b = 0; b < namesp.Length; b++) Console.Write(namesp[b] + s); } public void lol(string[] namesp,string k) { for (int b = 0; b < namesp.Length; b++) Console.Write(namesp[b] + k); } } } }
|
bas-tion.ru
07 май 2016 00:07
class Program { // Статический метод. Нет необходимости создавать объект. // В качестве аргумента, метод получает массив строковых данных. // Выводит полученные данные в одну строку через запятую. public static void AddComma(string[] aList) { string aSymb = ","; string myString = ""; for (int i=0; i< aList.Length; i++) { if (i == (aList.Length - 1)) // Иф для удаления последнего разделителя в строке aSymb = "";
myString = myString + aList[i] + aSymb; } Console.WriteLine(myString); }
// Перегрузка предыдущего статического метода. // Добавлен аргумент - разделитель слов в строке public static void AddComma(string mySymb ,string[] aList) { string myString = ""; for (int i = 0; i < aList.Length; i++) { if (i == (aList.Length - 1)) // Иф для удаления последнего разделителя в строке mySymb = "";
myString = myString + aList[i] + mySymb; } Console.WriteLine(myString); } static void Main(string[] args) { string[] nameList = { "Россия", "Канада", "Чехия" };
// Пример статического полиморфизма. На стадии компиляции, // автоматически выбирается необходимый метод. AddComma(nameList); AddComma(":", nameList);
Console.ReadKey();
} }
|
Михаил
08 апр 2016 17:12
Вывод:
John,Pedro,Mike,Sam John | Pedro | Mike | Sam John.Pedro.Mike.Sam
Код программы:
class NamesOutput { protected string[] names; protected string delimeter;
public NamesOutput (string[] names) { this.names = names; }
public void Show () { this.delimeter = ","; this._show (); }
public void Show (string delimeter) { this.delimeter = delimeter; this._show (); }
private void _show () { Console.WriteLine (String.Join (this.delimeter, this.names)); } }
class Example { static void Main(string[] args) { string[] names = { "John", "Pedro", "Mike", "Sam" };
NamesOutput no = new NamesOutput (names);
no.Show (); no.Show (" | "); no.Show ("."); } }
|
NewOne
31 мар 2016 17:21
class Program { public static void MonitorNames(string[] names) { for (int i=0; i<names.Length;i++) { Console.WriteLine(names[i] + ","); } } public static void MonitorNames(string[] names, string sign) { for (int i = 0; i < names.Length; i++) { Console.WriteLine(names[i] + sign); } } static void Main(string[] args) { string[] names = { "Коля", "Саша", "Аня", "Ира" }; MonitorNames(names); Console.WriteLine("Введите любой друг знак"); string sign = Console.ReadLine(); MonitorNames(names, sign); Console.ReadKey(); } }
|
Вадик
18 мар 2016 15:59
Буду очень рад критике.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;
namespace reloading_methods { class Names { public string Name { get; set; } public Names(string name) { Name = name; }
public void Rec() { Name = Name + ", "; }
public void Rec(string sign) { Name = Name + sign + " "; } }
class Program { static void Main(string[] args) { List<Names> names = new List<Names>(); for (;;) { Console.WriteLine("Для пролжения нажмите Y, для закрытия программы введите N"); string Q1 = Console.ReadLine(); if (Q1 == "y" || Q1 == "Y") { for (;;) { Console.WriteLine("Для того чтобы начать вводить имена - введите W"); Console.WriteLine("Для того чтобы получить список имён - введите L"); Console.WriteLine("Чтобы выйти - введите Q"); string Q2 = Console.ReadLine(); if (Q2 == "W" || Q2 == "w") { for (;;) { Console.WriteLine("Введите имя или Q для выхода (имя не может быть Q и q"); string Q3 = Console.ReadLine(); if (Q3 == "Q" || Q3 == "q") { break; } else { string name; name = Q3; names.Add(new Names(name)); } } } else if (Q2 == "L" || Q2 == "l") { string str = ""; Console.WriteLine("Для того что бы ввести свой разделитель введите его, если хотите оставить по умолчанию - просто нажмите Enter"); string Q3 = Console.ReadLine(); if (Q3 == "" || Q3 == "") { foreach (Names name in names) { name.Rec(); } foreach (Names name in names) { str += name.Name; } } else { foreach (Names name in names) { name.Rec(Q3); } foreach (Names name in names) { str += name.Name; } } Console.WriteLine(str); Console.WriteLine("Длы продолжения нажмите любую клавишу"); Console.ReadKey(); continue; } else { break; } } } else if (Q1 == "n" || Q1 == "N") { break; } else { Console.WriteLine("Неизвестная команда"); } } } } }
|
игорь
29 янв 2016 10:59
class Gruppa { public Gruppa(string name) { _name = name; } string _name; public void Obrabotchik_imen(List<Gruppa>arrive) { foreach (Gruppa spell in arrive) { Console.Write(spell._name + ", "); }
}
public void Obrabotchik_imen(List<Gruppa> arrive,string s) { foreach (Gruppa spell in arrive) { Console.Write(spell._name + s+" "); }
}
} class student : Gruppa { public student(string name) : base(name) { } }
static void Main(string[] args) { List<Gruppa>lokomotivi=new List<Gruppa>(); lokomotivi.Add(new student("Федоров")); lokomotivi.Add(new student("Никитин")); lokomotivi.Add(new student("Солнцев")); lokomotivi.Add(new student("Игнатьев")); Gruppa b=new Gruppa("1b"); b.Obrabotchik_imen(lokomotivi); Console.WriteLine("\n Если вас не устраивает что список перечислен через , введите свой разделительный знак"); string s = Console.ReadLine(); Console.WriteLine("текущий список выглядит таким образом"); b.Obrabotchik_imen(lokomotivi, s);
} } }
|
neronovs
07 янв 2016 21:17
class ArrayNames { internal void GetNames(string stop, string[] names) { Console.WriteLine(String.Join(stop, names));//Connect the array and use a given separator } }
class Program { static void Main(string[] args) { string stop = ", "; string[] names = { "Anna", "Bella", "Cenderella", "Dimana", "Ellizabeth", "Fedora", "Glorya" }; ArrayNames list = new ArrayNames(); for (;;) { Console.Clear();//Erase information from the screen list.GetNames(stop, names); Console.WriteLine("\nEnter a new separator insted of '" + stop + "'. Or press 'Enter' to exit"); stop = null; stop = Console.ReadLine();//Change the separator //if (stop == "exit") break; if (stop == "") break; stop += " "; } } }
|
Kolsky
31 дек 2015 20:20
using System; using System.Collections.Generic;
namespace l { class Program { public static void GetNamesOnScreen(List<string> str) { string OutLine=""; foreach (string s in str) { OutLine += s + ", "; } Console.WriteLine(OutLine.Remove(OutLine.Length - 2)); } public static void GetNamesOnScreen(List<string> str, char symb) { string OutLine = ""; foreach (string s in str) { OutLine += s + symb; } Console.WriteLine(OutLine.Remove(OutLine.Length - 1)); } public static void GetNamesOnScreen(string str) { Console.WriteLine(str); } static void Main(string[] args) { List<string> T =new List<string>() {"Ято","Ики Хиёри","Юкинэ"}; GetNamesOnScreen("Кирито"); GetNamesOnScreen(T); GetNamesOnScreen(new List<string>() { "Первый", "Второй", "Третий", "Четвёртый" },'|'); Console.ReadKey(true); } } }
|
rotkiv
13 окт 2015 14:34
честно говоря, по началу тему понял, а как взялся за домашку, так все позабыл, про циклы и все остальное, но благодаря предыдущему решению ROOT 25 авг 2015 19:39 я таки сделал урок и теперь я знаю кунг-фу )) вот только одна дилемма, программа не имеет выхода
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;
namespace Overload { class Program { public static void Names(List<string> imena) { for(int i = 0; i < imena.Count; i++) { Console.WriteLine(imena[i]); Console.ReadKey(); } } public static void Names(List<string> imena, string znak) { for(int i = 0; i < imena.Count; i++) { Console.WriteLine(imena[i] + znak); Console.ReadKey(); } }
static void Main(string[] args) { string znak; List<string> imena = new List<string>(); link: Console.Clear(); Console.WriteLine("1 - to insert name\n 2 - vizualize list\n 3 - change sign"); int a = Convert.ToInt32(Console.ReadLine()); if (a == 1) { AddName: Console.Clear(); string insert = Console.ReadLine(); imena.Add(insert); goto link; } else if (a == 2) { VizualizeName: Console.Clear(); Names(imena); Console.ReadKey(); goto link; } else { Console.Clear(); Console.WriteLine("insert the sign"); znak = Console.ReadLine(); Console.WriteLine("List of newsigned names"); Names(imena, znak); Console.ReadKey(); goto link; } } } }
|
ROOT
25 авг 2015 19:39
//Домашнее задание//
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;
namespace Overload { class Program { public static void Names(List<string> names) { for (int i=0; i < names.Count; i ++) { if (i == names.Count - 1) { Console.Write(names[i] + "."); } else Console.Write(names[i] + ", "); } } public static void Names(List<string> names, string delimiter) { for (int i = 0; i < names.Count; i++) { if (i == names.Count - 1) { Console.Write(names[i] + "."); } else Console.Write(names[i] + delimiter + " "); } } static void Main(string[] args) { link: try { Console.ForegroundColor = ConsoleColor.White; int select2; List<string> names = new List<string>(); names.Add("Name1"); names.Add("Name2"); Console.WriteLine("1 - ввод имён\n2 - меню разделителей"); int select = Convert.ToInt32(Console.ReadLine()); if (select == 1) { do { Console.Clear(); Console.Write("Введите имя, которое хотите добавить: "); string name = Console.ReadLine(); names.Add(name); Console.Clear(); Console.WriteLine("1 меню разделителей\n2 - ввод имён"); select2 = Convert.ToInt32(Console.ReadLine()); Console.Clear(); } while (select2 != 1); } if (select == 1) { goto delimeter; } delimeter: Console.Clear(); Console.WriteLine("Выберите разделитель:\n1 - запятая\n2 - выбрать разделитель"); int select3 = Convert.ToInt32(Console.ReadLine()); if (select3 == 1) { Console.Clear(); Console.WriteLine("Список имён со стандартным разделителем: "); Names(names); Console.ReadKey(); } else if (select3 == 2) { Console.Clear(); Console.Write("Введите разделитель: "); string del = Console.ReadLine(); Console.Clear(); Console.WriteLine("Список имён с введённым разделителем: "); Names(names, del); Console.ReadKey(); } } catch(Exception) { Console.Clear(); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("ОШИБКА!!! ПОПРОБУЙТЕ СНОВА!!!\nERROR!!! TRY IT AGAIN!!!"); Console.ReadKey(); Console.Clear(); goto link; } } } }
|
Максим
18 авг 2015 18:50
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;
namespace Method_Overloading { class Name { public void Method(params string[] names) { for(int i = 0; i < names.Length; i++) { names[i] = names[i] + ",";
Console.Write(names[i]);
} } public void Method(char simvol, params string[] names) { for (int i = 0; i < names.Length; i++) { names[i] = names[i] + simvol;
Console.Write(names[i]); }
} }
class Program { static void Main(string[] args) { Name max = new Name();
max.Method("max", "dima", "andrey");
max.Method('<', "max", "alexander", "nikita" );
Console.ReadKey(); } } }
У меня все правильно?
|
Александр
16 авг 2015 11:17
Спасибо за урок!
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;
namespace ConsoleApplication26_Sharp_List { class Program { static void Main(string[] args) { string [] names = new string[] { "Евгений", "Дмитрий", "Владислав", "Николай" }; func(names); Console.ReadKey(); Console.Clear(); func(names, '*'); Console.ReadKey(); } static public void func(string [] temp) { for(int i = 0; i<temp.Length; i++) if (i == temp.Length - 1) Console.Write(temp[i] + "."); else Console.Write(temp[i] + "," + " "); } static public void func(string [] temp, char a) { for (int i = 0; i < temp.Length; i++) if (i == temp.Length - 1) Console.Write(temp[i] + "."); else Console.Write(temp[i] + a + " "); } } }
|
Очень Юра
06 авг 2015 21:49
Спасибо за урок.
class Program { public static void DisplayList(List<string> names, char a) { int interator = 0; foreach (string name in names) { interator ++; Console.Write(name + (interator == names.Count ? "\n" : a.ToString() + " ")); } } public static void DisplayList(List<string> names, int a) { foreach (string name in names) { Console.WriteLine(a++.ToString() + ". " + name); } }
static void Main(string[] args) { List<string> names = new List<string>() { "Вова", "Юра", "Надя", "Лена" }; DisplayList(names, ','); DisplayList(names, 1); Console.ReadLine(); } }
|
AlPer
03 июл 2015 10:51
Александр_Бугай 16 май 2015 22:04
if (split==1) { GetSplitComma(numbers); } else { GetSplitOther(numbers); }
Александр а в чем заключается Ваша "перегрузка"?
|
Warguss
11 июн 2015 10:37
class Program { static void DivideList(string[] str) { foreach (var s in str) { Console.Write(s+", "); } }
static void DivideList(string[] str, char ch) { foreach (var s in str) { Console.Write("{0}{1} ", s, ch); } }
static void Main() { string[] namelist = { "Анатолий", "Виктор", "Дмитрий", "Валерий", "Станислав", "Игорь", "Алексей" };
DivideList(namelist);
Console.Write("\nВведите символ разделителя: "); char delimiter = Convert.ToChar(Console.ReadLine()); DivideList(namelist, delimiter);
Console.ReadKey(); } }
|
Александр_Бугай
16 май 2015 22:04
class Program { public static void GetSplitComma(int numbers) { string s = ""; string name; for (int i = 0; i+1 < numbers; i++) { Console.WriteLine("Input name"); name = Convert.ToString(Console.ReadLine() + ","); s += name; } Console.WriteLine("Input name"); name = Convert.ToString(Console.ReadLine()); s += name; Console.WriteLine(s); } public static void GetSplitOther(int numbers) { string s = ""; string name; Console.WriteLine("Input your split. Choose any button"); string split = Convert.ToString(Console.ReadLine()); for (int i = 0; i + 1 < numbers; i++) { Console.WriteLine("Input name"); name = Convert.ToString(Console.ReadLine() + split); s += name; } Console.WriteLine("Input name"); name = Convert.ToString(Console.ReadLine()); s += name; Console.WriteLine(s); } static void Main(string[] args) { Console.WriteLine("Input numbers of names"); int numbers = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Input type of split. comma - 1, other - any button"); int split = Convert.ToInt32(Console.ReadLine()); if (split==1) { GetSplitComma(numbers); } else { GetSplitOther(numbers); } Console.ReadLine();
} }
|
Максим
15 май 2015 14:21
namespace HomeWork_MethodOverload { class Program { static void SomeMethod(string[] names) { int count = 1; Console.WriteLine(); foreach (string show in names) { if (count < names.Length) { Console.Write(show + ", "); count++; } else Console.Write(show + "."); } } static void SomeMethod(string[] names, char sign) { int count = 1; Console.WriteLine(); foreach (string show in names) if (count < names.Length) { count++; Console.Write(show + sign + " "); } else Console.Write(show + "/End/"); } static void SomeMethod(string[] names, char sign, char endSign) { int count = 1; Console.WriteLine(); foreach (string show in names) if (count < names.Length) { Console.Write(show + sign + " "); count++; } else Console.Write(show + endSign); }
static void Main(string[] args) { string[] names = { "Maxim", "Marina", "Ivan", "Alsu", "Timur", "Ramil" }; SomeMethod(names); SomeMethod(names, '='); SomeMethod(names, '^', '_'); Console.ReadKey(); } } }
|
Максим
23 апр 2015 12:19
Иван --- Нормально всё, задание простое
|
Иван
20 апр 2015 21:26
Скажите пожалуйста все ли как надо, если нет то подскажите как улучшить\исправить код
using System; using System.Collections.Generic; using System.Linq; using System.Text;
namespace Перегрузка_методов { class Program { public static void GetName(string[] Names) { foreach (string val in Names) { Console.WriteLine(val + ','); } } public static void GetName(string[] Names, string a) { foreach (string val in Names) { Console.Write(val + a); } } static void Main(string[] args) { // Настройка массива Console.Write("Введите предполагаемое количество имен: "); int a = Convert.ToInt32(Console.ReadLine()); //Создание массива string[] Names = new string[a]; //Ввод имен for (int i = 0; i < Names.Length; i++) { Console.Write("Имя " + (i + 1) + ": "); string name = Console.ReadLine(); Names[i] = name; } //Ввод символа разделителя Console.Write("Введите символ - разделитель: "); string s = Console.ReadLine();
//Вывод результата Console.WriteLine("Без разделителя: "); GetName(Names);
Console.WriteLine("С разделителем: "); GetName(Names, s);
//Задержка консоли Console.Read(); } } }
|
Dmitriy
31 мар 2015 21:36
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO;
namespace LessonOverload_of_methods { class Program { public static void Replace2(string[] array) { foreach (string f in array) { Console.WriteLine(f + ","); } } public static void Replace2(string[] array, string a) { foreach (string f in array) { Console.WriteLine(f + a); } } static void Main(string[] args) { string s; FileStream file2 = new FileStream("d:\\Lesson/test.txt", FileMode.Open); //создаем файловый поток StreamReader reader2 = new StreamReader(file2); s =reader2.ReadToEnd(); string[] array = s.Split(' '); Replace2(array); Console.WriteLine("Введите любой символ, на который хотите изменить запятую в конце каждого имени"); string a = Console.ReadLine(); Replace2(array, a); reader2.Close(); //закрываем поток } } }
|
Максим
31 мар 2015 11:52
Dmitriy --- Действительно, как так, что вы в первом варианте создали 2 разных класса. Ну второй вариант уже почти что надо, осталось лишь методы статическими сделать, нет смысла здесь создавать объект Replacement
|
Dmitriy
31 мар 2015 01:04
For дяди Коли
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO;
namespace LessonOverload_of_methods { class Replacement { public void Replace2(string[] array) { foreach (string f in array) { Console.WriteLine(f+","); } } public void Replace2(string[] array, string a) { foreach (string f in array) { Console.WriteLine(f + a); } } } class Program { static void Main(string[] args) { string s; FileStream file2 = new FileStream("d:\\Lesson/test.txt", FileMode.Open); //создаем файловый поток StreamReader reader2 = new StreamReader(file2); s =reader2.ReadToEnd(); string[] array = s.Split(' '); Replacement rep = new Replacement(); rep.Replace2(array); Console.WriteLine("Введите любой символ, на который хотите изменить запятую в конце каждого имени"); string a = Console.ReadLine(); rep.Replace2(array, a); reader2.Close(); //закрываем поток } } }
|
Дядя Коля
30 мар 2015 14:25
Dmitriy --------- Перечитайте пожалуйста данный урок и переделайте задание. А также избавьтесь от полей которые не используются.
|
Dmitriy
29 мар 2015 18:36
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO;
namespace LessonOverload_of_methods { class Replacement { public string[] array; public void Replace2(string[] array) { foreach (string f in array) { Console.WriteLine(f+","); } } } class Replacement2 : Replacement { public string a; public void Replace2(string[] array, string a) { foreach (string f in array) { Console.WriteLine(f + a); } } } class Program { static void Main(string[] args) { string s; FileStream file2 = new FileStream("d:\\Lesson/test.txt", FileMode.Open); //создаем файловый поток StreamReader reader2 = new StreamReader(file2); s =reader2.ReadToEnd(); string[] array = s.Split(' '); Replacement rep = new Replacement(); rep.Replace2(array); Console.WriteLine("Введите любой символ, на который хотите изменить запятую в конце каждого имени"); string a = Console.ReadLine(); Replacement2 rep2 = new Replacement2(); rep2.Replace2(array, a); reader2.Close(); //закрываем поток } } }
|
Andriy
20 мар 2015 18:29
class Program { static string a = "Andrey"; static string b = "Sergiy"; static string c = "Mukola"; static string d = "Pavlo"; public static void Imena() { Console.WriteLine(a+", "+b+", "+c+", "+d); }
public static void Imena(string r) { Console.WriteLine(a + r + " " + b + r + " " + c + r + " " + d); }
static void Main() { Console.WriteLine("Vvedit rozdilnuk"); string r1 = Console.ReadLine(); Imena(); Imena(r1);
Console.ReadLine(); }
|
sdfsdf
18 мар 2015 10:22
static void Main(string[] args) { string[] s = { "aaa", "bbb", "ccc" }; somemethod(s); Console.WriteLine(); somemethod(s, Convert.ToChar(Console.ReadLine())); Console.ReadLine(); } static void somemethod(string[] s) { for (int i = 0; i < s.Length - 1; i++) Console.Write(s[i] + ", "); Console.Write(s[s.Length - 1] + '.'); } static void somemethod(string[] s, char c) { for (int i = 0; i < s.Length - 1; i++) Console.Write(s[i] + c + ' '); Console.Write(s[s.Length - 1] + '.'); } }
|
Виталий
20 фев 2015 11:34
Вот, перегрузил:
class Program { public static void delimiter(string a, string b, int c, int d) { Console.WriteLine(c + "." + a + " " + d + "." + b); } public static void delimiter(string a, string b, string c) { Console.WriteLine(a + "," + b + "," + c); } static void Main(string[] args) { delimiter("Миша", "Коля", 1, 2); delimiter("Миша", "Коля", "Толя"); Console.ReadKey(); } }
|
Виталий
19 фев 2015 20:13
Опять попробовал. "Требуется ссылка на объект" кажется, слишком перегрузил.
class Program { string[] names = { "Иван", "Николай", "Виталий", "Максим" }; void schet() { for (int number = 0; number < 4; number++) { Console.WriteLine(names[number] + ","); } } void schet(string delimiter) { for (int number = 0; number < 4; number++) { Console.WriteLine(names[number] + delimiter); } } static void Main(string[] args) { schet(); } }
|
Виталий
19 фев 2015 13:46
Не знаю почему, но определяет что-то не так. Похоже, перестарался...
class program { public void delimiter(string a, string b, string c, string delimiter) { Console.WriteLine(a + delimiter + b + delimiter + c + "."); } public void delimiter(string a, string b, string c, int delimiter) { Console.WriteLine(a + delimiter + b + delimiter + c + "."); } public void delimiter(string a, string b, string c, ulong delimiter) { Console.WriteLine(a + delimiter + b + delimiter + c + "."); } static void Main (string[] args) { delimiter("Виталий", "Максим","Сергей", "-"); } }
|
AlexWolf
03 фев 2015 14:48
так правильно?
using System; using System.Collections.Generic; using System.Linq; using System.Text;
namespace ConsoleApplication1 { class Names { string[] names = new string[4]{"Миша", "Коля", "Маша", "Толя"}; public int i; public void show() { for (i = 0; i < names.Length; i++) { Console.Write(names[i] + ", "); } } public void show(string a) { for (i = 0; i < names.Length; i++) { Console.Write(names[i] + a); } } } class Program { static void Main(string[] args) { string a = ""; Names text = new Names(); bool on = true; Console.WriteLine("Жми только 1, 2 или 3."); text.show(); do switch (Console.ReadKey(true).Key) { case ConsoleKey.D1: Console.Clear(); a = " + "; text.show(a); break; case ConsoleKey.D2: Console.Clear(); a = " - "; text.show(a); break; case ConsoleKey.D3: Console.Clear(); a = "/ "; text.show(a); break; case ConsoleKey.Escape: on = false; break; default: Console.WriteLine("Жми только 1, 2 или 3."); break; } while (on); } } }
|
Максим
25 дек 2014 14:13
pinguin-linuxoid --- Можно
|
pinguin-linuxoid
25 дек 2014 12:31
Видимо я один создавал конструктор принимающий список, чтоб метод был полностью пустой
using System; using System.Collections.Generic; using System.Linq; using System.Text;
namespace Lesson_23 { class List_in { private List<string> test; public List_in(List<string> test) { this.test = test; }
public void Get_list() { for(int i = 0; i < test.Count; i++) { if(i < test.Count - 1){ Console.Write(test[i] + ", "); } else Console.Write(test[i]); } Console.WriteLine("\n"); }
public void Get_list(char a) { for(int i = 0; i < test.Count; i++) { if(i < test.Count - 1){ Console.Write(test[i] + a + " "); } else Console.Write(test[i]); } Console.WriteLine("\n"); } }
class Program { static void Main(string[] args) {
List<string> trololo = new List<string>(); trololo.Add("test"); trololo.Add("test2"); trololo.Add("test3");
List_in torch = new List_in(trololo); torch.Get_list(); torch.Get_list('@'); torch.Get_list('*');
Console.ReadKey(); } } }
Так можно?
|
Диманиак
01 дек 2014 13:06
можно было создать отдельный класс как у Jamshid, но т.к. Program тоже класс, то можно и так :)
class Program { public static void PrintNames(List<string> names) { for (int i=0;i<names.Count;i++) { string name = names.ElementAt(i); Console.Write(name); if (i < names.Count-1) Console.Write(","); else Console.WriteLine("\n"); } }
public static void PrintNames(List<string> names, char separator) { for (int i = 0; i<names.Count; i++) { string name = names.ElementAt(i); Console.Write(name); if (i < names.Count - 1) Console.Write(separator.ToString()); else Console.WriteLine("\n"); } } static void Main(string[] args) { List<string> names = new List<string>(); names.Add("Марина"); names.Add("Анна"); names.Add("Ирина"); Console.WriteLine("Строка с разделителем по-умолчанию:\n"); PrintNames(names); Console.WriteLine("Введите новый разделитель:"); char separator = Console.ReadLine().ElementAt(0); Console.WriteLine("Строка с разделителем \"" + separator.ToString()+ "\":\n"); PrintNames(names, separator); Console.ReadKey(); } }
|
Jamshid
12 ноя 2014 15:14
class Program { public static void Main(string[] args) { List<string> names = new List<string>{"Mike", "John", "Katy", "Bob", "Kamilla"}; myLib.listing(names); Console.WriteLine(); myLib.listing(names,':'); Console.Write("Press any key to continue . . . "); Console.ReadKey(true); } class myLib { public static void listing(List<string> names) { for(int i=0;i<names.Count-1;i++) Console.Write(names[i]+","); Console.Write(names[names.Count-1]); } public static void listing(List<string> names, char separator) { for(int i=0;i<names.Count-1;i++) Console.Write(names[i]+separator.ToString()); Console.Write(names[names.Count-1]); } } }
|
Максим
26 сен 2014 19:39
Firik --- Та нет, нормально всё
|
Firik
25 сен 2014 01:03
Намудрил?)
class Program { public static void ShowNames(List<string> Spisok) { int Max = Spisok.Count - 1; int Tek = 0; string s = ""; foreach (string el in Spisok) { if (Tek != Max) { s = el + ", " + s; Tek++; } else s = s + el; } Console.WriteLine(s); return; }
public static void ShowNames(List<string> Spisok, string Symbol) { int Max = Spisok.Count - 1; int Tek = 0; string s = ""; foreach (string el in Spisok) { if (Tek != Max) { s = el + Symbol + s; Tek++; } else s = s + el; } Console.WriteLine(s); return; }
static void Main(string[] args) { List<string> Spisok = new List<string>(); Spisok.Add("Вася"); Spisok.Add("Петя"); Spisok.Add("Миша"); Spisok.Add("Серега"); ShowNames(Spisok); Console.WriteLine("Введите делитель"); string del = Console.ReadLine(); ShowNames(Spisok, del); Console.ReadKey(); } }
|
dimasik
22 май 2014 23:52
namespace PeregruzMetoda { class Names { public List<string> names = new List<string> { "Лукьян", "Борис", "Маркиз", "Карлос", "Сантос", "Кирилл" };
public void Spisok() { for (int i = 0; i <names.Count-2; i++) { Console.Write(names[i + 1] + ", "); } Console.WriteLine(names[names.Count-1]); } public void Spisok(string a) { for (int i = 0; i <names.Count-2; i++) { Console.Write( names[i+1] + a); } Console.WriteLine(names[names.Count-1]); }
} class Program { static void Main(string[] args) { Names name = new Names();
name.Spisok(); name.Spisok(" | ");
Console.ReadKey();
} } }
|
Максим
24 апр 2014 21:04
Ромик --- Убирать не нужно, такое уж условие. Только часть else if здесь лишняя, хватает просто else: if (i < list.Count-1) Console.Write(list[i] + ", "); else Console.Write(list[i]);
|
Ромик
23 апр 2014 16:41
Написал - поцеловал монитор =) class MyProgram { public void Met(List<string>list) { for (int i = 0; i < list.Count; i++) { if (i < list.Count-1) Console.Write(list[i] + ", "); else if (i == list.Count-1) Console.Write(list[i]); } } public void Met(List<string> list, string razdel) { for (int i = 0; i < list.Count-1; i++) { if (i < list.Count-1) Console.Write(list[i] + razdel + " "); else if (i == list.Count) Console.Write(list[i]); } } } class Program { static void Main(string[] args) { MyProgram my = new MyProgram(); List<string> name = new List<string>() { "John","Frenk","Gregory"}; my.Met(name); Console.WriteLine("\nВведите символ через который разделим"); string simv = Console.ReadLine(); my.Met(name, simv); Console.ReadKey(); } } только 1 момент мне не нравиться, как убрать "-1" в методах после list.Count?
|
Максим
19 мар 2014 14:54
The Saint --- Цикл должен быть внутри метода AddAndDisplay, а не этот метод в цикле. А чтобы убрать последний символ, делайте проверку в цикле последняя ли это итерация, если да - вывод без разделителя
|
The Saint
19 мар 2014 14:21
Даже вот так, если правильнее:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;
namespace ReLoad { class Program { public static void AddAndDisplay(string a, string b) { Console.Write(a + b); } static void Main(string[] args) { List<string> team = new List<string>() { "Иван", "Петр", "Василий", "Александр" }; int l = team.Count; Console.WriteLine("Введите разделительный символ:"); string b = Convert.ToString(Console.ReadLine()); Console.Clear();
for (int i = 0; i < l; i++) { AddAndDisplay(team[i], b + " "); } Console.ReadLine(); } } }
|
Максим
13 фев 2014 15:28
Илюфер --- Ну вывести в цикле массив строк, это мы проходили уже
|
Илюфер
13 фев 2014 14:35
Да, но я использовал IEnumerable и метод Join, который мы еще как бы не учили. Вопрос заключается в следующем: возможно ли выполнить задание, базируясь только на том что мы знаем по вашим урокам? (без IEnum и Join)
|
Максим
12 фев 2014 17:45
Илюфер --- Не понял вопроса. Это задание Вы выполнили как и требовалось
|
Илюфер
12 фев 2014 10:50
Кстати, как выполнить задание, не отходя от изученного именно в здешних уроках?
|
Илюфер
12 фев 2014 09:30
огонь?
public class MyClass { public static void SuperGenerateStringFromList(IEnumerable<string> str) { Console.WriteLine(string.Join(", ", str)); }
public static void SuperGenerateStringFromList(IEnumerable<string> str, string separator) { Console.WriteLine(string.Join(separator, str)); }
static void Main(string[] args) { List<string> names = new List<string> { "Obi", "Yoda", "Anaken" };
SuperGenerateStringFromList(names); // Obi, Yoda, Anaken SuperGenerateStringFromList(names, " + "); // Obi + Yoda + Anaken SuperGenerateStringFromList(names, " - "); // Obi - Yoda - Anaken
Console.ReadKey();
} }
|
Максим
11 фев 2014 20:36
Ilyko --- Здравствуйте. Синтаксис это немного не то, но я понял, что Вы имеете в виду. Пока я пишу уроки о том, как вообще программировать на C#, без этого идти дальше нет смысла. Думаю, осталось не так много уроков до следующего этапа
|
Ilyko
11 фев 2014 08:32
Доброго времени суток. Вы планируете осветить весь синтаксис языка, только затем идти дальше? Например в Windows Forms?
|
Максим
05 фев 2014 18:09
Дмитрий --- Думаю, это тема для отдельного урока
|
Дмитрий
05 фев 2014 12:24
И, кстати говоря, мне кажется, было бы неплохо здесь же и про перегрузку операторов рассказать
|