I'm writing a program that can calculate the call charge made by its customers. It requires us to define and call a method which can calculate and return the call charge.
I have a bit of an error in the output: the total charge isn't detected. Is there something wrong while in the main method or the formula method that I created?
import java.util.Scanner;
public class Asg22 {
static double formula(double rate) {
double charge =+ rate;
return charge;
}
public static void main(String[] args) {
//variables
int total = 0;
int n;
int choice = 0;
int i = 0;
double sum = 0;
int min = 0;
int cat = 0;
String data = "";
double rate = 0;
double charge=0;
//scanner
Scanner scan = new Scanner(System.in);
do{
do{System.out.println("Enter the call duration (in minutes): ");
min = scan.nextInt();
System.out.println("Enter category (1.Daytime, 2.Evening, 3.Off-peak): ");
cat = scan.nextInt();
if (cat == 1) {
rate = min * 0.07;
formula(rate);
} else if (cat == 2) {
rate = min * 0.12;
formula(rate);
} else if (cat == 3) {
rate = min * 0.05;
formula(rate);
} else {
System.out.println("The number you've inserted is Invalid.");
}}while(cat !=1 && cat !=2 && cat !=3);
charge = formula(rate);
System.out.printf("The amount you have to pay is = RM%.2f", rate);
System.out.println("\nDo you want to continue? 1.Yes 2.No ");
choice = scan.nextInt();
i++;
} while(choice == 1);
System.out.println("Total Customer: "+i);
charge += rate;
System.out.printf("Total Charge: RM%.2f", charge);}
}
Output:
Enter the call duration (in minutes):
22
Enter category (1.Daytime, 2.Evening, 3.Off-peak):
1
The amount you have to pay is = RM1.54
Do you want to continue? 1.Yes 2.No
1
Enter the call duration (in minutes):
56
Enter category (1.Daytime, 2.Evening, 3.Off-peak):
2
The amount you have to pay is = RM6.72
Do you want to continue? 1.Yes 2.No
1
Enter the call duration (in minutes):
22
Enter category (1.Daytime, 2.Evening, 3.Off-peak):
4
The number you've inserted is Invalid.
Enter the call duration (in minutes):
13
Enter category (1.Daytime, 2.Evening, 3.Off-peak):
3
The amount you have to pay is = RM0.65
Do you want to continue? 1.Yes 2.No
2
Total Customer: 3
Total Charge: RM1.30
There are multiple problems with this code:
=+
- this are 2 separate operators, it is interpreted as double charge = +rate;
where the +
is the Unary Plus Operator + .
main
.Minimal change to make it work (though this is not necessarily the best solution):
static double charge = 0;
static double formula(double rate) {
charge += rate;
return charge;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.