Click here to Skip to main content
15,889,833 members
Please Sign up or sign in to vote.
2.00/5 (2 votes)
See more:
I can get this program to give me an answer but it is the incorrect answer. It's supposed to calculate the cost of a phone call to a certain area code. Any help would be appreciated. This is my first attempt at writing an array.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SmithMichaelChatAWhile.cs
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] areaCodes = { 262, 414, 608, 715, 815, 920 };
            double[] ratesPerMinute = { 0.07, 0.10, 0.05, 0.16, 0.24, 0.14 };

            int areaCode;

            double cost = 0;
            double minutes;

            Console.WriteLine("Please enter an area code ");
            Console.WriteLine("choose between: 262, 414, 608, 715, 815, 920 ");
            areaCode = Convert.ToInt32(Console.ReadLine());
            Console.Write("Please enter number of minutes ");
            minutes = Convert.ToDouble(Console.ReadLine());

            cost = Convert.ToDouble(cost);
            cost = ratesPerMinute [0] ;
            Console.WriteLine("The cost for this call will be " + cost * minutes);
            }
        
    }
}
Posted

1 solution

You always take the first element from the array, hence the selected area code will actually always be 262, whatever you input.

Use Array.IndexOf to find the index of the entered area code and then use that index to get the rates per minute. If the user inputted an area code that's not in the list, IndexOf will return -1.
C#
int index = Array.IndexOf(areaCodes, areaCode);
if (index == -1)
{
    Console.WriteLine("Invalid area code.");
    return; // terminate execution of the Main method
}
cost = ratesPerMinute[index];
 
Share this answer
 
Comments
Member 11403574 20-Feb-15 12:06pm    
That works! Thanks so much!
Thomas Daniels 20-Feb-15 12:12pm    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900