From e1720b362f61284f9e5dcc7703036c6378d0b71b Mon Sep 17 00:00:00 2001 From: Geir Okkenhaug Jerstad Date: Mon, 2 Dec 2024 13:45:57 +0100 Subject: [PATCH] extract to method --- Emne 3/Innkapsling/Innkapsling/Program.cs | 17 ++++++--------- Emne 3/Innkapsling/Innkapsling/Stats.cs | 25 ++++++++++++++++++++++- 2 files changed, 30 insertions(+), 12 deletions(-) diff --git a/Emne 3/Innkapsling/Innkapsling/Program.cs b/Emne 3/Innkapsling/Innkapsling/Program.cs index 4403cd1..495de0d 100644 --- a/Emne 3/Innkapsling/Innkapsling/Program.cs +++ b/Emne 3/Innkapsling/Innkapsling/Program.cs @@ -1,6 +1,7 @@  -var numbers = new int[100]; -var numberCount = 0; +using Innkapsling; + +var stats = new Stats(); while (true) { Console.WriteLine("Skriv et tall (eller blankt for å avslutte: "); @@ -8,13 +9,7 @@ while (true) if (string.IsNullOrWhiteSpace(numberStr)) break; var number = Convert.ToInt32(numberStr); - numbers[numberCount] = number; - numberCount++; - var sum = numbers.Sum(); - Console.Clear(); - Console.WriteLine( - $"Antall tall: {numberCount} " + - $"Sum: {sum} " + - $"Snitt: {(float)sum / numberCount}" - ); + stats.AddNumber(number); + stats.Show(); + } \ No newline at end of file diff --git a/Emne 3/Innkapsling/Innkapsling/Stats.cs b/Emne 3/Innkapsling/Innkapsling/Stats.cs index 8e4493c..c0a8aff 100644 --- a/Emne 3/Innkapsling/Innkapsling/Stats.cs +++ b/Emne 3/Innkapsling/Innkapsling/Stats.cs @@ -2,5 +2,28 @@ namespace Innkapsling; public class Stats { - + private int[] _numbers; + private int _numberCount; + + public Stats() + { + _numbers = new int[10]; + } + + public void AddNumber(int number) + { + _numbers[_numberCount] = number; + _numberCount++; + } + + public void Show() + { + var sum = _numbers.Sum(); + Console.Clear(); + Console.WriteLine( + $"Antall tall: {_numberCount} " + + $"Sum: {sum} " + + $"Snitt: {(float)sum / _numberCount}" + ); + } } \ No newline at end of file