Problem med program som lägger till varor och sorterar varor i shoppinglista
Hej! Jag har lite problem med mitt program. Det är menybaserat och i det kan man lägga till varor som man sedan skriver ut som ett "kvitto", antingen med en metod som sorterar per pris eller en annan som sorterar per namn.
Jag har problem med metoden som sorterar varorna per namn i kvittot. När jag kör koden får jag NullReference. Men det får jag inte om jag ska jämföra priserna. Och jag förstår bara inte varför just articles[i].Name blir null i den ena metoden men inte i den andra?
Här är metoden som sorterar per pris:
int countReceipt = 0;
Article temp; // Article är en struct
for (int i = 0; i < articles.Length - 1; i++) // articles är en array av Article
{
for (int j = i + 1; j < articles.Length; j++)
{
if (articles[i].Price < articles[j].Price)
{
temp = articles[i];
articles[i] = articles[j];
articles[j] = temp;
}
}
// check if article price is not 0
if (articles[i].Price != 0)
{
countArticles++;
Console.WriteLine($"{countReceipt,-2} {articles[i].Name,-10} {articles[i].Price:C}");
}
}
Här är koden jag har problem med som skall sortera varorna efter namn:
int countArticles = 0;
decimal totalPrice = 0;
// counter for the number of articles bought
for (int i = 0; i < nrArticles; i++)
{
if (articles[i].Name != string.Empty && articles[i].Price != 0)
{
countArticles++;
}
}
// checks if shopping list contains any articles
if (countArticles > 0)
{
Console.WriteLine("\n\t==YOUR RECEIPT==");
Console.WriteLine($"\nDate of purchase: {DateTime.Now}");
Console.WriteLine($"\nNumber of items purchased: {countArticles}");
Console.WriteLine($"\n{"#",-2} {"Name",-10} {"Price"}");
// add the prices of the items in the array together
foreach (var item in articles)
{
totalPrice += item.Price;
}
// counter for the number of objects in the receipt
int countReceipt = 0;
for (int i = 0; i < articles.Length - 1; i++)
{
Article temp;
for (int j = i + 1; j < articles.Length; j++)
{
// compare elements content, articles[] null. why?
if (articles[i].Name.CompareTo(articles[j].Name) > 0) // HÄR får jag error NullReference: Object reference not set to an instance.... articles[] was null.
{
temp = articles[j];
articles[j] = articles[i];
articles[i] = temp;
}
}
// check if article name is not empty
if (articles[i].Name != string.Empty)
{
countReceipt++;
Console.WriteLine($"{countReceipt,-2} {articles[i].Name,-10} {articles[i].Price:C}");
}
}
Är articles.length storleken på en array och nrArticles hur många som faktiskt används? Då är det väl alltid nrArticles du ska loopa till? De som inte används lär ha Name osatta, alltså null. Priset är inte heller satt, men då är det ändå nåt tal, kanske 0, kanske nåt annat, så jämförelsen fungerar ändå, fast den är meningslös.