Sovi.AI - AI Math Tutor

Scan to solve math questions

QUESTION IMAGE

jump to level 1 declare constant double variable one_time_cost and cons…

Question

jump to level 1
declare constant double variable one_time_cost and constant integer variable cost_per_event, and initialize the variables as follows:

  • one_time_cost has value 197.00.
  • cost_per_event has value 35.

the program then reads integer numevents from input and calculates the total expense given the number of events, using one_time_cost and cost_per_event.

ex: if the input is 2, then the output is:

2 events = 267.00 dollars

1 import java.util.scanner;
2
3 public class totalexpense {
4 public static void main(string args) {
5 scanner scnr = new scanner(system.in);
6
7 / your code goes here /
8
9 int numevents;
10 double totalexpense;
11
12 numevents = scnr.nextint();
13
14 totalexpense = (numevents * cost_per_event) + one_time_cost;
15 }
}

Explanation:

Step1: Declare constants in Java

In Java, we use the final keyword to declare constants. For ONE_TIME_COST (a double), and COST_PER_EVENT (an int), we can write the following code within the main method before reading numEvents.

final double ONE_TIME_COST = 197.00;
final int COST_PER_EVENT = 35;

Step2: Complete the Java program

The full Java program with the constant declarations added at the appropriate place (before line 9 in the given code - where numEvents is declared) would be:

import java.util.Scanner;

public class TotalExpense {
    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);
        final double ONE_TIME_COST = 197.00;
        final int COST_PER_EVENT = 35;
        int numEvents;
        double totalExpense;
        numEvents = scnr.nextInt();
        totalExpense = (numEvents * COST_PER_EVENT) + ONE_TIME_COST;
        System.out.println(numEvents + " events = " + String.format("%.2f", totalExpense) + " dollars");
    }
}

The added line at the end (System.out.println...) is to print the result in the format shown in the example (with two - decimal places for the total expense).

Answer:

import java.util.Scanner;

public class TotalExpense {
    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);
        final double ONE_TIME_COST = 197.00;
        final int COST_PER_EVENT = 35;
        int numEvents;
        double totalExpense;
        numEvents = scnr.nextInt();
        totalExpense = (numEvents * COST_PER_EVENT) + ONE_TIME_COST;
        System.out.println(numEvents + " events = " + String.format("%.2f", totalExpense) + " dollars");
    }
}