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

View file

@ -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}"
);
}
}