I am currently using the Udacity Introduction to Java course. There was a topic on Algorithms and it gave an example Algorithm for comparing and purchasing two different cars in pseudo code. I decided to turn that into some Java code to see just how well I grasped the concept.
The algorithm was:
For each car, compute. Gas cost = (miles driven / mpg) * price per gallon. Total cost = gas cost + car cost. If car 1 < car 2, buy car 1. Else, buy car 2.
//Algorithm for buying a car
//by comparing car price, MPG,
//local gas price, and the miles
//to be drive in total.
//idea from udacity Intro
//to Java course.
import java.util.Scanner;
public class buyingCars {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the price of car one: ");
int carOnePrice = input.nextInt();
System.out.println("Enter the price of car two: ");
int carTwoPrice = input.nextInt();
System.out.println("Enter the price of gas in your area: ");
double gasPrice = input.nextDouble();
System.out.println ("What is the average mpg of car one? ");
int carOneMpg = input.nextInt();
System.out.println ("What is the average mpg of car two? " );
int carTwoMpg = input.nextInt();
System.out.println("Give me an amount of miles total you think you will drive in this car: ");
int milesDriven = input.nextInt();
double gasCostCarOne = (milesDriven / carOneMpg) * gasPrice;
double totalCostCarOne = gasCostCarOne + carOnePrice;
double gasCostCarTwo = (milesDriven / carTwoMpg) * gasPrice;
double totalCostCarTwo = gasCostCarTwo + carTwoPrice;
if (totalCostCarOne < totalCostCarTwo) {
System.out.println("Car One will, in total, cost less than car two. Buy it.");
}
else {
System.out.println("Car two will, in total, cost less than car one. Buy it.");
}
}
}
What I am wondering is if my code was clean and my form is good? Are there things I am doing in my code that I should not be, or is everything looking pretty solid?
Also, is there a simpler way of doing this? It just seems like an awful lot of code that could potentially be narrowed down. Could each car hold it's values in an array or something like that?
If there is a problem with my post, please let me know. I am still getting use to posting here.