From 3b97a76af4eb3e998de18acd2a7d1bad793a8b35 Mon Sep 17 00:00:00 2001 From: Sven-Erik Jonsson Date: Fri, 28 Aug 2020 13:08:23 +0200 Subject: [PATCH] Progress on number app. --- .../Session03/Session03Excercise02/Program.cs | 87 ++++++++++++++++++- 1 file changed, 84 insertions(+), 3 deletions(-) diff --git a/Session03/Session03/Session03Excercise02/Program.cs b/Session03/Session03/Session03Excercise02/Program.cs index 50a66f8..091b827 100644 --- a/Session03/Session03/Session03Excercise02/Program.cs +++ b/Session03/Session03/Session03Excercise02/Program.cs @@ -1,4 +1,6 @@ using System; +using System.Diagnostics; +using System.Globalization; namespace Session03Excercise02 { @@ -8,13 +10,92 @@ static void Main(string[] args) { Console.WriteLine("Ange ett antal siffror, separerat med kommatecken."); var input = Console.ReadLine(); - var inputArray = input.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries); + var inputArray = input.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + double?[] numberArray = new double?[inputArray.Length]; - foreach (var number in inputArray) + //for (int i = 0; i < inputArray.Length; i++) + //{ + // try + // { + // numberArray[i] = Convert.ToDouble(inputArray[i]); + // } + // catch (Exception) + // { + // numberArray[i] = 0; + // } + //} + + for (int i = 0; i < inputArray.Length; i++) + { + NumberStyles numberStyle = NumberStyles.Integer | NumberStyles.Float; + IFormatProvider formatProvider = CultureInfo.InvariantCulture; + + bool parsed = double.TryParse(inputArray[i], numberStyle, formatProvider, out double parsedValue); + + if (parsed == true) + { + numberArray[i] = parsedValue; + } + else + { + numberArray[i] = null; + } + + //numberArray[i] = GetDoubleValue(inputArray[i]); + } + + //foreach (var number in numberArray) + //{ + // Console.WriteLine("Värde: " + number.ToString()); + //} + + //int exceptionStatus = GetExceptionStatus(); + + } + + // Metod som returnerar en siffra baserat på en sträng + static double GetDoubleValue(string input) + { + try + { + var result = int.Parse(input); + + return result; + } + catch (FormatException ex) when (ex.Message.Contains("Input string")) + { + return double.MinValue; + } + catch (Exception ex) + { + return 0; + } + + } + + // Metod som returnerar ett heltal, saknar inparameter + static int GetExceptionStatus() + { + int exceptionResult; + + try { - Console.WriteLine("Värdet är " + number); + exceptionResult = -1; + + throw new Exception("Provocerat fel"); + + return exceptionResult; } + catch (Exception ex) + { + exceptionResult = ex.HResult; + return exceptionResult; + } + finally + { + exceptionResult = int.MaxValue; + } } } }