I am doing a web class in programming C#. I want to say right of the bat that I do not want you guys to do my work for me. Now to my specific/generic problem. I am used to writing sequential code. It is when I try to move my working code (s) to classes/methods I get in deep dodo.
The code example below is for a guessing game 1-100. I have tried for four hours straight do break code out in to a separate Class. I manage to get the user input or the RND in to a class. Then the logic in main breaks down. It seems like I get best result if the RND block is Static but user input is not Static etc., etc. In the end I went back to scratch with everything in Main and turn to you for generic guidelines.
I need to get this in my head so I can clean up my Main every time. Start at Class Program Ignore Screen that is working.
<--------Code Below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Uppgift3GissaTalet
{
static class Screen
{
// Screen - Tools that I use every time ignore until end of screen======================================= >
// Methods for screen handling:
//
// Clear Screen ------------------------------------------
static public void cls()
{
Console.Clear();
}
// Set Curser Posittion ----------------------------------
static public void cup(int column, int rad)
{
Console.SetCursorPosition(column, rad);
}
// Key Input --------------------------------------------
static public ConsoleKeyInfo inKey()
{
ConsoleKeyInfo in_key; in_key = Console.ReadKey(); return in_key;
}
// String Input -----------------------------------------
static public string inStr()
{
string in_string; in_string = Console.ReadLine(); return in_string;
}
// Int Input -------------------------------------------
static public int inInt()
{
int int_in; try { int_in = Int32.Parse(Console.ReadLine()); }
catch (FormatException) { Console.WriteLine("Input Error \b"); int_in = 0; }
catch (OverflowException) { Console.WriteLine("Input Owerflow\b"); int_in = 0; }
return int_in;
}
// Float Input -------------------------------------------
static public float inFloat()
{
float float_in; try { float_in = Convert.ToSingle(Console.ReadLine()); }
catch (FormatException) { Console.WriteLine("Input Error \b"); float_in = 0; }
catch (OverflowException) { Console.WriteLine("Input Owerflow\b"); float_in = 0; }
return float_in;
}
// Meny ------------------------------------------------
static public int meny(string rubrik, string m_val1, string m_val2)
{ // Meny med 2 val ---------------------
int menSvar; menyRubrik(rubrik); menyRad(m_val1); menyRad(m_val2); menSvar = menyInm();
return menSvar;
}
static public int meny(string rubrik, string m_val1, string m_val2, string m_val3)
{ // Meny med 3 val ---------------------
int menSvar; menyRubrik(rubrik); menyRad(m_val1); menyRad(m_val2); menyRad(m_val3); menSvar = menyInm();
return menSvar;
}
static public int meny(string rubrik, string m_val1, string m_val2, string m_val3, string m_val4)
{ // Meny med 4 val ---------------------
int menSvar; menyRubrik(rubrik); menyRad(m_val1); menyRad(m_val2); menyRad(m_val3); menyRad(m_val4); menSvar = menyInm();
return menSvar;
}
static public int meny(string rubrik, string m_val1, string m_val2, string m_val3, string m_val4, string m_val5)
{ // Meny med 5 val ---------------------
int menSvar; menyRubrik(rubrik); menyRad(m_val1); menyRad(m_val2); menyRad(m_val3); menyRad(m_val4); menyRad(m_val5); menSvar = menyInm();
return menSvar;
}
static public int meny(string rubrik, string m_val1, string m_val2, string m_val3, string m_val4, string m_val5, string m_val6)
{ // Meny med 6 val ---------------------
int menSvar; menyRubrik(rubrik); menyRad(m_val1); menyRad(m_val2); menyRad(m_val3); menyRad(m_val4); menyRad(m_val5); ; menyRad(m_val6); menSvar = menyInm();
return menSvar;
}
static void menyRubrik(string rubrik)
{ // Meny rubrik --------
cls(); Console.WriteLine("\n\t {0}\n----------------------------------------------------\n", rubrik);
}
static void menyRad(string menyVal)
{ // Meny rad --------
Console.WriteLine("\t {0}", menyVal);
}
static int menyInm()
{ // Meny inmating ------
int mVal; Console.Write("\n\t Menyval : "); mVal = inInt(); return mVal;
}
// Screen - End <========================================
} // screen <----
class Program
{
static void Main(string[] args)
{//Foreign bla bla.
string rubrik = "\tGissa ett tal mellan 1 och 100: ";
Random rnd = new Random();
int slumpTal = rnd.Next(1, 101);
int svar;
int count = 0;
Screen.cls();
//Console.Write("\t\t" + slumpTal); //Used for fixing logic.
Console.WriteLine("\n\t {0}\n\t----------------------------------------------\n", rubrik);
Console.Write("\tSkriv ditt tal: ");
svar = Screen.inInt();
count++;
//Foreign yadda yadda.
do
{
if (svar < 1 || svar > 100) //Påminn användaren om att hålla sig inom ramarna.
{
System.Console.Write("\tTalet du söker är inom intervallet 1-100!", svar);
Console.Write("\n\tSkriv ditt tal: ");
svar = Screen.inInt();
}
else if (slumpTal > svar && (slumpTal - svar < 6)) //Getting hotter.
{
System.Console.Write("\tTalet du söker är större än {0} men du är nära nu!", svar);
Console.Write("\n\tSkriv ditt tal: ");
svar = Screen.inInt();
count++;
}
else if (slumpTal > svar) //Ge ledtråd om att användaren måste skriva ett större tal.
{
System.Console.Write("\tTalet du söker är större än {0}.", svar);
Console.Write("\n\tSkriv ditt tal: ");
svar = Screen.inInt();
count++;
}
else if (slumpTal < svar && (svar - slumpTal < 6)) //Getting hotter.
{
System.Console.Write("\tTalet du söker är mindre än {0} men du är nära nu!", svar);
Console.Write("\n\tSkriv ditt tal: ");
svar = Screen.inInt();
count++;
}
else if (slumpTal < svar) //Ge ledtråd om att användaren måste skriva ett lägre tal.
{
System.Console.Write("\tTalet du söker är mindre än {0}.", svar);
Console.Write("\n\tSkriv ditt tal: ");
svar = Screen.inInt();
count++;
}
} while (svar != slumpTal);
Screen.cls();
Console.ForegroundColor = ConsoleColor.Green; //Changing colour(sic!) at win.
Console.Write("\n\n\t\tBra jobbat, du löste problemet. Rätt svar är {0}!\n\t\tDu tog {1} försök på dig.", slumpTal, count);
Screen.inKey();
}//<------------Main
}//<===========Program
}
I've just tried to break it up a bit. It's harder to interpret what you are creating without using English naming, however the principles are the same.
Create objects within your main, of the classes you've created.
class Program
{
static void Main(string[] args)
{
string rubrik;
string m_val1;
string m_val2;
Utilities utility = new Utilities();
string str = Console.ReadLine();
int myint = utility.inInt(str);
MyClass myclass = new MyClass();
// or
// getting these values before doing so
MyClass class = new MyClass(rubrik, m_val1, m_val2);
myclass.Method(myint); // etc
The variables that will be passed in may be used in class methods
Or may become initialisers for an instantiation of that class.
public class MyClass
{
// class members
// eg ???
public string Rubrik {get; set;}
// constructors
public MyClass(){}
public MyClass(string rubrik, string m_val1, string m_val2)
{
Rubrik = rubrik;
// and so on.
}
// TODO .. add these menyRad(m_val1);
// menyRad(m_val2); menyRad(m_val3);
// menyRad(m_val4); menSvar = menyInm();
public int meny(string rubrik, string m_val1, string m_val2)
{
int menSvar;
// Use class members to do some calculation and return the value
return menSvar;
}
// etc
}
Create a separate Utilities class for any house keeping methods.
public class Utilities
{
// Int Input -------------------------------------------
public int inInt(string input)
{
int int_in;
try
{
int_in = Int32.Parse(intput);
}
catch (FormatException)
{
Console.WriteLine("Input Error \b");
int_in = 0;
}
catch (OverflowException)
{
Console.WriteLine("Input Owerflow\b");
int_in = 0;
}
return int_in;
}
// Float Input -------------------------------------------
public float inFloat(string input)
{
... etc
}
}
Related
I just finished a programming 1 class and the last assignment I was making was named "the buss" where I was supposed to identify the different passengers on the buss. Sort the by age, count the average age on the buss and so on. But there were some things I didn't figure out in time and trying to do it now and was looking is someone could help me.
My problem is that I'm supposed to identify their sex and I just can't figure out how to make that.
The second one is to "poke them" and based on different age and sex make different comments.
using System;
using System.Globalization;
using System.Runtime.ExceptionServices;
using System.Security.Cryptography;
namespace Bussen
{
class Buss
{
//passagerare means passenger
public int[] passagerare = new int[25];
public int antal_passagerare;
public void Run()
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("Welcome to the awesome Buss-simulator");
int menu;
do
{
//the menu of every choise you can make.
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("Välj ett alternativ: ");
Console.WriteLine("1. Lägg till en passagerare. ");
Console.WriteLine("2. Kontrollera åldern på passagerarna. ");
Console.WriteLine("3. Beräkna den sammanlagda åldern på passagerarna. ");
Console.WriteLine("4. Beräkna medelåldern på passagerarna. ");
Console.WriteLine("5. Identifiera den äldsta passageraren. ");
Console.WriteLine("6. Hitta åldern. ");
Console.WriteLine("7. Sortera bussen efter ålder. ");
Console.WriteLine("8. Print sex. ");
Console.WriteLine("0. Avsluta programmet. ");
menu = int.Parse(Console.ReadLine());
switch (menu)
{
case 1:
add_passenger();
break;
case 2:
Print_buss();
break;
case 3:
Calc_total_age();
break;
case 4:
Calc_average_age();
break;
case 5:
Max_age();
break;
case 6:
Find_age();
break;
case 7:
Sort_buss();
break;
case 8:
Print_sex();
break;
case 0:
menu = 0;
break;
}
} while (menu != 0);
}
//where you add you passengers by age
public void add_passenger()
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Skriv in hur många passagerare ni vill lägga till.");
string str1 = Console.ReadLine();
int size = Convert.ToInt32(str1);
for (int i = 0; i < size; i++)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Lägg till en passagerare genom att skriva in personens ålder ålder: ");
string answer = Console.ReadLine();
int nya_passagerare = Convert.ToInt32(answer);
passagerare[i] = nya_passagerare;
antal_passagerare++;
}
}
// this is where you print out all the passengers.
public void Print_buss()
{
for (int i = 0; i < antal_passagerare; i++)
{
Console.ForegroundColor = ConsoleColor.Magenta;
Console.WriteLine("Passagerarnas ålder är: " + passagerare[i]);
}
}
//this is where you add the total age on every passenger.
public void Calc_total_age()
{
int sum = 0;
for (int i = 0; i < passagerare.Length; i++)
{
sum += passagerare[i];
}
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Den sammanlagda åldern på passagerarna är " + sum + ".");
}
//where you calculate the average age on the buss
public void Calc_average_age()
{
int sum = 0;
for (int i = 0; i < antal_passagerare; i++)
{
sum += passagerare[i];
}
double dsum = Convert.ToDouble(sum);
double dsum1 = dsum / antal_passagerare;
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("Passagerarnas medelålder är " + dsum1 + " år.");
Console.WriteLine(" ");
}
//where you find the oldest passenger on the buss
public void Max_age()
{
int maxAge = passagerare[0];
foreach (var enPassagerare in passagerare)
if (enPassagerare > maxAge)
maxAge = enPassagerare;
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Den äldsta passageraren är " + maxAge + " år gammal.");
}
//this where you find with seat the diffent passengers sitt on between surtn ages
public void Find_age()
{
bool found = false;
Console.WriteLine("Vilken är den yngst åldern som du vill hitta ?");
int yngst = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Vilken är det högst åldern som du vill hitta ?");
int högst = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Passagerarna som mellan åldern " + yngst + " - " + högst + " sitter i : ");
for (int i = 0; i < passagerare.Length; i++)
{
if (passagerare[i] > högst || passagerare[i] > yngst)
{
Console.WriteLine("stolen " + i);
found = true;
}
}
if(!found)
{
Console.WriteLine("OBS det finns inte sån ålder i bussen ");
}
}
//this is where you sort the buss from ungest to oldest passenger
public void Sort_buss()
{
int temp;
for (int i = 0; i < passagerare.Length - 1; i++)
{
for (int j = 0; j < passagerare.Length - 1 - i; j++)
{
if (passagerare[j] > passagerare[j + 1])
{
temp = passagerare[j];
passagerare[j] = passagerare[j + 1];
passagerare[j + 1] = temp;
}
}
}
for (int i = 0; i < passagerare.Length; i++)
{
Console.WriteLine("Passagerare " + (i + 1) + " är " + passagerare[i] + " år gammal ");
}
}
//this is where im supose to identify with sex every passenger has...
public void Print_sex()
{
for (int k = 0; k < info.Length +1; k++)
{
Console.WriteLine("Plats" + info[k] + kön);
}
}
class Program
{
public static void Main(string[] args)
{
var minbuss = new Buss();
minbuss.Run();
var mysex = new sex();
Console.ForegroundColor = ConsoleColor.DarkCyan;
Console.Write("press any key to continue . . . ");
Console.ReadKey(true);
}
}
}
}
Like others have suggested, the best way to do this is to refactor (change) your code to use classes. This is called object oriented programming. I'll try my best to explain it for your current level of experience.
Firstly, create a class. Let's call this "Person".
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Sex { get; set; }
}
Secondly, let's create a list to hold the people on the bus. Instead of creating an array with a set size, we'll create a List.
List<Person> People = new List<Person>();
Now, in your "add_passenger" method, which I advise you rename to follow the general coding standards, to "AddPassenger".
public void AddPassenger()
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Skriv in hur många passagerare ni vill läggatill.");
// Let's presume the input is in the format Name, Age, Sex.
string input = Console.ReadLine();
// This will create a string array with all the "details".
// E.g [0] = Name, [1] = Age, Sex [2].
string[] personDetails = input.Split(",");
// Instantiate a person object and populate the properties.
Person person = new Person();
person.Name = personDetails[0].Trim();
person.Age = Convert.ToInt32(personDetails[1].Trim());
person.Sex = personDetails[2].Trim();
// Add the newly created person to the people list.
People.Add(person);
}
Now you're probably thinking that your bus can a very large amount of people, which is right because a List can hold a couple billion items - that's a pretty big bus! I would advise to add a method that checks the count is less than 25 before the AddPassenger() method call within your switch statement.
I would also like to advise that C# has an incredibly powerful ability to do searches within lists and can even perform mathematical calculations for you in one liners using something called LINQ. An example of this from your sample code would be your "Calc_total_age" method - which I would rename to CalculateTotalAge (it's better to be specific what a function does than to abbreviate. This helps other developers working on your code understand what it's doing if it's clear.
public void CalculateTotalAge()
{
Console.ForegroundColor = ConsoleColor.Red;
// Calculate the total age using a LINQ expression.
int totalAge = People.Sum(x => x.Age);
Console.WriteLine($"Den sammanlagda åldern på passagerarna är {totalAge}");
}
Finally, to answer your question about listing the age of every person on the bus, we can do the following.
public void ListSexOfEveryPerson()
{
foreach(Person person in people)
{
Console.WriteLine($"{person.Name}'s sex is {person.Sex}");
}
}
If we wanted to get creative and use LINQ expressions, we could do:
public void ListSexOfEveryPerson()
{
people.ForEach(p => Console.WriteLine($"{p.Name}'s sex is {p.Sex}"));
}
If LINQ expressions are confusing at this time, then just use the first example until you feel comfortable, there's nothing wrong with a foreach loop!
Also, if you're wondering what the '$' symbol before the quotation is used for, it's for string interpolation. It's a better way of 'injecting' values into a string instead of doing "X" + "X" + "X".
Hope this helps!
Can somebody help me to separate the user input by space so my program can sort it by spaces
I don't know how to separate the user input by space how will I do that?
can anyone help me with this?
and also if you have a suggestion in improving it please do so. thank you so much!
Here is the output of my program:
Enter a string: 10 42 a ds 1 sfa 422 d w
Choose between the two sorting strategies:
a) - Bubble Sort
b) - Quick Sort
Your option: a
Bubble Sort: , , , , , , , , 0, 1, 1, 2, 2, 2, 4, 4, a, a, d, d, f, s, s, w,
I want ito be like this:
Enter a string: 10 42 a ds 1 sfa 422 d w
Choose between the two sorting strategies:
a) - Bubble Sort
b) - Quick Sort
Your option: a
Bubble Sort: 1, 10, 42, 422, a, d, ds, sfa, w
I am a newbie, please help me.
Here are my code:
using System;
namespace SortStrategyPattern
{
class Context
{
public static string userInput;
private IStrategy _strategy;
public Context()
{}
public Context(IStrategy strategy)
{
this._strategy = strategy;
}
public void SetStrategy(IStrategy strategy)
{
this._strategy = strategy;
}
class Program
{
static void Main(string[] args)
{
var context = new Context();
context.UserInput();
}
}
public void UserInput()
{
Console.Write("Enter a string: ");
userInput = Console.ReadLine();
char response;
var context = new Context();
do
{
Console.WriteLine();
Console.WriteLine("Choose between the two sorting strategies:");
Console.WriteLine("\ta) - Bubble Sort");
Console.WriteLine("\tb) - Quick Sort");
Console.WriteLine();
Console.Write("Your option: ");
{
response = char.Parse(Console.ReadLine());
}
Console.WriteLine();
switch (response.ToString().ToLower())
{
case "a":
BubbleSort OutputA = new BubbleSort();
OutputA.Implementation(userInput);
break;
case "b":
QuickSort OutputB = new QuickSort();
OutputB.Implementation(userInput);
break;
default:
Console.WriteLine("Invalid answer. Please enter a valid option.");
response = '\0';
break;
}
} while (response == '\0');
}
public interface IStrategy
{
object Implementation(string useInput);
}
class BubbleSort : IStrategy
{
public object Implementation(string userInput)
{
char temp;
char[] charStr = userInput.ToCharArray();
for (int x = 1; x < charStr.Length; x++)
{
for (int y = 0; y < charStr.Length - 1; y++)
{
if (charStr[y] > charStr[y + 1])
{
temp = charStr[y];
charStr[y] = charStr[y + 1];
charStr[y + 1] = temp;
}
}
}
Console.Write("Bubble Sort: ");
foreach (char input in charStr)
{
Console.Write(input + ", ");
}
return 0;
}
}
class QuickSort : IStrategy
{
public object Implementation(string userInput)
{
var charArray = userInput.ToCharArray();
quicksort(charArray, 0, userInput.Length);
Console.Write("Quick Sort: ");
foreach (char uinput in charArray)
{
Console.Write(uinput + ", ");
}
return 0;
}
static void quicksort(char[] userInput, int start, int end)
{
if (start < end)
{
int pivotIndex = partition(userInput, start, end);
quicksort(userInput, start, pivotIndex);
quicksort(userInput, pivotIndex + 1, end);
}
}
static void swap(char[] userInput, int i, int j)
{
char temp = userInput[i];
userInput[i] = userInput[j];
userInput[j] = temp;
}
static int partition(char[] userInput, int start, int end)
{
int pivotIndex = userInput[start];
int swapIndex = start;
for (int i = start + 1; i < end; i++)
{
if (userInput[i] < pivotIndex)
{
swapIndex++;
swap(userInput, i, swapIndex);
}
}
swap(userInput, start, swapIndex);
return swapIndex;
}
}
}
}
My answers assume you are trying to use the Strategy pattern to implement various sort methods.
Below are some coding tips that might be helpful:
Converting string data to a string array
As mention by #00110001, you can use the String.Split method to convert a string to an array of strings. In my example, I am passing in two parameters. The first determines what to delimited on, the second will remove any empty entries.
Example:
char[] delimiterChars = { ' ' };
string[] strInputArray = userInput.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);
Code Organization:
In this instance, you should not place classes inside other classes. They are not needed and the way you implement them makes your code very hard to read. I would suggest re-organizing the code as the follows example shows:
Example:
namespace SortStrategyPattern
{
public interface ISortStrategy
{
}
public class BubbleSort : ISortStrategy
{
}
public class QuickSort : ISortStrategy
{
}
public class SortContext : ISortStrategy
{
}
class Program
{
}
}
Encapsulate like functionality
You should only include logic that accomplishes a certain task in your classes. Mixing functionality just complicate things. Example your Context class should only contain logic that deal with storing a certain sorting strategy.
Example:
public class SortContext : ISortStrategy
{
private ISortStrategy _strategy;
private SortContext() { }
public SortContext(ISortStrategy strategy)
{
_strategy = strategy;
}
public void SetStrategy(ISortStrategy strategy)
{
_strategy = strategy;
}
public string[] Sort(string[] data)
{
return _strategy.Sort(data);
}
}
The logic that handles the user input and display the results should be place in the Program class Main method.
static void Main(string[] args)
{
char[] delimiterChars = { ' ' };
string userInput = "", sortOpt="";
do
{
// Retrieve a list of strings from the user. Each string is separated by one or more spaces.
Console.Write("Enter a list of strings: ");
userInput = Console.ReadLine();
// Terminate loop if blank/empty string is passed
if (String.IsNullOrWhiteSpace(userInput))
break;
// Split user input into a series of strings. Assuming empty entries are not allowed.
// Reference: https://learn.microsoft.com/en-us/dotnet/csharp/how-to/parse-strings-using-split
string[] strInputArray = userInput.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);
// Inquire sort method to use
Console.WriteLine("Choose between the two sorting strategies:");
Console.WriteLine("\ta) - Bubble Sort");
Console.WriteLine("\tb) - Quick Sort");
Console.WriteLine();
Console.Write("Your option: ");
sortOpt = Console.ReadLine();
// Determine the sort method
SortContext context = null;
switch ( sortOpt.Trim() )
{
case "a":
Console.WriteLine("\nPerforming Bubble Sort");
context = new SortContext(new BubbleSort());
break;
case "b":
Console.WriteLine("\nPerforming Quick Sort");
context = new SortContext(new QuickSort());
break;
default:
Console.WriteLine("Invalid answer. Please enter a valid option.");
continue;
}
string[] resultArray = context.Sort(strInputArray);
foreach (string str in resultArray)
Console.WriteLine(str);
} while (true);
Console.WriteLine("Press any key to continue...."); Console.ReadKey();
}
Well, you use method userInput.ToCharArray(); to separate what user inputs to the application.
You should use Split method, where you can specify which character to split by. So it look like: userInput.Split(' ');
Also, on how to make it better. You split the user input in a sorting algorithm - that's messing up repsonsibilities - sorting algorithm should take care only of sorting, not preparing input. That way, you also duplicate the code to split the string.
Sorting methods should accept string[] (array of strings) to sort.
So, changes should be done like that:
Change declaration: public static string[] userInput; (also, IMO that should just regular variable..)
userInput = Console.ReadLine().Split(' '); - here we prepare our input
And lastly - change method declarations:
public interface IStrategy
{
object Implementation(string[] userInput);
}
Also you do not need return type on that method, as you do not return any variable, just constant 0, which is not used anywhere. So yuo can even more simplify:
public interface IStrategy
{
void Implementation(string[] userInput);
}
I modified your code with a slight change. Both searches return the desired result. Do not define classes together. It reduces the readability of the program.
Program class
class Program
{
static void Main(string[] args)
{
var context = new Context();
context.UserInput();
}
}
Context class
class Context
{
public static string userInput;
private IStrategy _strategy;
public void UserInput()
{
while(true)
{
Console.Write("Enter a string: ");
userInput = Console.ReadLine();
char response;
do
{
Console.WriteLine();
Console.WriteLine("Choose between the two sorting strategies:");
Console.WriteLine("\ta) - Bubble Sort");
Console.WriteLine("\tb) - Quick Sort");
Console.WriteLine();
Console.Write("Your option: ");
response = char.Parse(Console.ReadLine());
Console.WriteLine();
switch (response.ToString().ToLower())
{
case "a":
_strategy = new BubbleSort();
_strategy.Implementation(userInput);
break;
case "b":
_strategy = new QuickSort();
_strategy.Implementation(userInput);
break;
default:
Console.WriteLine("Invalid answer. Please enter a valid option.");
response = '\0';
break;
}
} while (response == '\0');
Console.WriteLine(Environment.NewLine);
}
}
}
IStrategy interface
public interface IStrategy
{
void Implementation(string useInput);
}
BubbleSort class
class BubbleSort : IStrategy
{
public void Implementation(string userInput)
{
string temp;
string[] stringArray = userInput.Trim().Split(' ');
for (int x = 1; x < stringArray.Length; x++)
{
for (int y = 0; y < stringArray.Length - 1; y++)
{
if (String.Compare(stringArray[y], stringArray[y + 1], comparisonType: StringComparison.OrdinalIgnoreCase) > 0)
{
temp = stringArray[y];
stringArray[y] = stringArray[y + 1];
stringArray[y + 1] = temp;
}
}
}
Console.Write("Bubble Sort: ");
int i = 1;
foreach (string uinput in stringArray)
{
if (i == stringArray.Length)
Console.Write(uinput);
else
Console.Write(uinput + ", ");
i++;
}
}
}
QuickSort class
class QuickSort : IStrategy
{
public void Implementation(string userInput)
{
string[] stringArray = userInput.Trim().Split(' ');
Quick_Sort(stringArray, 0, stringArray.Length - 1);
Console.Write("Quick Sort: ");
int i = 1;
foreach (string uinput in stringArray)
{
if (i == stringArray.Length)
Console.Write(uinput);
else
Console.Write(uinput + ", ");
i++;
}
}
static void Quick_Sort(string[] userInput, int left, int right)
{
if (left < right)
{
int pivot = Partition(userInput, left, right);
if (pivot > 1)
{
Quick_Sort(userInput, left, pivot - 1);
}
if (pivot + 1 < right)
{
Quick_Sort(userInput, pivot + 1, right);
}
}
}
private static int Partition(string[] arr, int left, int right)
{
string pivot = arr[left];
while (true)
{
int comparison = String.Compare(arr[left], pivot, comparisonType: StringComparison.OrdinalIgnoreCase);
while (String.Compare(arr[left], pivot, comparisonType: StringComparison.OrdinalIgnoreCase) < 0 && left < right)
{
left++;
}
while (String.Compare(arr[right], pivot, comparisonType: StringComparison.OrdinalIgnoreCase) > 0 && right > 0)
{
right--;
}
if (left < right)
{
if (arr[left] == arr[right]) return right;
string temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
}
else
{
return right;
}
}
}
}
Bubble Sort
Quick Sort
I'm locked to show list member, compare and modify members.
This program is a automotive shop and I got Vendors (Salesman) , Customers (same method of vendors) and I will have and interface for cars/cargo/etc...
for now in' concentrating to methods for this list :
public static List<Venditori> Venditori = new List<Venditori>();
These are the proprieties of Vendors:
public class Venditori
{
public Guid Id { set; get; }
public string NomeVenditore { get; set; }
public string CognomeVenditore { get; set; }
public string TelefonoVenditore { get; set; }
public string EmailVenditore { get; set; }
public bool VenditoreAttivo { get; set; }
public string DateTime { get; set; }
public Venditori(Guid id, string nomevenditore, string cognomevenditore, string telefonovenditore,
string emailvenditore, bool venditoreattivo, string datetime)
{
this.Id = id;
this.NomeVenditore = nomevenditore;
this.CognomeVenditore = cognomevenditore;
this.TelefonoVenditore = telefonovenditore;
// Without this.
EmailVenditore = emailvenditore;
VenditoreAttivo = venditoreattivo;
DateTime = datetime;
venditoreattivo = true;
}
}
This is method to insert values, also print what i've just insert into list :
public static Venditori Registravenditore()
{
Venditori v = new Venditori();
v.Id = Guid.NewGuid();
Console.Clear();
Console.WriteLine();
Console.WriteLine("-------------------------------------");
Console.WriteLine("- Inserisci il Nome del Venditore : -");
Console.WriteLine("-------------------------------------");
v.NomeVenditore = Console.ReadLine();
Console.Clear();
Console.WriteLine();
Console.WriteLine("----------------------------------------");
Console.WriteLine("- Inserisci il Cognome del Venditore : -");
Console.WriteLine("----------------------------------------");
v.CognomeVenditore = Console.ReadLine();
Console.Clear();
Console.WriteLine();
Console.WriteLine("-----------------------------------------");
Console.WriteLine("- Inserisci il Telefono del Venditore : -");
Console.WriteLine("-----------------------------------------");
v.TelefonoVenditore = Console.ReadLine();
Console.Clear();
Console.WriteLine();
Console.WriteLine("-------------------------------------");
Console.WriteLine("- Inserisci la Mail del Venditore : -");
Console.WriteLine("-------------------------------------");
v.EmailVenditore = Console.ReadLine();
v.DateTime = DateTime.Now.ToString();
Liste.Venditori.Add(v);
Console.Clear();
Console.WriteLine("");
Console.WriteLine("---------------------------------------------------------------------------------------------------");
Console.WriteLine($"- Hai inserito il venditore {v.NomeVenditore} - {v.CognomeVenditore} - Avente GuId - {v.Id} - ");
Console.WriteLine($"- Il telefono è : {v.TelefonoVenditore} - La sua mail è : {v.EmailVenditore}");
Console.WriteLine($"- Il Venditore è attivo dal : {v.DateTime}");
Console.WriteLine("---------------------------------------------------------------------------------------------------");
Console.WriteLine("");
return v;
}
The problem are
Problem1 : When I start the method to list ( ElencoVenditori() ) all Vendors and relative proprieties, return to me only the last insert. I've tried to use Liste.Venditori.FindAll() but need to insert some paramether in FindAll and I don't know what I have to pass. Searched everywhere in web, first in Microsoft.Docs, but nothing ...
This is the code :
public static List<Venditori> ElencoVenditori()
{
// Eseguo un ForEach per ciclare dalla lista i miei dati. A differenza del While che cicla un condizionale
// e For che cicla una index, questo comando è dedicato alle liste.
// Associa alla variabile "item", tramite il comando "in", la lista venditori e mostra in console cosa contengono
foreach (var item in Liste.Venditori)
{
Console.Clear();
Console.WriteLine("");
Console.WriteLine($"I Venditori presenti in Lista sono : Nome - {item.NomeVenditore} | GuId - {item.Id}");
Console.WriteLine($" Telefono - {item.TelefonoVenditore} | Mail - {item.EmailVenditore}");
Console.WriteLine($" Venditore Aggiunto il - {item.DateTime}");
Console.WriteLine("");
Console.WriteLine("");
}
return Liste.Venditori;
}
Problem 2
I got another method ( VerificaListaVenditori() ), that should show me if one "Venditore" is present or not in the list, using as search index the name (NomeVenditore) or the surname (CognomeVenditore).
At the search using any index, i retrive and exception error:
Unhandled Exception: System.FormatException: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
at System.Text.StringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args)
at System.String.FormatHelper(IFormatProvider provider, String format, ParamsArray args)
at System.String.Format(String format, Object[] args)
at VenditaAutoConcessionarioConsole.Methods.VendorsMethods.VerificaListaVenditori() in C:\Users\Faggiano\source\repos\Progetti\ConcessionarioAuto\ConcessionarioAutoConsole\VenditaAutoConcessionarioConsole\Methods\VendorsMethods.cs:line 168
at VenditaAutoConcessionarioConsole.Methods.ProgramMethods.VendorSelect() in C:\Users\Faggiano\source\repos\Progetti\ConcessionarioAuto\ConcessionarioAutoConsole\VenditaAutoConcessionarioConsole\Methods\ProgramMethods.cs:line 70
at VenditaAutoConcessionarioConsole.Program.Main(String[] args) in C:\Users\Faggiano\source\repos\Progetti\ConcessionarioAuto\ConcessionarioAutoConsole\VenditaAutoConcessionarioConsole\Program.cs:line 53
Premere un tasto per continuare . . .
This is the code :
public static void VerificaListaVenditori()
{
string nomevenditore = "";
string cognomevenditore = "";
Console.Clear();
Console.WriteLine();
Console.WriteLine("----------------------------------------------------------------");
Console.WriteLine("- Inserisci il Nome od il Cognome del Venditore per la ricerca -");
Console.WriteLine("-------------- (Restituisce le Proprietà) ----------------------");
Console.WriteLine("----------------------------------------------------------------");
Console.WriteLine();
nomevenditore = Console.ReadLine();
cognomevenditore = Console.ReadLine();
string risultatoPositivo = "Il Venditore {0} è presente - Avente GuId {1} - " +
" Il Cognome è {2} - Il Telefono è {3} - La Mail è {4}" +
" E' attivo dal {5}";
string risultatoNegativoNome = $"Il Venditore ''{nomevenditore}'' non è presente nella Lista";
string risultatoNegativoCognome = $"Il Venditore ''{cognomevenditore}'' non è presente nella Lista ";
int index = -1;
for (int i = 0; i < Liste.Venditori.Count; i++)
{
if (nomevenditore == Liste.Venditori[i].NomeVenditore | cognomevenditore == Liste.Venditori[i].CognomeVenditore)
{
index = i;
//// Visualizza risultatoPositivo ed interrompe il ciclo
//Console.WriteLine(risultatoPositivo);
}
}
if (index >= 0)
{
Console.Clear();
Console.WriteLine("---------------------------------------------------------");
Console.WriteLine(String.Format(risultatoPositivo, Liste.Venditori[index].NomeVenditore, Liste.Venditori[index].Id, Liste.Venditori[index].CognomeVenditore, Liste.Venditori[index].TelefonoVenditore, Liste.Venditori[index].EmailVenditore));
Console.WriteLine("----------------------------------------------------------");
}
else
{
Console.WriteLine("---------------------------------------------------------");
Console.WriteLine(risultatoNegativoNome, risultatoNegativoCognome);
Console.WriteLine("---------------------------------------------------------");
}
}
The full code can be found on GitHub.
If the List.Venditori is accessed through the index then it must be 0 to List.Venditori.Count-1.
So your for loop must be
for (int i = 0; i < Liste.Venditori.Count; i++)
{
...
}
So I'm trying to create a dartgame in Console Application with C#.
This is as far as I have gotten atm:
class Program
{
static void Main(string[] args)
{
Game gameOn = new Game();
gameOn.PlayGame();
}
class Game
{
private List<Players> playerList = new List<Players>();
public void AddPlayers(string name)
{
Players names = new Players(name);
playerList.Add(names);
}
public void PlayGame()
{
Console.WriteLine("Välkommen till Dartspelet! Tryck valfri knapp för att fortsätta...");
Console.ReadLine();
Console.WriteLine("Skriv in antal spelare. Ni kommer också att möta en Dator.");
Console.WriteLine();
int players = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < players; i++)
{
Console.Write("Skriv in spelarens namn: ");
string playersNames = Console.ReadLine();
AddPlayers(playersNames);
}
Console.WriteLine();
Console.WriteLine("Spelet har börjat!");
Console.WriteLine();
foreach (Players name in playerList)
{
Console.WriteLine("Datorn börjar att kasta... Var god vänta...");
System.Threading.Thread.Sleep(2000);
Random rng = new Random();
int ranAttempt1 = rng.Next(0, 21);
int ranAttempt2 = rng.Next(0, 21);
int ranAttempt3 = rng.Next(0, 21);
Attempts result = new Attempts(ranAttempt1, ranAttempt2, ranAttempt3);
Console.WriteLine("Datorn Fick " + result.GetScore() + " på 3 kast.");
Console.ReadLine();
Console.WriteLine(name + "s Tur! ");
Console.WriteLine("Skriv in Poäng mellan 0-20 för kast 1:");
int attempt1 = Int32.Parse(Console.ReadLine());
Console.WriteLine("Skriv in Poäng mellan 0-20 för kast 2:");
int attempt2 = Int32.Parse(Console.ReadLine());
Console.WriteLine("Skriv in Poäng mellan 0-20 för kast 3:");
int attempt3 = Int32.Parse(Console.ReadLine());
Attempts result1 = new Attempts(attempt1, attempt2, attempt3);
Console.WriteLine(name + " Fick " + result1.GetScore());
}
Console.ReadLine();
}
}
class Attempts
{
private int attempt1;
private int attempt2;
private int attempt3;
public Attempts(int attempt1 = 0, int attempt2 = 0, int attempt3 = 0)
{
this.attempt1 = attempt1;
this.attempt2 = attempt2;
this.attempt3 = attempt3;
}
public int GetScore()
{
return attempt1 + attempt2 + attempt3;
}
}
class Players
{
private string Name { get; set; }
public List<Attempts> attempts = new List<Attempts>();
public Players(string name = "")
{
Name = name;
}
public override string ToString()
{
return Name;
}
}
}
I need help with creating a while loop around the foreach loop that will end when one of the players has reached a score of 301 or over. I also need a method to keep the score in a List or something like that for every turn. But yeah I'm stuck so any help is greatly appriciated! :)
And sorry if the code is a bit messy
Thanks in advance!
Well, you already have the List for the player's attempts. You could:
add a while loop around the foreach(Players...):
append the attempt after it's finished.
after a each player's attempts, calculate the total score.
print the score and exit if the total score > 301
while(true)
{
foreach(Players name in playerList)
{
// existing code here
// you should encapsulate attempts with getter and setter,
// but according to your Players class this will work.
name.attempts.add(result1);
// now sum up the total results for the player
// exercise for the reader.
int totalResults = player.getTotalScore();
if(totalResults > 301)
{
Console.WriteLine("Player " + name.getName() + " won the game!");
Environment.exit(0);
}
}
}
This is my code for some console app. First thing that doesn't work very well is method SwitchLetters. When I input some string and press enter every letter goes to new line. I don't know why. Also i don't know how to display lower and upper case in methods PrintBeforeSwitch and PrintAfterSwitch. And Exception how to use try and catch for some exception and which exception to use...
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please input string");
string input = Console.ReadLine();
NewString ns = new NewString();
StringOperation so = new StringOperation();
ns.SwitchLetters(input);
so.PrintBeforeSwitch(input);
so.PrintAfterSwitch(input);
}
}
class NewString
{
private string newString;
public string _NewString
{
get
{
return newString;
}
set
{
newString = value;
}
}
public void SwitchLetters(string newStr)
{
StringBuilder myString = new StringBuilder();
for (int i = 0; i < newStr.Length; i++)
{
if (char.IsUpper(newStr, i))
myString.Append(char.ToLower(newStr[i]));
else if (char.IsLower(newStr, i))
myString.Append(char.ToUpper(newStr[i]));
else
myString.Append(newStr[i]);
Console.WriteLine(myString.ToString());
Console.ReadLine();
Console.WriteLine(newStr.ToUpper());
}
}
}
class StringOperation
{
private string inputString;
//public NewString newSrt;
public string InputString
{
get
{
return inputString;
}
set
{
inputString = value;
}
}
public int VocalNumber(string str)
{
int num;
return num = str.Count(a => "aeiouAEIOU".Contains(a));
}
public int SpaceNumber(string str)
{
int num;
return num = str.Count(b => b == ' ');
}
public List<int> LowerUpperCaseLattersNumber(string str)
{
int counterLower = 0;
int counterUpper = 0;
List<int> counter = new List<int>();
foreach (char value in str)
{
if (char.IsLower(value))
{
counterLower++;
}
else
{
counterUpper++;
}
}
counter.Add(counterLower);
counter.Add(counterUpper);
Console.WriteLine("Number of small latters is: {0}", counterLower);
Console.WriteLine("Number of big letters is: {0}", counterUpper);
return counter;
}
public string SwitchVocals(ref string str)
{
string vocals = str.Replace("a", "x").Replace("e", "x").Replace("i", "x").Replace("o", "x").Replace("u", "x").Replace("A", "X").Replace("E", "X").Replace("I", "X").Replace("O", "X").Replace("U", "X");
Console.WriteLine(vocals);
return vocals;
}
public void PrintBeforeSwitch(string str)
{
Console.WriteLine(str);
Console.WriteLine("Information about string:");
Console.WriteLine("Number of vowels: {0}", VocalNumber(str));
Console.WriteLine("Number of space: {0}", SpaceNumber(str));
Console.WriteLine("Number of small latters is: {0}", LowerUpperCaseLattersNumber(str));
Console.WriteLine("Number of big letters is: {0}", LowerUpperCaseLattersNumber(str));
Console.ReadLine();
}
public void PrintAfterSwitch(string str)
{
SwitchVocals(ref str);
Console.WriteLine("Information about string after switch:");
Console.WriteLine("Number of vowels: {0}", VocalNumber(str));
Console.WriteLine("Number of space: {0}", SpaceNumber(str));
Console.WriteLine("Number of small latters is: {0}", LowerUpperCaseLattersNumber(str));
Console.WriteLine("Number of big letters is: {0}", LowerUpperCaseLattersNumber(str));
Console.ReadLine();
}
}
Here is an idea how to do the exception:
public void SwitchLetters(string newStr)
{
try
{
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadLine();//this stops the program so you can read the error
}
}
I think you had the two lines swapped around so.PrintBeforeSwitch and ns.SwitchLetters
static void Main(string[] args)
{
Console.WriteLine("Please input string");
string input = Console.ReadLine();
NewString ns = new NewString();
StringOperation so = new StringOperation();
so.PrintBeforeSwitch(input);
ns.SwitchLetters(input);
so.PrintAfterSwitch(input);
}
If you use Console.WriteLine("some string here"); it will do exactly as it says, write line. However you can use Console.Write("some string here"); and it should add the text/string onto the existing line.
Can you please give us more information by what you mean "First thing that doesn't work very well is method SwitchLetters..." what should it do? What does it currently do?
To resolve your issue in the comment below remove the Console.ReadLine()
public void SwitchLetters(string newStr)
{
StringBuilder myString = new StringBuilder();
for (int i = 0; i < newStr.Length; i++)
{
if (char.IsUpper(newStr, i))
myString.Append(char.ToLower(newStr[i]));
else if (char.IsLower(newStr, i))
myString.Append(char.ToUpper(newStr[i]));
else
myString.Append(newStr[i]);
Console.WriteLine(myString.ToString());
//Console.ReadLine(); This line needs to be removed
Console.WriteLine(newStr.ToUpper());
}
}