# Simple miles per gallon code

Page 1 of 1

## 14 Replies - 30707 Views - Last Post: 27 August 2013 - 08:15 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=327670&amp;s=85df1f78b5ba0754bd2a430e1d9be599&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 Flippinroo2

Reputation: 0
• Posts: 37
• Joined: 31-July 13

# Simple miles per gallon code

Posted 25 August 2013 - 04:13 PM

Hey guys, I was wondering if you could help me out. I seem to get an error when i run this code. I can't figure out what it is.
```import java.util.Scanner;
public class Calculation {

static double mpg, dollarpermile, fulltank;
static Scanner scanner = new Scanner(System.in);

public static int miles(){
System.out.println("Please enter the number of miles driven.");
int miles = scanner.nextInt();
return miles;
}
public static int gallons(){
System.out.println("Please enter the number of gallons used.");
int gallons = scanner.nextInt();
return gallons;
}
public static double money(){
System.out.println("Please enter the price per gallon.");
double money = scanner.nextDouble();
return money;
}

public static void main (String[] args){
mpg = miles() / gallons();
dollarpermile = gallons() * money();
fulltank = gallons() * miles();
System.out.println("You get " + mpg + " miles per gallon.");
System.out.println("You get \$" + dollarpermile + " dollars per mile.");
System.out.println("On a full tank you can drive " + fulltank + "miles with a full tank.");

}

}

```

Is This A Good Question/Topic? 0

## Replies To: Simple miles per gallon code

### #2 schutzzz

• D.I.C Regular

Reputation: 143
• Posts: 342
• Joined: 22-April 13

## Re: Simple miles per gallon code

Posted 25 August 2013 - 04:39 PM

Can you post the error?

### #3 pbl

• There is nothing you can't do with a JTable

Reputation: 8378
• Posts: 31,956
• Joined: 06-March 08

## Re: Simple miles per gallon code

Posted 25 August 2013 - 05:54 PM

not sure what you consider as an error, but one thing for sure int that extract from your code

```		mpg = miles() / gallons();
dollarpermile = gallons() * money();
fulltank = gallons() * miles();

```

the methods miles(), gallons() and money() should only be called once and the value returned store in temp variables
```		double totalMiles = miles();
double totalGallons  = gallons();
double totalMoney = money();
dollarpermile = totalGallons * totalMoney;
fulltank = totalGallons() * totalMiles();

```

### #4 StrongJoshua

Reputation: 48
• Posts: 170
• Joined: 19-July 13

## Re: Simple miles per gallon code

Posted 25 August 2013 - 06:48 PM

In a program like this I would have made it procedural, instead of using methods. Simple create a GasTank class (call it what you like) and when you create a new GasTank object in your main method it will ask the user to enter the values in turn, which you will store within the class so that you don't accidentally ask twice. Then at the end you would just print out the ending statements (this is all within the GasTank class).

### #5 ChrisNt

• cute bug

Reputation: 262
• Posts: 896
• Joined: 31-July 13

## Re: Simple miles per gallon code

Posted 25 August 2013 - 10:47 PM

```public static double money(){
. . .
}

Should be...

public static double getMoney() {
. . .
}

```

This post has been edited by ChrisNt: 25 August 2013 - 10:50 PM

### #6 schutzzz

• D.I.C Regular

Reputation: 143
• Posts: 342
• Joined: 22-April 13

## Re: Simple miles per gallon code

Posted 25 August 2013 - 11:28 PM

the methods shouldn't be static at all. absolutely no reason for it.

### #7 Mylo

• Knows all, except most.

Reputation: 265
• Posts: 747
• Joined: 11-October 11

## Re: Simple miles per gallon code

Posted 25 August 2013 - 11:54 PM

I think that using OOP for just a single, simple problem, is far from necessary, and seemingly ridiculous to me. It's not like he needs to reuse anything here.

### #8 pbl

• There is nothing you can't do with a JTable

Reputation: 8378
• Posts: 31,956
• Joined: 06-March 08

## Re: Simple miles per gallon code

Posted 26 August 2013 - 03:55 AM

Mylo, on 26 August 2013 - 02:54 AM, said:

I think that using OOP for just a single, simple problem, is far from necessary, and seemingly ridiculous to me. It's not like he needs to reuse anything here.

It is far from necessary if you have OO experience and already wrote a few hundred programs.
But in the case of a newbie who start to learn, like we have here, better to start right now with the good principles. It is not when he will have to interface a gas tanks inventory system with a the available tankers of a military squadron performing refuelling in the air that it will be the time for him to start to create objects.

### #9 Mylo

• Knows all, except most.

Reputation: 265
• Posts: 747
• Joined: 11-October 11

## Re: Simple miles per gallon code

Posted 26 August 2013 - 04:04 AM

Of course, and I'm in full support of that. I suppose my thinking was more objective sided, than teaching sided.

### #10 Flippinroo2

Reputation: 0
• Posts: 37
• Joined: 31-July 13

## Re: Simple miles per gallon code

Posted 26 August 2013 - 12:36 PM

Thanks guys for all the feedback, I've worked on it and tweaked it up but I am still getting an error. I am just starting out programming so I don't understand some of the abbreviations you guys use.
```public class Calculation extends GasTank{

public static void main (String[] args){

Calculation gastank1 = new Calculation(); // creates the object GasTank() from the Gastank() class

gastank1.getMiles();
gastank1.getGallons();
gastank1.getMoney();

System.out.println("You get " + gastank1.mpg() + " miles per gallon.");
System.out.println("You get \$" + gastank1.dollarpermile() + " dollars per mile.");
System.out.println("On a full tank you can drive " + gastank1.fulltank() + " miles with a full tank.");
}
}

```

That is my main class with main method, and I made a GasTank() class then created an object. Here is the GasTank class code.
```import java.util.Scanner;

public class GasTank {

double mpg, dollarpermile, fulltank, money;
int miles, gallons;
Scanner scanner = new Scanner(System.in);

public int getMiles(){
System.out.println("Please enter the number of miles driven.");
int miles = scanner.nextInt();
return miles;
}
public int getGallons(){
System.out.println("Please enter the number of gallons used.");
int gallons = scanner.nextInt();
return gallons;
}
public double getMoney(){
System.out.println("Please enter the price per gallon.");
double money = scanner.nextDouble();
return money;
}
public double mpg(){
double mpg = miles / gallons;
return mpg;
}
public double dollarpermile(){
double dollarpermile = gallons * money / mpg;
return dollarpermile;
}
public double fulltank(){
double fulltank = gallons * mpg;
return fulltank;
}
}

```

When i compile and run the program it asks for the correct input but there is an error during the calculation. For testing purposes i use 400 miles 14 gallons @ 3.38 per gallon. Here is the error:

Exception in thread "main" java.lang.ArithmeticException: / by zero
at GasTank.mpg(GasTank.java:26)
at Calculation.main(Calculation.java:12)

### #11 schutzzz

• D.I.C Regular

Reputation: 143
• Posts: 342
• Joined: 22-April 13

## Re: Simple miles per gallon code

Posted 26 August 2013 - 01:04 PM

you get the error because it's trying to divide by 0.

you're creating a new int (which first off is wrong because gas and miles are not always whole numbers) its a big problem. also the get methods should only be getting data from the object that's already there. You shouldn't request the information in it.

```private int miles;
...

public GasTank(double miles, double gallons, double ppg) {
this.miles = miles;
...
}

public double getMiles() {
return miles;
}

...

```

```import java.util.Scanner;

public class Driver {

double miles;
double gallons;
double ppg;

public static void main(String[] arguments) {
Driver driver = new Driver();
}

Driver() {
Scanner scanner = new Scanner(System.in);
System.out.println("Miles?");
miles = scanner.nextDouble();
...
GasTank tank1 = new GasTank(miles,...,...);
System.out.println(tank1.getMiles());
...
}

}

```

edit: by the way you can return equations.

```public int add() {
return var1 + var2;
}

```

```public int add() {
int result = var1 + var2;
return result;
}

```

This post has been edited by schutzzz: 26 August 2013 - 01:15 PM

### #12 ChrisNt

• cute bug

Reputation: 262
• Posts: 896
• Joined: 31-July 13

## Re: Simple miles per gallon code

Posted 26 August 2013 - 01:26 PM

In all get methods you create local variables and you return them and not your fields which have the same name.
```public class GasTank {

double mpg, dollarpermile, fulltank, money;
int miles, gallons;
Scanner scanner = new Scanner(System.in);

public int getMiles(){
System.out.println("Please enter the number of miles driven.");
int miles = scanner.nextInt();  // you create a local variable
return miles;                   // you return that local variable and not your
// field miles which has the same name
}

```

So when you call this method everything is 0

```public double mpg(){
mpg = miles / gallons; // these are your fields which you didnt change the value of them
return mpg;            // thats why you get that exception because you divine with 0
}

```

Local variable's scope is from the line they are declared on until the closing curly brace of the method or code block within which they are declared.

But as schutzzz said getter should return information about the state of an object and not change the state of that object.

Also why you extend GasTank??

### #13 Flippinroo2

Reputation: 0
• Posts: 37
• Joined: 31-July 13

## Re: Simple miles per gallon code

Posted 26 August 2013 - 03:24 PM

I fixed it up, and made it look better.
```public class Calculation{

public static void main (String[] args){
GasTank gastank1 = new GasTank();

gastank1.getMiles();
gastank1.getGallons();
gastank1.getMoney();

System.out.println("You get " + gastank1.mpg() + " miles per gallon.");
System.out.println("You get \$" + gastank1.dollarpermile() + " dollars per mile.");
System.out.println("On a full tank you can drive " + gastank1.fulltank() + " miles with a full tank.");
}
}

```

Here is the GasTank() code
```import java.util.Scanner;
class GasTank {

double mpg;
double dollarpermile;
double fulltank;
double money;
double miles;
double gallons;

Scanner scanner = new Scanner(System.in);

public double getMiles(){
System.out.println("Please enter the number of miles driven.");
return miles = scanner.nextDouble();
}
public double getGallons(){
System.out.println("Please enter the number of gallons used.");
return gallons = scanner.nextDouble();
}
public double getMoney(){
System.out.println("Please enter the price per gallon.");
return money = scanner.nextDouble();
}
public double mpg(){
return mpg = miles / gallons;
}
public double dollarpermile(){
return dollarpermile = gallons * money / mpg;
}
public double fulltank(){
return fulltank = gallons * mpg;
}
}

```

Here is the output:
Please enter the number of miles driven.
400
Please enter the number of gallons used.
14
Please enter the price per gallon.
3.38
You get 28.571428571428573 miles per gallon.
You get \$1.6562 dollars per mile.
On a full tank you can drive 400.0 miles with a full tank.

Is there any ways I can round the number up to the hundreths place. I would also like to make the 400.0 miles output as an even 400

### #14 schutzzz

• D.I.C Regular

Reputation: 143
• Posts: 342
• Joined: 22-April 13

## Re: Simple miles per gallon code

Posted 26 August 2013 - 03:37 PM

Take a look into DecimalFormat or printf

don't use the get methods to ask for data, use them to retrieve the data!

Your GasTank class should look similar to this

```public class GasTank {

private double totalMiles;
private double tankCapacity;
private double pricePerGallon;

public double getTotalMiles() {
}

public double getTankCapacity() {
return tankCapacity;
}

public double getPricePerGallon() {
return pricePerGallon;
}

public double getMilesPerGallon() {
}

public double getTotalPrice() {
return tankCapacity * pricePerGallon;
}

public double getPricePerMile() {
return getTotalPrice() / getMilesPerGallon();
}

public GasTank(double totalMiles, double tankCapacity, double pricePerGallon) {
this.totalMiles = totalMiles;
this.tankCapacity = tankCapacity;
this.pricePerGallon = pricePerGallon;
}

}

```

Get the input in your class with the main method.

```import java.util.Scanner;

public class GasDriver {

private Scanner input = new Scanner(System.in);

private GasDriver() {
System.out.println("Miles:");
double miles = input.nextDouble();

System.out.println("Gallons:");
double gallons = input.nextDouble();

System.out.println("PPG:");
double price = input.nextDouble();

GasTank tank1 = new GasTank(miles, gallons, price);

System.out.println(tank1.getMilesPerGallon());
... // etc..

}

public static void main(String[] arguments) {
new GasDriver();
}

}

```

Also you don't need to initialize a double while your retrieving the information, you're doing this

```public double mpg(){
return mpg = miles / gallons;
}

```

it really should be
```public double getMpg() {
return miles / gallons;
}

```

This post has been edited by schutzzz: 26 August 2013 - 03:59 PM

### #15 Flippinroo2

Reputation: 0
• Posts: 37
• Joined: 31-July 13

## Re: Simple miles per gallon code

Posted 27 August 2013 - 08:15 PM

Here is my final product, I think it looks much better now. Thanks for all your help guys the finished product looks much better then my first attempt.
```import javax.swing.JOptionPane;
public class Calculation{
private Calculation(){
double mpg;
double dollarpermile;
String money;
double moneyNumber;
String miles;
double milesNumber;
String gallons;
double gallonsNumber;

miles = JOptionPane.showInputDialog(null, "Please enter the number of miles driven.");
milesNumber = Double.parseDouble(miles);

gallons = JOptionPane.showInputDialog(null, "Please enter the number of gallons used.");
gallonsNumber = Double.parseDouble(gallons);

money = JOptionPane.showInputDialog(null, "Please enter the price per gallon.");
moneyNumber = Double.parseDouble(money);

mpg =  milesNumber / gallonsNumber;
dollarpermile = gallonsNumber * moneyNumber / mpg;

JOptionPane.showMessageDialog(null, "You get " + mpg + " miles per gallon," + " and you spend \$" + dollarpermile + " dollars per mile.");

System.out.println("You get " + mpg + " miles per gallon.");
System.out.printf("You get \$" + dollarpermile + " dollars per mile.");
}
public static void main (String[] args){
new Calculation();
}
}

```