I'm new to java and trying to create a simple code checking the gas usage of a given car with given miles per gallon and gas but every time I try to initialize the variables, it keeps giving me errors. inTank and mpg say that only final is permitted and the constructors can't initialize the variable parameters for some reason. If someone could explain to me why and how to fix this I would be grateful. Happens in the Udacity IDE and Ecclipse.
public class MileagePrinter {
public static void main(String[] args)
{
// your code here
private double inTank;
private double mpg;
public MileagePrinter(double gasInTank, double milesPerGallon) {
inTank = gasInTank;
mpg = milesPerGallon;
}
}
}
Reorder the code... you have class variables and a constructor inside the main method...
it must look like
public class MileagePrinter {
private double inTank;
private double mpg;
public MileagePrinter(double gasInTank, double milesPerGallon) {
inTank = gasInTank;
mpg = milesPerGallon;
}
public static void main(String[] args){
// your code here
}
}
Main method and constructor are different from each other. Main is the starting point of execution of a program whereas constructor is used to create an object. We need to take constructor out of main method here, e.g.
public class MileagePrinter {
private double inTank;
private double mpg;
public MileagePrinter(double gasInTank, double milesPerGallon) {
inTank = gasInTank;
mpg = milesPerGallon;
}
public static void main(String[] args){
MileagePrinter pointer = new MileagePrinter(10d, 100d); //create object using constructor
}
}
Personally I prefer to separate the main in a class Main (for example, the name isn't important) for an organization of this type:
main.java :
public class Main {
public static void main(String[] args) {
// your code here
}
}
MileagePrinter.java :
public class MileagePrinter {
private double inTank;
private double mpg;
public MileagePrinter(double gasInTank, double milesPerGallon) {
inTank = gasInTank;
mpg = milesPerGallon;
}
}
Related
I'm very new to java. I am writing this program that calculates Compound and Simple Interest and some other things which I'll add in the future.
Syntax-
Class Data
import java.util.Scanner;
public class DATA {
public static void main(String[] args) {
Scanner m=new Scanner(System.in);
System.out.println("What do you want to calculate SI/CI");
String choice=m.nextLine();
{
if (choice.equalsIgnoreCase("si") || choice.equalsIgnoreCase("ci"))
Interest.var();
if (choice.equalsIgnoreCase("si")){
Interest.ci();
}
}
}
}
Class Interest
import java.util.Scanner;
public class Interest {
public static void var(){
Scanner m=new Scanner(System.in);
System.out.println("Enter the principle");
double p=m.nextDouble();
System.out.println("Enter the rate");
double r=m.nextDouble();
System.out.println("Enter the time");
double t=m.nextDouble();
}
public static void si(double p, double r, double t){
double si=(p*r*t)/100;
System.out.println("The Simple Interest is "+si);
}
public static void ci(double p, double r, double t){
double ci=p*Math.pow((1+(r/100)),(t))-p;
System.out.println("The Compound Interest is "+ci);
}
}
I've created a method called var in the Interest class which asks for the principle and other data for calculation. So If the user asks to calculate CI/SI, it imports the var method and asks the questions. now I can't figure out a way to use those variable for calculation.
I hope you guys can help me, criticisms and suggestions are welcomed but if you can help me with the current problem, that would be more then helpful and again I'm really new to java
Create private variables p,r and t inside the class Interest. Create a constructor and pass the 3 values. So if you call the method si() or ci(), you can simply use this.p, this.r and this.t to calculate. You can also remove the params in si() and ci() methods.
When you define a class in JAVA, usually if you have variables that you use in more than one function, you define them like global variables for that class and use getters and setters methods to get or set them, like :
import java.util.Scanner;
public class Interest {
private double p;
private double r;
private double t;
......
public void setP(double p){this.p=p;}
public void setR(double r){this.r=r;}
public void setT(double t){this.t=t;}
public double getP(){return p;}
public double getR(){return r;}
public double getT(){return t;}
}
However, your code could looks like :
import java.util.Scanner;
public class Interest {
private double p;
private double r;
private double t;
public static void var(){
Scanner m=new Scanner(System.in);
System.out.println("Enter the principle");
p=m.nextDouble();
System.out.println("Enter the rate");
r=m.nextDouble();
System.out.println("Enter the time");
t=m.nextDouble();
}
public static void si(){
double si=(p*r*t)/100;
System.out.println("The Simple Interest is "+si);
}
public static void ci(){
double ci=p*Math.pow((1+(r/100)),(t))-p;
System.out.println("The Compound Interest is "+ci);
}
}
Here is my main class for this and I keep getting an error saying that
The abstract class has not been overridden
I have tried making the car class abstract and not overridding, I have tried to override and using an abstract class, without success. I just don't know what I'm doing wrong.
public abstract class Car implements CarbonFootprint {
private double Car;
private double MilesDrivenPerYear;
private double MilesPerGallon;
//Constructor
public Car(double MilesDrivenPerYear, double MilesPerGallon) {
this.MilesDrivenPerYear = MilesDrivenPerYear;
this.MilesPerGallon = MilesPerGallon;
}
//Return miles driven per year
public double getMilesDrivenPerYear() { return MilesDrivenPerYear; }
//Return Miles per Gallon
public double getMilesPerGallon() { return MilesPerGallon; }
public void setMilesDrivenPerYear(double MilesDrivenPerYear) {
this.MilesDrivenPerYear = MilesDrivenPerYear;
}
public void setMilesPerGallon(double MilesPerGallon) {
this.MilesPerGallon = MilesPerGallon;
}
#Override
public String toString() {
return String.format("%s: %n%s: %s", "Car", "Miles
Driven: ",getMilesDrivenPerYear(), "Miles per
Gallon; ",getMilesPerGallon());
}
public abstract double Car();
public double getCarbonFootprint() {
return Car = getMilesDrivenPerYear() / getMilesPerGallon() * 19.82;
}
}
//end car class'
public class CarbonFootprintTest {
public static void main(String[] args) {
ArrayList FootprintList = new ArrayList();
Car Footprint1 = new Car(25, 36);
FootprintList.add(Footprint1);
Building Footprint2 = new Building(78, 78);
FootprintList.add(Footprint2);
Bicycle Footprint3 = new Bicycle(90);
FootprintList.add(Footprint3);
System.out.println("Shaina Carbon Footprint Calculator");
for (Object Footprint: FootprintList) {
System.out.printf("Miles Driven:");
System.out.printf("Car Carbon Footprint",
Footprint2.getCarbonFootprint());
}
}
Car is an Abstract class, so you cannot create an instance of it. You should probably make another class that extends the Car class. See this answer for information:
https://stackoverflow.com/a/30317092/7260643
I tried making a simple class in java using netbeans IDE. Whenever I try to do execute this it gives such warning."non static variable referenced from static context".Can anyone tell me why it happens and how to solve it. Thanx in advance.
public class HW3Q4 {
class Payment{
private double amount_payment;
public void set_amount(double amount){
amount_payment = amount;
}
public double get_amount(){
return amount_payment;
}
public void paymentDetails(){
System.out.println("The amount of the payment is: "+amount_payment);
}
}
public static void main(String[] args) {
// TODO code application logic here
Payment p1 = new Payment();
p1.set_amount(34000.00);
p1.get_amount();
p1.paymentDetails();
}
}
You make a mistake in creating the object. So this would help you:
public class HW3Q4 {
class Payment{
private double amount_payment;
public void set_amount(double amount){
amount_payment = amount;
}
public double get_amount(){
return amount_payment;
}
public void paymentDetails(){
System.out.println("The amount of the payment is: "+amount_payment);
}
}
public static void main(String[] args) {
// TODO code application logic here
HW3Q4 newInstance = new HW3Q4();
newInstance.init();
}
public void init(){
Payment p1 = new Payment();
p1.set_amount(34000.00);
p1.get_amount();
p1.paymentDetails();
}
}
Your payment class is within the HW3Q4 which try to act similar to say a string field within your class HW3Q4 like private String myString. So in order to avoid the error use:
HW3Q4 h = new HW3Q4 ();
Payment p1 = h.new Payment();
You are declaring a separate Payment class for each instance of HW3Q4. Instead, I think you want to declare Payment in its own file (Payment.java), which would be preferred, but I guess you could declare it as a static inner class - just change class Payment { /* ... */ } to static class Payment { /* ... */ }.
I'm having trouble with a problem I'm working on for class.
The errors occurring are
TC1.java:17: error: myQuantity has private access in CheckItem
items[i].myQuantity=quantities[i];
and
TC1.java:20: error: myPrice has private access in CheckItem
a[i]=items[i].myPrice*((items[i].mySalesTax\100)+1);
This is the code I currently have.
public class CheckItem
{
private double myPrice,
mySalesTax;
private int myQuantity = 1;
public CheckItem( double price, double salesTax )
{
myPrice = price;
mySalesTax = salesTax;
}
public int getQuantity()
{
return myQuantity;
}
public void setQuantity( int qty )
{
myQuantity = qty;
}
public double lineItemTotal()
{
return roundMoney((myPrice*myQuantity)*((mySalesTax/100)+1));
}
public static double roundMoney( double amount )
{
return (int)(100 * amount + 0.5) / 100.0;
}
public static void setQuantities( CheckItem[] items, int[] quantities )
{
for (int i=0;i<quantities.length;i++){
items[i].myQuantity=quantities[i];
}
}
public static double[] lineItemTotals( CheckItem[] items )
{
double[] a=new double[items.length];
for (int i=0;i<items.length;i++){
a[i]=items[i].myPrice*((items[i].mySalesTax/100)+1);
}
return a;
}
}
The problem is that static methods can't access private instance variables. Define getters and setters for those variables, and use them:
items[i].setQuantity(quantities[i]);
a[i]=items[i].getPrice()*((items[i].getSalesTax()\100)+1);
and it will work.
This code compiles fine. If you are trying to access private members outside this class you would get private access error during compilation. In that case standard fix is to provide setters and/or getters.
** EDIT **
Seems like there is confusion about allowed access. You can NOT access any instance variables from static methods/context DIRECTLY! But you CAN access instance variables via instance itself as shown here:
class Test {
private int s = 123;
void instPrint() {
System.out.println(s); // fine
}
static void statPrint(Test ss) {
System.out.println(ss.s); // this is fine too!
// System.out.println(s); // does not compile obviously
}
}
This is the same case as in the code above. This has nothing to do with access modifiers because it's all happening in the same class.
Your code declares these two member variables in class CheckItem with the private scope. This means no other classes can access them directly on a CheckItem instance:
private double myPrice,
mySalesTax;
If you want class TC1 to be able to read or modify them, declare them in CheckItem.java as public. Alternatively, and generally a better practice, you could add public methods to CheckItem.java to allow other classes to access their values:
public double getMyPrice() {
return this.myPrice;
}
public void setMyPrice(double price) {
this.myPrice = price;
}
public double getMySalesTax() {
return this.mySalesTax;
}
public void setMySalesTax(double st) {
this.mySalesTax = st;
}
public int getMyQuantity() {
return this.myQuantity;
}
public void setMyQuantity(int newQty) {
this.myQuantity = newQty;
}
Then, in TC1.java you'd use these methods instead of direct access:
items[i].setMyQuantity(quantities[i]);
and
a[i]=items[i].getMyPrice()*((items[i].getMySalesTax()\100)+1);
So I have a car class and a car tester class. Here is the car class:
package main;
public class Car {
private long distance;
private double newDistance;
private double gasAmount;
private double newGasAmount;
// Contrsuctor
Car(){
distance = 0;
}
Car(long newDistance){
distance = newDistance;
}
//Accessor
public long getDistance(){
return distance;
}
public double getGasInTank(){
return gasAmount;
}
//Mutator
public void drive(double distance){
newDistance = distance;
}
public void addGas(double gasAmount){
newGasAmount = gasAmount;
}
}
And here is the problem. In my carTester class, why doesnt myVehicle.drive(); work??
It underlines it in red (netBeans) and says "package myVehicle doesn't exist"
package main;
public class CarTester {
Car myVehicle = new Car();
myVehicle.drive();
double gasLeft = myVehicle.getGasInTank();
}
The compiler will issue this message when you attempt to invoke an operation on an Object in the class block.
You need to use a main method in CarTester. Also you need to supply a double distance value as per your drive method.
public class CarTester {
public final static void main(String[] args) {
Car myVehicle = new Car();
myVehicle.drive(33.2);
...
}
}
run your code in CarTester class inside of the method. for example public final static void main(String[] args) {...}...
e.g.
package main;
public class CarTester {
public final static void main(String[] args) {
Car myVehicle = new Car();
myVehicle.drive();
double gasLeft = myVehicle.getGasInTank();
}
}
I think what the problem is is that you don't have a method in class CarTester. The compiler is complaining that it cannot find a package with the name of myVehicle, because it is trying to interpret the line myVehicle.drive(); as a type. You need to change the class CarTester to something like:
public class CarTester
{
public static void main(string[] args)
{
Car car = new Car();
car.drive(10.0);
double gasLeft = car.getGasInTank();
}
}