We are required to complete a simple ticketing system for a local cinema in netbeans and I'm stumped on two problems.
Problem 1 is as part of the output, is once you have selected ticket type + quantity, there needs to be an output "you are purchasing X number of tickets at Y quantity"
Problem 2 is the seniors ticket needs to be at a cost of $32.50 and I cannot seem to find a workaround for allowing a calculation to be made using a decimal figure. I debugged and it seemed to change the number to an integer, which then would not calculate correctly. Help!
package ticketingsystem;
import java.io.*;
public class ticketingsystem
{
public static void main(String []args) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String order,again;
int quantity,price1=0,price2=0, price3=0,loop1=0,quantity1,quantity2=0;
System.out.println(" ");
System.out.println("Welcome to the cinemas!");
System.out.println(" ");
System.out.println("MAIN MENU");
System.out.println(" ");
System.out.println("The cinema has the following options");
System.out.println(" ");
System.out.println("1 = Child (4-5 yrs)");
System.out.println("2 = Adult (18+ yrs)");
System.out.println("3 = Senior (60+ yrs)");
do{
System.out.println(" ");
System.out.print("Enter your option: ");
order=br.readLine();
if (order.equalsIgnoreCase("1")) {
price1=18;
} else if (order.equalsIgnoreCase("2")) {
price1=36;
}
else if (order.equalsIgnoreCase("3")) {
price1= (int) 32.5;
}
System.out.print("Enter the number of tickets: ");
quantity1= Integer.parseInt(br.readLine());
quantity2=quantity1+quantity2;
price2=price1*quantity2;
System.out.println("You are purchasing " int (order=br) " tickets at" (quantity1);
System.out.print("Do you wish to continue? (Y/N) : ");
again=br.readLine();
if (again.equalsIgnoreCase("y"))
loop1=loop1+1;
else loop1=loop1-100;
} while (loop1==1);
System.out.println(" ");
System.out.println("Total Price : "+price2);
}
}
Hi would suggest to make the following changes.
First rename price2 to totalPrice and change it to a double:
double totalPrice;
I would create an enum class for TicketType, where you can also assign the price1 value:
enum TicketType {
child(18), adult(36), senior(32.5);
TicketType(double price) {
this.price = price;
}
private double price;
public double getPrice() {
return price;
}
}
You can now change you main method to this:
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String order, again;
int quantity = 0;
double totalPrice;
TicketType ticketType; // add the enum to the method
System.out.println(" ");
System.out.println("Welcome to the cinemas!");
System.out.println(" ");
System.out.println("MAIN MENU");
System.out.println(" ");
System.out.println("The cinema has the following options");
System.out.println(" ");
System.out.println("1 = Child (4-5 yrs)");
System.out.println("2 = Adult (18+ yrs)");
System.out.println("3 = Senior (60+ yrs)");
do {
System.out.println(" ");
System.out.print("Enter your option: ");
order = br.readLine();
//use a switch case instead of the if else pattern
switch (order.toLowerCase()) {
case "1":
ticketType = TicketType.child;
break;
case "3":
ticketType = TicketType.senior;
break;
default:
ticketType = TicketType.adult;
break;
}
System.out.print("Enter the number of tickets: ");
quantity = Integer.parseInt(br.readLine());
totalPrice += ticketType.getPrice() * quantity;
// %s will be replaced with the string value of ticketType, %.2f means it will be replaced with a decimal, round to decimals
System.out.printf("You are purchasing %s tickets at %.2f \n", ticketType, ticketType.getPrice());
System.out.print("Do you wish to continue? (Y/N) : ");
again = br.readLine();
}
while (again.equalsIgnoreCase("y"));
System.out.println(" ");
System.out.printf("Total Price : $%.2f \n", totalPrice);
}
You can use the System.out.printf() to format messages you print to the console
On the price1 value, you are losing some precision by storing it as an int.
In Java, the int is rounded (to floor) to values without the decimal point precision. For this purpose, you'll want to use float or double to retain your cent value.
Also, you may find the java.text.NumberFormat class useful for the Currency handling.
Related
import java.util.Scanner;
public class Asgn1 {
//comment practice
/*multi-line comment practice
* no text fill
*/
public static void main(String[] args) {
//user prompted inputs for future calculations
Scanner in = new Scanner(System.in);
System.out.println("The following information is required:");
System.out.println("Enter customer ID: ");
String customerId = in.nextLine();
System.out.println("Enter unit price in decimal format (up to two decimals, e.g. 3.5): ");
String unitPrice = in.nextLine();
System.out.println("Enter quantity (whole numbers only): ");
String orderQuantity = in.nextLine();
System.out.println("Enter product description, (e.g. 'whole wheat bread'): ");
String productDescription = in.nextLine();
System.out.println("Enter discount in decimal format (e.g. .05 = 5%): ");
String appliedDiscount = in.nextLine();
//confirm order data details and display to user
System.out.println("Your order data is as follows: ");
System.out.println("Customer ID: " + customerId);
System.out.println("Unit Price: " + unitPrice);
System.out.println("Order Quantity: " + orderQuantity );
System.out.println("Product Description: " + productDescription);
System.out.println("Applied Discount: " + appliedDiscount);
//calculation formulas based on users input
int beforeDiscount = (Integer.parseInt(unitPrice) * Integer.parseInt(orderQuantity));
int afterDiscount = 1 - (Integer.parseInt(unitPrice) * Integer.parseInt(orderQuantity)) * (appliedDiscount);
//totals before and after discount
System.out.println("Your Order Totals");
System.out.println("Before Discount: ");
System.out.println("After Discount: ");
}
}
I have this java code I want to take the unit price and multiply that by the order quantity, then apply the discount so I can display a before and after discount price.
Originally, when I entered this, I figured out I had to parse the strings for unitPrice and orderQuantity as ints, but when I tried that with the double, I got this message as well on the same line: "Type mismatch: cannot convert from double to int".
I tried looking around at other answers but could not find something that would fix this issue so I'm asking for help, please. What would be the best way to solve this?
In the future, should I try to alter it before it comes in, maybe where they input it, or do I wait until I get the values and then alter that? What would convention dictate?
Thank you for your consideration and assistance.
I change some things on the code... first, the type of variables of unit price and appliedDiscount into double. And also I change the formula to calculate price after discount.
public static void main(String[] args) {
//user prompted inputs for future calculations
Scanner in = new Scanner(System.in);
Scanner in2 = new Scanner(System.in);
System.out.println("The following information is required:");
System.out.println("Enter customer ID: ");
String customerId = in.nextLine();
System.out.println("Enter unit price in decimal format (up to two decimals, e.g. 3.5): ");
double unitPrice = in.nextDouble();
System.out.println("Enter quantity (whole numbers only): ");
int orderQuantity = in.nextInt();
System.out.println("Enter product description, (e.g. 'whole wheat bread'): ");
String productDescription = in2.nextLine();
System.out.println("Enter discount in decimal format (e.g. .05 = 5%): ");
double appliedDiscount = in.nextDouble();
//confirm order data details and display to user
System.out.println("Your order data is as follows: ");
System.out.println("Customer ID: " + customerId);
System.out.println("Unit Price: " + unitPrice);
System.out.println("Order Quantity: " + orderQuantity );
System.out.println("Product Description: " + productDescription);
System.out.println("Applied Discount: " + appliedDiscount);
//calculation formulas based on users input
double beforeDiscount = (unitPrice * orderQuantity);
double afterDiscount = beforeDiscount - (beforeDiscount * (appliedDiscount));
//totals before and after discount
System.out.println("Your Order Totals" );
System.out.println("Before Discount: "+ beforeDiscount);
System.out.println("After Discount: " + afterDiscount);
}
I did what i could and now the code works however when the user inputs the wrong value and is prompted to try again you have to hit enter and then you are asked to input a value, i cant think of what it is.
i also want to be able to get the program to start again after completing, i tried a do, while loop but it looped infinitely
public static void main(String[] args) {
String nameOfIngredient = null;
Float numberOfCups = null;
Float numberOfCaloriesPerCup = null;
Float totalCalories;
while(nameOfIngredient == null)
{nameOfIngredient = setIngredients(); }// Allows us to loop
while(numberOfCups == null)
{numberOfCups = setNumberOfCups(); }// Allows us too loop
while(numberOfCaloriesPerCup == null)
{numberOfCaloriesPerCup = setNumberOfCalories();} // Allows us to loop
totalCalories = numberOfCups * numberOfCaloriesPerCup;
System.out.println(nameOfIngredient + " uses " + numberOfCups + " cups and this amount contains " + totalCalories + " total calories.");
System.out.print("\n");
}
//A method to be called on in the main class while loop making it easier to read and maintain
public static String setIngredients() {
System.out.println("Please enter the name of the ingredient: ");
Scanner scan = new Scanner(System.in);
try {
String ingredients = scan.nextLine();
System.out.println("\r");
return ingredients;
}
catch (Exception e){
scan.nextLine();
System.out.println("Error taking in input, try again");
}
return null;
}
//A method to be called on in the main class while loop making it easier to read and maintain
public static Float setNumberOfCups() {
System.out.println("Please Enter Number Of Cups: ");
Scanner scan = new Scanner(System.in);
try {
String numberOfCups = scan.nextLine();
Float numberOfCupsFloat = Float.parseFloat(numberOfCups);
System.out.println("\n");
return numberOfCupsFloat;
}
catch (NumberFormatException numberFormatException){
System.out.println("Invalid Input must be a numeric value Please Try Again: ");
System.out.println("\n");
scan.nextLine();
}
catch (Exception e){
scan.nextLine();
System.out.println("Error taking in input, try again.");
}
return null;
}
//A method to be called on in the main class while loop making it easier to read and maintain
public static Float setNumberOfCalories() {
System.out.println("Please Enter Number Of Calories per cup: ");
Scanner scan = new Scanner(System.in);
try {
String numberOfCalories = scan.nextLine();
Float numberOfCaloriesFloat = Float.parseFloat(numberOfCalories);
System.out.println("\n");
return numberOfCaloriesFloat;
}
catch (NumberFormatException numberFormatException){
System.out.println("Invalid value Please enter a numeric value:");// if the input is incorrect the user gets prompted for the proper input
scan.nextLine();// if the input is incorrect the user gets prompted for the proper input
}
catch (Exception e){
scan.nextLine();
System.out.println("Error in input please try again.");
}
return null;
}
You may want to accept it as a string and check if it is numeric or not using String methods. Post that you can either move forward if format is correct or re prompt the user for correct value while showing the error.
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String nameOfIngredient = "";
double numberCups = 0.0;
int numberCaloriesPerCup = 0;
double totalCalories = 0.0;
System.out.println("Please Enter Ingredient Name: ");
nameOfIngredient = scnr.nextLine(); //In case ingredient is more than one word long.
System.out.println("Please enter the number of cups of " + nameOfIngredient + " required: ");
String numCups = scnr.next();
while(!numCups.chars().allMatch( Character::isDigit ))
{
System.out.println("Incorrect format for number of cups. Please enter numeric values");
numCups = scnr.next();
}
numberCups = Double.parseDouble(numCups);
System.out.println("Please enter the number of calories per cup of " + nameOfIngredient + " : ");
numberCaloriesPerCup = scnr.nextInt();
totalCalories = numberCups * numberCaloriesPerCup;
System.out.println(nameOfIngredient + " uses " + numberCups + " cups and this amount contains " + totalCalories + " total calories.");
}
Alternatively you could also do this using try catch statements. I believe this would be a better way to parse double values
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String nameOfIngredient = "";
double numberCups = 0.0;
int numberCaloriesPerCup = 0;
double totalCalories = 0.0;
System.out.println("Please Enter Ingredient Name: ");
nameOfIngredient = scnr.nextLine(); //In case ingredient is more than one word long.
System.out.println("Please enter the number of cups of " + nameOfIngredient + " required: ");
String numCups = scnr.next();
while(numberCups==0.0)
{
try {
numberCups = Double.parseDouble(numCups);
} catch (NumberFormatException e) {
System.out.println("Incorrect format for number of cups. Please enter numeric values");
numCups = scnr.next();
}
}
System.out.println("Please enter the number of calories per cup of " + nameOfIngredient + " : ");
numberCaloriesPerCup = scnr.nextInt();
totalCalories = numberCups * numberCaloriesPerCup;
System.out.println(nameOfIngredient + " uses " + numberCups + " cups and this amount contains " + totalCalories + " total calories.");
}
I've taken your code and added support for input of fractional numbers. Comments added on important changes.
parseCups returns an Optional so we can tell if the input was valid or not.
parseIngredientValue does the work of deciding whether or not the input is a fraction and/or attempting to parse the input as a Double.
package SteppingStone;
import java.util.Optional;
import java.util.Scanner;
public class SteppingStone2_IngredientCalculator {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String nameOfIngredient = "";
String cupsStr = "";
double numberCups = 0.0;
int numberCaloriesPerCup = 0;
double totalCalories = 0.0;
System.out.println("Please Enter Ingredient Name: ");
nameOfIngredient = scnr.nextLine(); // In case ingredient is more than one word long.
Optional<Double> cups = Optional.empty();
while (cups.isEmpty()) { // repeat until we've got a value
System.out.println("Please enter the number of cups of " + nameOfIngredient + " required: ");
cupsStr = scnr.nextLine();
cups = parseCups(cupsStr);
}
numberCups = cups.get();
System.out.println("Please enter the number of calories per cup of " + nameOfIngredient + " : ");
numberCaloriesPerCup = scnr.nextInt();
totalCalories = numberCups * numberCaloriesPerCup;
// Using String.format to allow rounding to 2 decimal places (%2.2f)
System.out.println(String.format("%s uses %2.2f cups and this amount contains %2.2f total calories.",
nameOfIngredient, numberCups, totalCalories));
}
private static double parseIngredientValue(String input) {
if (input.contains("/")) { // it's a fraction, so do the division
String[] parts = input.trim().split("/");
double numerator = (double) Integer.parseInt(parts[0]);
double denomenator = (double) Integer.parseInt(parts[1]);
return numerator / denomenator;
} else { // it's not a fraction, just try to parse it as a double
return Double.parseDouble(input);
}
}
private static Optional<Double> parseCups(String cupsStr) {
double result = 0.0;
String input = cupsStr.trim();
String[] parts = input.split(" +"); // split on any space, so we can support "1 2/3" as an input value
switch (parts.length) {
case 2:
result += parseIngredientValue(parts[1]); // add the 2nd part if it's there note that there's no
// break here, it will always continue into the next case
case 1:
result += parseIngredientValue(parts[0]); // add the 1st part
break;
default:
System.out.println("Unable to parse " + cupsStr);
return Optional.empty();
}
return Optional.of(result);
}
}
Sample run:
Please Enter Ingredient Name:
Special Sauce
Please enter the number of cups of Special Sauce required:
2 2/3
Please enter the number of calories per cup of Special Sauce :
1500
Special Sauce uses 2.67 cups and this amount contains 4000.00 total calories.
I still am a student and still learning java and I just recently learned how if...else... works but I don't know how to properly use it. How do I compute and display the amount of the total price using the if...else....
The problem:
A rice store nearby is on sale. All rice is sold at 10% (.1) off per kilo if the customer buys at least 11 kilos. For anything less than that, the regular price applies.
Here is the list of prices:
Lion - Php48/kilo
Ganador - Php50/kilo
Conchita - Php47/kilo
Other types of rice - Php45/kilo
Let the user input the rice purchased and the kilos and then compute and display the total amount the customer needs to pay.
Example: If a customer buys 3 kilos of Lion rice, your program is expected to only compute 3 kilos with the regular price.
Note: Customers may buy rice in any quantity, even half a kilo.
My code:
import java.util.Scanner;
public class Main
{
public static void main (String[] args)
{
System.out.println("List of prices: ");
System.out.println("Lion - Php48/kilo");
System.out.println("Ganador - Php50/kilo");
System.out.println("Conchita - Php47/kilo");
System.out.println("Other types of rice - Php45/kilo");
System.out.println(" ");
Scanner input = new Scanner(System.in);
System.out.println("Type of rice: ");
String rice = input.nextLine();
System.out.println(" ");
System.out.println("Kilos of rice: ");
int kilo = input.nextInt();
System.out.println(" ");
System.out.println("Type of rice: " +rice);
System.out.println("Kilos of rice: " +kilo);
if(kilo>11)
{
System.out.println("You have a discount of 10%.");
}
else if(kilo<11)
{
System.out.println("You have no discount of 10%.");
}
}
}
The problem statement says that any amount of rice can be bought, even half a kilo. Computers cannot accept vulgar fractions, like ½, but they can accept decimal fractions so the type for variable kilo should be double (and not int).
Think how you would do the calculation. You need to get the price for the type of rice that the user entered. I would use a switch statement or a Map but since you may not have already learned those and since you state that this is an exercise in using if...else, the below code uses if...else to get the price for the requested type of rice.
After you get the price, you simply multiply by the entered amount. Now you apply the discount. A discount of 10% means that you multiply the price by 0.9.
Here is the code.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("List of prices: ");
System.out.println("Lion - Php48/kilo");
System.out.println("Ganador - Php50/kilo");
System.out.println("Conchita - Php47/kilo");
System.out.println("Other types of rice - Php45/kilo");
System.out.println(" ");
Scanner input = new Scanner(System.in);
System.out.println("Type of rice: ");
String rice = input.nextLine();
System.out.println(" ");
System.out.println("Kilos of rice: ");
double kilo = input.nextDouble();
System.out.println(" ");
System.out.println("Type of rice: " + rice);
System.out.println("Kilos of rice: " + kilo);
int price;
if ("Lion".equals(rice)) {
price = 48;
}
else if ("Ganador".equals(rice)) {
price = 50;
}
else if ("Conchita".equals(rice)) {
price = 47;
}
else {
price = 45;
}
double cost = price * kilo;
if (kilo >= 11) {
System.out.println("You have a discount of 10%.");
cost *= 0.9;
}
else {
System.out.println("You have no discount of 10%.");
}
System.out.println("Cost: " + cost);
}
}
Note that you need to compare strings using method equals. Refer to How do I compare strings in Java?
Here is output of a sample run of the above code.
List of prices:
Lion - Php48/kilo
Ganador - Php50/kilo
Conchita - Php47/kilo
Other types of rice - Php45/kilo
Type of rice:
Ganador
Kilos of rice:
11.5
Type of rice: Ganador
Kilos of rice: 11.5
You have a discount of 10%.
Cost: 517.5
The key to this problem is utilizing conditional(e.g:if) statements or a HashMap to determine the value of the type of rice the customer selected.
Step 1: determine the type of rice.
Step 2: determine the price of the rice from Step 1
Step 3: determine whether or not the quantity of rice the customer selected is >=11 kilos
Step 4: if Step 3 is true, then apply a 90% discount on the totalPrice
Please also consider that if any other type of rice is provided the default price is 45.
Code Example below: utilizing a HashMap.
public class Main {
public static void main (String[] args)
{
//declaring local variables
int priceOfOtherTypesOfRice = 45;
double discountValue = 0.9;
HashMap<String,Integer> ricePriceMap = new HashMap<>();
ricePriceMap.put("Lion", 48);
ricePriceMap.put("Ganador", 50);
ricePriceMap.put("Conchita", 47);
double totalPrice =0.0;
System.out.println("List of prices: ");
System.out.println("Lion - Php48/kilo");
System.out.println("Ganador - Php50/kilo");
System.out.println("Conchita - Php47/kilo");
System.out.println("Other types of rice - Php45/kilo");
System.out.println(" ");
Scanner input = new Scanner(System.in);
System.out.println("Type of rice: ");
String rice = input.nextLine();
System.out.println(" ");
System.out.println("Kilos of rice: ");
int kilo = input.nextInt();
System.out.println(" ");
System.out.println("Type of rice: " +rice);
System.out.println("Kilos of rice: " +kilo);
if(kilo>11)
{
System.out.println("You have a discount of 10%.");
totalPrice =kilo * ((discountValue)*ricePriceMap.getOrDefault(rice, priceOfOtherTypesOfRice));
}
else if(kilo<11)
{
System.out.println("You have no discount of 10%.");
totalPrice =kilo * ricePriceMap.getOrDefault(rice, priceOfOtherTypesOfRice);
}
System.out.println("Final total cost of rice is " + totalPrice);
}
}
Console output:
I am creating a program that basically asks a user what they wish to purchase and gives them their total.
I am supposed to use 2 separate methods outside of Main to complete this task:
One method to get the user input as to which service they want performed, this method will also tell the user the total cost of the services (BEFORE TAX AND LABOR)
Another method to calculate labor costs and tax costs
The first method should return total cost to the main method, and the second method should get that total from the main method and calculate the Final Cost after labor and tax are added in.
(if the car is an import, 5% of the total should be added on)
Here is what I have so far:
import java.util.Scanner;
public class Assign3 {
public static double carMaintenance(String userCar) {
Scanner input = new Scanner(System.in);
String service_ordered="";
String more="yes";
double amount;
double total=0;
//declare and intialize parallel arrays, Services and Prices and display them to the user
String[] services = {"Oil Change" , "Tire Rotation", "Air Filter", "Fluid Check"}; //intialize list of services
double[]price = {39.99, 49.99, 19.99, 10.99}; //initialize corresponding price for services
for(int i= 0; i < services.length; i++) {
System.out.print( services[i]+ "...." );
System.out.print( price[i] + "\t");
}
do // *****2. THIS IS WHAT IS BEING EXECUTED FROM THE METHOD CALL IN MAIN *****
{
System.out.print("What service do you want done?: ");
String choice = input.nextLine();
if (choice.equalsIgnoreCase("oil change")) {
System.out.println("You chose an oil change");
amount = 39.99;
total = total + amount;
service_ordered+="Oil Change ";
System.out.print("Do you want to do another service? ");
more = input.nextLine();
} else if (choice.equalsIgnoreCase("tire rotation")) {
System.out.println("You chose a tire rotation");
amount = 49.99;
total = total + amount;
service_ordered+="Tire Rotation ";
System.out.print("Do you want to do another service? ");
more = input.nextLine();
} else if (choice.equalsIgnoreCase("air filter")) {
System.out.println("You chose an air filter");
amount = 19.99;
total = total + amount;
service_ordered+="Air Filter ";
System.out.print("Do you want to do another service? ");
more = input.nextLine();
} else if (choice.equalsIgnoreCase("fluid check")) {
System.out.println("You chose a flud check");
amount = 10.99;
total = total + amount;
service_ordered+="Fluid Check ";
System.out.print("Do you want to do another service? ");
more = input.nextLine();
}
} while (more.equalsIgnoreCase("yes"));
System.out.println("You ordered: " + service_ordered);
System.out.println("Your total due is " + total);
return total;
}
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.println("What kind of car do you have?: "); //****1. CODE STARTS HERE *****
String userCar = input.nextLine();
double total = carMaintenance(userCar); //*****2. CODE CALLS THIS METHOD AND EXECUTES IT *****
calcFinalPrice(total);
}
public static void calcFinalPrice(double total) {
double salesTax=.08;
double laborFee=.3;
double importFee=.05;
Scanner input = new Scanner(System.in);
System.out.println("Is your vehicle an import?: ");
String isImport = input.nextLine();
if(isImport.equals("yes")) {
total=total*laborFee+total; // this is the labor fee
double importTotal = total*importFee+total;
double totalAfterTax = importTotal*salesTax+importTotal; //this is the import total aftertax
System.out.println("It will cost " + totalAfterTax + " to fix your vehicle.");
}
if(isImport.equals("no")) {
total=total*laborFee+total; // this is the labor fee
double totalAfterTax = total*salesTax+total; //this is the total aftertax
System.out.println("It will cost " + totalAfterTax + " to fix your vehicle ");
}
}
}
package travelCost;
import java.util.Scanner;
public class travelCost {
public static void main(String[] args) {
//Scanner function
Scanner in = new Scanner(System.in);
//define problem variables
//first
double distance;
double mpg;
double pricePerGallon;
double milesPerKwh;
double pricePerKwh;
double totalCostGas;
double totalCostElec;
String type;
//Here i want the user to input a string and then based upon the answer //section into the for loop
System.out.println("Enter whether the car is 'elec' or 'gas': ");
type = in.next();
if (type.equals("elec"))
{
System.out.println("Enter the Total Distance in Miles: ");
distance = in.nextDouble();
System.out.println("Enter the total Miles per Kwh: ");
milesPerKwh = in.nextDouble();
System.out.println("Enter the Total Price per Kwh: ");
pricePerKwh = in.nextDouble();
totalCostElec = (distance/milesPerKwh) * pricePerKwh;
System.out.printf("The trip is going to cost $%5.2f: ", totalCostElec);
} else if (type.equals("gas: ")
{
System.out.println("Enter the Miles per Gallon: ");
mpg = in.nextDouble();
System.out.println("Enter the total Price per Gallon of Gasoline: ");
pricePerGallon = in.nextDouble();
System.out.println("Enter the total Price per Gallon of Gasoline: ");
pricePerGallon = in.nextDouble();
totalCostGas = (distance/mpg) * pricePerGallon;
System.out.printf("The trip is going to cost $%5.2f", totalCostGas);
}else
{
System.out.println("Please resubmit entry");
}
System.out.println();
}
}
After the corrections which mentioned by Paul, here is the complete code:
travelCost.java
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double distance;
double mpg;
double pricePerGallon;
double milesPerKwh;
double pricePerKwh;
double totalCostGas;
double totalCostElec;
String type;
System.out.println("Enter whether the car is 'elec' or 'gas': ");
type = in.next();
if (type.equals("elec")) {
System.out.println("Enter the Total Distance in Miles: ");
distance = in.nextDouble();
System.out.println("Enter the total Miles per Kwh: ");
milesPerKwh = in.nextDouble();
System.out.println("Enter the Total Price per Kwh: ");
pricePerKwh = in.nextDouble();
totalCostElec = (distance / milesPerKwh) * pricePerKwh;
System.out.printf("The trip is going to cost $%5.2f: ",
totalCostElec);
} else if (type.equals("gas")) {
System.out.println("Enter the Total Distance in Miles: ");
distance = in.nextDouble();
System.out.println("Enter the Miles per Gallon: ");
mpg = in.nextDouble();
System.out
.println("Enter the total Price per Gallon of Gasoline: ");
pricePerGallon = in.nextDouble();
System.out
.println("Enter the total Price per Gallon of Gasoline: ");
pricePerGallon = in.nextDouble();
totalCostGas = (distance / mpg) * pricePerGallon;
System.out.printf("The trip is going to cost $%5.2f", totalCostGas);
} else {
System.out.println("Please resubmit entry");
}
System.out.println();
}
Input:
elec 100 10 2
Output:
The trip is going to cost $20.00:
make it
else if (type.equals("gas"))
There are 4 problems with this:
The line } else if (type.equals("gas: ") needs another ) at the end.
In the "gas" case, you are using the variable distance but you do not give it a value.
While if (type.equals("elec")) is the correct syntax (answering your question), it is usually better to write if ("elec".equals(type)) because this will not throw a NullPointerException if type == null.
It should be "gas", not "gas: ".
As Paul mentions, your if statement syntax is correct, but it is good practice to start with the hard coded strings ("elec" and "gas") in order to avoid NullPointerExceptions. As mentioned in the other answers, the if else should be using "gas" instead of "gas: ". To help avoid those kinds of errors, you might consider making "elec" and "gas" into static final String constants. If you use constants, you'll know that they are the same throughout your program. You might also want to call type.toLowerCase() in the event that the user enters the response in uppercase.