extract to method

This commit is contained in:
Geir Okkenhaug Jerstad 2024-12-02 13:45:57 +01:00
parent 4879b3bd6f
commit e1720b362f
2 changed files with 30 additions and 12 deletions

View file

@ -1,6 +1,7 @@
 
var numbers = new int[100]; using Innkapsling;
var numberCount = 0;
var stats = new Stats();
while (true) while (true)
{ {
Console.WriteLine("Skriv et tall (eller blankt for å avslutte: "); Console.WriteLine("Skriv et tall (eller blankt for å avslutte: ");
@ -8,13 +9,7 @@ while (true)
if (string.IsNullOrWhiteSpace(numberStr)) break; if (string.IsNullOrWhiteSpace(numberStr)) break;
var number = Convert.ToInt32(numberStr); var number = Convert.ToInt32(numberStr);
numbers[numberCount] = number; stats.AddNumber(number);
numberCount++; stats.Show();
var sum = numbers.Sum();
Console.Clear();
Console.WriteLine(
$"Antall tall: {numberCount} " +
$"Sum: {sum} " +
$"Snitt: {(float)sum / numberCount}"
);
} }

View file

@ -2,5 +2,28 @@ namespace Innkapsling;
public class Stats 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}"
);
}
} }