This is a code for a foundations class that I'm working on currently. I keep getting an error, but I'm not sure what I've done incorrectly. Any help would be greatly appreciated. Thanks!
package miles;
public class Miles {
private int miles;
private int gas;
public static int mpg;
public void setMiles(int miles) {
this.miles = miles;
}
public void setGas(int gas){
this.gas = gas;
}
public int getMpg(){
mpg = miles/gas;
return mpg;
}
}
package miles;
import java.util.Scanner;
public class MilesDriver {
public static void main(String [] args) {
Miles gas = new Miles();
Scanner input = new Scanner(System.in);
System.out.println("Enter Miles: ");
int setGas = input.nextInt();
System.out.println("Enter Gas: ");
int setMiles = input.nextInt();
System.out.printf("MPG: %n%s%n", gas.getMpg() );
}
}
You actually forgot to set the values of your object :
System.out.println("Enter Miles: ");
int setMiles = input.nextInt();
gas.setMiles(setMiles);
System.out.println("Enter Gas: ");
int setGas = input.nextInt();
gas.setGas(setGas);
Try not to give a variables name the same name as a method of your object. You'll end confusing yourself and get stuck.
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.