How to add exception for errors(try, catch) - c#

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());
}
}

Related

C# convert XML Node string to Int32

I reading data from webservice and is not clean. I need to convert string to Int where string can be null, number or with white spaces. I make simple program to achieve this but with whitespaces my code does not hit ... If (uint.TryParse(cleanNumber, out ux)) not sure what I am missing from puzzle?
public class Program
{
static void Main(string[] args)
{
string no = "08709079777 ";
//string no = "0870777777";
Console.WriteLine("no "+ no);
Program o = new Program();
var t1 = o.ConvertStringToInt32(no);
Console.WriteLine("t1 "+ t1);
Console.ReadLine();
}
private int ConvertStringToInt32(string number)
{
int returnIntVal = 0;
try
{
if (!string.IsNullOrEmpty(number))
{
var cleanNumber = Regex.Replace(number, #"\s+", "");
uint ux;
if (uint.TryParse(cleanNumber, out ux))
{
returnIntVal = (int)ux;
}
}
else
{
returnIntVal = 0;
}
}
catch(Exception exp)
{
var ex = exp;
}
return returnIntVal;
}
}
The number 0870777777 you are trying to parse is beyond int data type range which is -2,147,483,648 to 2,147,483,647. Check the data type ranges at here.
Use the data type as long (or Int64).
private static long ConvertStringToInt32(string number)
{
long returnIntVal = 0;
try
{
if (!string.IsNullOrEmpty(number))
{
var cleanNumber = Regex.Replace(number, #"\s+", "");
if (long.TryParse(cleanNumber, out long ux))
{
returnIntVal = ux;
}
}
else
{
returnIntVal = 0;
}
}
catch(Exception exp)
{
var ex = exp;
}
Console.WriteLine("returnIntVal: " + returnIntVal);
return returnIntVal;
}
Check this fiddle - https://dotnetfiddle.net/3Luoon
Well i dont know why you complicate things but this should be really very easy to solve
public int ConvertToInt(string n) {
// Trim should solve your case where the number end or start with whitespace. but just
// incase i did the replace thing to if there is any whitespace between the numbers.
// So its upp to you if you want to retaine the replace or not.
n = n?.Replace(" ", "").Trim();
if (Int.TryParse(n, var out number))
return number;
else return 0;
}

do-while loop does not go through while condition C#

I wrote a do-while loop but it does not run through while condition somehow.
When I type in invalid characters it should go back to beginning and repeat as it's supposed to.
I ran the code step by step on Visual Studio and it shows that code does not even go through while condition. (no matter what the input value is)
Can someone please help me?
Many thanks in advance!
using System;
using static System.Console;
namespace a5
{
class Program
{
const string acceptedLetters = "EHLNTXZ";
static void Main(string[] args)
{
GetUserString(acceptedLetters);
ReadKey();
}
static string GetUserString(string letters)
{
string invalidCharacters;
do
{
invalidCharacters = null;
Write("Enter : ");
string inputCharacters = ReadLine();
foreach(char c in inputCharacters)
{
if(letters.IndexOf(char.ToUpper(c))==-1)
{
invalidCharacters = c.ToString();
}
}
if(invalidCharacters != null)
{
WriteLine("Enter a valid input");
}
return inputCharacters;
} while (invalidCharacters != null);
}
}
}
The problem is that you return the inputed string at the end of the loop no matter the validation done.
You can use a boolean to check this validity.
Also you don't need to parse all the string and you can break the inner loop on the first invalid char.
I renamed the string as result to use a standard pattern and to be more clean.
For example:
static string GetUserString(string letters)
{
string result;
bool isValid;
do
{
Console.Write("Enter : ");
result = Console.ReadLine();
isValid = true;
foreach ( char c in result )
if ( letters.IndexOf(char.ToUpper(c)) == -1 )
{
isValid = false;
Console.WriteLine("Enter a valid input");
break;
}
}
while ( !isValid );
return result;
}
The line return inputCharacters; makes it leave the loop.
I think you meant:
} while (invalidCharacters != null);
return inputCharacters;
using System;
using static System.Console;
namespace a5
{
class Program
{
const string acceptedLetters = "EHLNTXZ";
static void Main(string[] args)
{
GetUserString(acceptedLetters);
ReadKey();
}
static string GetUserString(string letters)
{
string invalidCharacters;
do
{
invalidCharacters = null;
Write("Enter : ");
string inputCharacters = ReadLine();
foreach(char c in inputCharacters)
{
if(letters.IndexOf(char.ToUpper(c))== -1)
{
invalidCharacters = c.ToString();
}
}
if(invalidCharacters != null)
{
WriteLine("Enter a valid input");
}
} while (invalidCharacters != null);
return inputCharacters;
}
}
}

method: color console string with parameter object[] prms

I cannot create a function myself that takes the a text with params object[] and colourizes it.
protected void ColorToConsole(ConsoleColor c, string s, params object[] p) {
Console.ForegroundColor = c;
Console.Write(string.Format(s, p));
}
I would like to call the function like this: ColorToConsole(ConsoleColor.Blue, "I like {0}", p. I expect only the p to be colored in blue. I'm trying to get another method where I can provide multiple Colors for the different p but i'm stuck here.
UPDATE 4
Here is code that you wants, it's parsing given value,finding places where to put colorized text and doing it.
using System;
using System.Linq;
using System.Text.RegularExpressions;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello {{1}} {0}", "Henry");
WriteLine(ConsoleColor.Red, "Hello {0},{2} {1} asd {1} {0} {2}", "Name1", "Name2", "Name3");
WriteLine(ConsoleColor.Red, "Hello {{1}} {0}", "Henry");
Console.WriteLine("Hello {{1}} {0}", "Henry","David");
WriteLine(ConsoleColor.Green,"Hello {{1}} {0}", "Henry", "David");
try
{
Console.WriteLine("Hello {{1}} {1} {0}", "Henry");
}
catch(Exception exc)
{
Console.WriteLine(exc.Message);
}
try
{
WriteLine(ConsoleColor.Red, "Hello {{1}} {1} {0}", "Henry");
}
catch (Exception exc)
{
Console.WriteLine(exc.Message);
}
}
public static void WriteLine(ConsoleColor c, string value, params object[] prms)
{
var regEx = new Regex("{[0-9]+}");
var matches = regEx.Matches(value);
int i = 0;
int newLenght = (value.Length - 3 * (prms.Length) + (int)prms.Sum(x => ((string)x).Length));
var valueArr = value.ToCharArray();
foreach (Match m in matches)
{
while (i < m.Index && i < valueArr.Length)
{
Console.Write(valueArr[i]);
i++;
}
if (valueArr[i].Equals('{') && i+m.Value.Length< valueArr.Length && valueArr[i + m.Value.Length].Equals('}'))
{
i += m.Value.Length;
Console.Write(m.Value.Trim('{', '}'));
}
else if (int.Parse(m.Value.Trim('{', '}')) < prms.Length)
{
i += m.Value.Length;
Console.ForegroundColor = c;
Console.Write(prms[int.Parse(m.Value.Trim('{', '}'))]);
Console.ResetColor();
}
else
{
throw new Exception("Index must be greater than or equal to zero and less than the size of the argument list.");
}
}
while (i < valueArr.Length)
{
Console.Write(valueArr[i]);
i++;
}
Console.WriteLine();
}
}
}
And the output will be the following:
I do not think, string.Format has that capability what you are expecting.
But you can customize the function by using sub strings.
I tried the below function, And it is doing good.
I see the output similar to your expectation. Look into comments in below code. A sample just for string input. For object array scroll down a bit for second piece of code.
public void ColorToConsole(ConsoleColor c, string s, string p)
{
//GET THE SUBSTRING TILL {0} AND WRITE IT TO CONSOLE
string substr = s.Substring(0,s.IndexOf("{0}"));
Console.Write(substr);
//NOW SET THE FORE GROUND COLOR. WRITE THE REST
Console.ForegroundColor = c;
Console.Write(p);
}
If you want each of your p elements in different colors, you can try the below code.
Console.ForegroundColor = ConsoleColor.Blue;
Console.Write(p[0]);
//RESET THE COLOR.
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Red;
Console.Write(p[1]);

English to Pig Latin C# Console Application

I'm having some trouble making an applicaton in c# converting english to pig latin. I have everything else down except for when it comes to making the getTranslation method for it. For some odd reason I just can't figure it out. IF someone could give me some ideas I would appreciate it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace W15M5A2_CPigLatinApp
{
class W15M5A2_CPigLatinAppProgram
{
static void Main(string[] args)
{
string inputPhrase = "";
string[] phraseOut;
DisplayInfo();
inputPhrase = GetPhrase();
while (inputPhrase != "")
{
Console.WriteLine(" ");
phraseOut = GetTranslation(inputPhrase);
DisplayResults(inputPhrase, phraseOut);
inputPhrase = GetPhrase();
}
Console.ReadKey();
}
public static void DisplayInfo()
{
Console.WriteLine("********************************************************" +
"\n*** You will be prompted to enter a string of ***" +
"\n*** words. The phrase will be converted into a ***" +
"\n*** pseudo Pig Latin with results displayed. ***" +
"\n\n*** Enter as many strings as you would like. ***" +
"\n********************************************************\n\n");
Console.Write("\n\n\n Press any key when you are ready to begin...");
Console.ReadKey();
Console.Clear();
}
public static string GetPhrase()
{
string inputPhrase;
Console.WriteLine("Enter a phrase or group of words " +
"\nTo Exit, press the Enter key\n");
inputPhrase = Console.ReadLine();
return inputPhrase;
}
// GetTranslation method
public static string[] GetTranslation(string phraseIn)
{
}
public static void DisplayResults(string input, string[] output)
{
Console.Clear();
Console.WriteLine("Original Phrase: " + input + "\n");
Console.Write("\nNew Phrase: ");
foreach (string i in output)
{
Console.Write(i + " ");
}
Console.WriteLine("\n");
}
}
}
public static string[] GetTranslation(string phraseIn)
{
string vow = "aeiouyAEIOUY";
var splitted = phraseIn.Split(new[] {" "}, StringSplitOptions.None);
List< string> ret = new List<string>();
foreach (string split in splitted)
{
string vows = string.Empty;
string cons = string.Empty;
for (var i = 0; i < split.Length; i++)
{
char ch = split[i];
if (vow.Contains(ch))
{
vows += ch;
}
else
{
cons += ch;
}
}
ret.Add(cons + vows + "ay");
}
return ret.ToArray();
}
This is a (little bit hacky) solution. I tested it with the examples from Wiki.
public static string ToPigLatin(string word)
{
string result = string.Empty;
string pigSuffixVowelFirst = "yay";
string pigSuffixConstanantsFirst = "ay";
string vowels = "aeiouAEIOU";
if(vowels.Contains(word.First()))
{
result = word + pigSuffixVowelFirst;
}
else
{
int count = 0;
string end = string.Empty;
foreach(char c in word)
{
if (!vowels.Contains(c))
{
end += c;
count++;
}
else
{
break;
}
}
result = word.Substring(count) + end + pigSuffixConstanantsFirst;
}
return result;
}
Use at your own peril :)

Random is not working good

I generate a string with 62 options ^ 6 letters = 56,800,235,584
But when running the code, it repeats the same string less then every 200,200 times
What is the problem here?
BTW:
This code is based on the answer here
class Program
{
static void Main(string[] args)
{
var d = new Dictionary<string, bool>();
for (int i = 0; ; i++)
{
var s = GenerateString(6);
try
{
d.Add(s, false);
}
catch (Exception ex)
{
Console.WriteLine(String.Format("{0} - {1} - {2}", i, s, ex.Message));
i = 0;
}
}
Console.ReadKey();
}
static Random _rnd = new Random();
public static string GenerateString(int len)
{
const string bigLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const string smallLetters = "abcdefghijklmnopqrstuvwxyz";
const string numbers = "1234567890";
var validChars = bigLetters + smallLetters + numbers;
var result = new StringBuilder();
for (int i = 0; i < len; i++)
{
result.Append(validChars[_rnd.Next(validChars.Length)]);
}
return result.ToString();
}
}
There is all OK with random.
The problem is related with Birthday paradox. When you have 200k items one of them could repeat.
Random string doesnt garantee always unique result. For unique results you should use GUID's.
To avoid repeatation you can do a check for existence before adding the string to the list:
After for loop in GenerateString()
if(d.Contains(result.ToString()) // check whether the current generated string is in the list
{
GenerateString(len); // if it is already existed generate another one
}
else
{
return result.ToString(); // if not then return the string
}

Categories

Resources