Write a program named ChatAWhile that stores the area codes and rates in parallel arrays and allows a user to enter an area code and the length of time for a call in minutes, and then display the total cost of the call.

Respuesta :

Answer:

  1. import java.util.Scanner;
  2. public class Main {
  3.    public static void main(String[] args)
  4.    {
  5.        int areaCode[] = {121, 122, 123, 124, 125};
  6.        double rates [] = {0.2, 0.3, 0.35, 0.15, 0.25};
  7.        Scanner input = new Scanner(System.in);
  8.        System.out.print("Enter area code: ");
  9.        int a = input.nextInt();
  10.        System.out.print("Enter calling time: ");
  11.        int time = input.nextInt();
  12.        double cost = 0;
  13.        for(int i=0; i < areaCode.length; i++){
  14.            if(areaCode[i] == a){
  15.                cost = rates[i] * time;
  16.            }
  17.        }
  18.        System.out.println("Total cost of the call: $" + cost);
  19.    }
  20. }

Explanation:

The solution code is written in Java.

Firstly create two parallel arrays for area code and calling rate (Line 7-8). Presume the rate is based on call per minute.

Next, user Scanner object to prompt user to input area code and calling time (Line 10 - 14).

Create a for loop to identify the index where the input area code can be found in the array  and then calculate the cost by using the same index i to get the corresponding rate (Line 17 - 20).

Print the cost to console (Line 22).