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 { /* ... */ }.
Related
I've been working with Java in the last few days, so I am very new to programming in Java.
I am currently going through a bunch of online tutorials and trying to learn as much as possible. In one tutorial, we are getting to learn how to use objects correctly. The person who made the video uses an online compiler, while i follow along in eclipse.
In my code I have two classes
The first is called objectDesign
public class objectDesign {
public static void main(String[] args) {
System.out.println("We are creating a new PEZ dispenser");
PezDispenser dispenser = new PezDispenser();
System.out.printf("The dispenser is %s", dispenser.characterName);
}
}
The second is called PezDispenser
public class PezDispenser {
public String characterName;
public static void main(String[] args) {
String characterName="Mario";
}
}
The goal is to define the character who the object is supposed to be. I used a string called characterName and set it to Mario which i would like to return when I run the objectDesign class. I made the string public thinking that would enable the objectDesign class to find the information. However the console returns "The dispenser is null" every time I run the code.
What am I doing wrong?
You can use below code
package com.stackoverflow;
public class ObjectDesign {
public static void main(String[] args) {
System.out.println("We are creating a new PEZ dispenser");
PezDispenser dispenser = new PezDispenser("Mario");
System.out.printf("The dispenser is %s", dispenser.characterName);
}
}
package com.stackoverflow;
public class PezDispenser {
public String characterName;
public PezDispenser(String characterName) {
// TODO Auto-generated constructor stub
this.characterName=characterName;
}
}
here are few ways of doing this
Option 1:
public class PezDispenser {
public String characterName = "Mario";
public static void main(String[] args) {
String characterName="Mario"; // This statement is never executed because this class's main was never invoked.
}
}
Option 2:
public class PezDispenser {
public String characterName;
public static void main(String[] args) {
String characterName="Mario";
}
}
public class objectDesign {
public static void main(String[] args) {
System.out.println("We are creating a new PEZ dispenser");
PezDispenser dispenser = new PezDispenser();
dispenser.characterName = "Mario";
System.out.printf("The dispenser is %s", dispenser.characterName);
}
}
These are not the best options, but going by what you are trying to achieve these should serve the purpose.
How can I call two methods from the same class over one object? I mean I try to write a class and its methods to run above code:
volume = Calculate.do_calc().get_volume(a);
I am creating Calculate class and two methods of it. do_calc() and get_volume(a). How should I write this class to run that code.
Unless do_calc() returns the class in where de function get_volume() is located this should never be done.
Here is a little sample for you.
public class ChainTest {
public static void main(String[] args) {
System.out.println(new ChainTest().do_calc().get_volume(1));
}
public ChainTest do_calc() {
// do something;
return ChainTest.this;
}
public int get_volume(int a) {
return a;
}
}
You don't need to write the code in one line. You can call same object methods in different lines.
Calculator calculator = new Calculator();
calculator.do_calc();
calculator.get_volume(a);
In case, if you want static methods
Calculator.do_calc();
Calculator.get_volume(a);
Case 1 If do_calc is static
public class Calculator {
public static void main(String[] args) {
System.out.println(Calculator.do_calc().get_volume(1));
}
public static Calculator do_calc() {
Calculator calculator = new Calculator();
// do something;
return calculator;
}
public float get_volume(int a) {
return a;
}
}
Case 2 : If do_calc is not static
public class Calculator {
public static void main(String[] args) {
System.out.println(new Calculator().do_calc().get_volume(1));
}
public Calculator do_calc() {
Calculator calculator = new Calculator();
// do something;
return calculator;
}
public float get_volume(int a) {
return a;
}
}
Case 3 : If both have return type float as you mentioned in comment
public class Calculator {
public static void main(String[] args) {
Calculator calculator = new Calculator();
calculator.do_calc();
System.out.println(calculator.get_volume(1));
}
public float do_calc() {
// do something;
return 1f; // return your result
}
public float get_volume(int a) {
// do something;
return a;
}
}
You must return this; at the end of each method of your class if they are not static. If the methods are static, do it like this:
public class Calculation {
public static Calculation do_calc () {
//do your calculation
return null;
}
public static Calculation get_volume(int x) {
//do your calculation
return null;
}
}
Then you can write:
Calculation.do_calc().get_volume(1);
No problem in returning null, as the methods are static and not related to a specific instance of the class. If you don't like it, then return new Calculation();
[Edit]
The first method should return a real object if you need to pass its result to the second method:
public class Calculation {
int result;
public static Calculation do_calc () {
//do your calculation
Calculation c=new Calculation();
c.result = theResultOfTheCalculation;
return c;
}
public void get_volume(int x) {
//do your calculation for example:
System.out.println(result + x);
}
}
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;
}
}
I am writing a code that create an array of instances of Account object in another class (Bank).
I am initializing the array inside the main method, but it is not accessible inside the Bank class.
What I want to do is create 4 instances of the Account class and to be able to perform all tasks inside the Bank class methods. Is there a way that I can do this?
this is my code
Account.java
package question1;
import java.util.Date;
public class Account {
public int AccountNum;
public double BALANCE;
public Date OPENDATE;
public String OwnerName;
public Account() {
// TODO Auto-generated constructor stub
}
public Account(int accnum, double balance, Date opendate, String ownername) {
this.AccountNum = accnum;
this.BALANCE = balance;
this.OPENDATE = opendate;
this.OwnerName = ownername;
}
public int getAccountNum() {
return AccountNum;
}
public void setAccountNum(int accountNum) {
AccountNum = accountNum;
}
public double getBALANCE() {
return BALANCE;
}
public void setBALANCE(double bALANCE) {
BALANCE = bALANCE;
}
public Date getOPENDATE() {
return OPENDATE;
}
public void setOPENDATE(Date oPENDATE) {
OPENDATE = oPENDATE;
}
public String getOwnerName() {
return OwnerName;
}
public void setOwnerName(String ownerName) {
OwnerName = ownerName;
}
public double yearlyInterest(double balace) {
return balace;
}
}
Bank.java
package question1;
public class Bank {
public static void main(String[] args) {
Account[] acc = new Account[4];
for(int i = 0 ; i<acc.length; i++){
acc[i] = new Account();
System.out.println(acc[i].toString());
}
/// how to continue form here ??
}
}
Call the constructor of the Account class. Now you can set all arguments as desired. Afterwards, you can add the instance to any array or collection.
List<Account> accounts = new ArrayList<Account>(4);
Account myAccount = new Account(123, 100.5, new Date(), "dev leb");
accounts.add(myAccount);
You probably want to have a property of an Account array in your class.
You can set your property in the class body:
public class Bank {
//Set your property here.
private Account[] _acc;
//Initialize in ctor.
public Bank() {
_acc = new Account[4];
}
//....
//You can then use it as a property in your code.
//If needed outside the class, set up setter and getter methods,
//avoiding violating encapsulation.
public Account[] getAcc(){
return _acc;
}
public void setAcc(Account acc){
this._acc = acc;
}
//If you need this to be used inside main, then you must instantiate a
//Bank in main and then make all the appropriate operations there.
public static void main(String[] args) {
Bank bank = new Bank();
Account[] bankAccounts = bank.getAcc();
//....
}
}
My suggestion though is that you use an ArrayList instead:
Set the property:
private List<Account> acc;
And in constructor:
acc = new List();
In order to add an account in a class method:
acc.add(new Account());
In order to retrieve an element by indexing:
acc.get(0);
for more information, look at the ArrayList JavaDoc.
If you are not able to understand why your array that is defined inside the main is not accessible inside your Bank class, then I suggest you search more about Object-Oriented programming, Class definition, instantiation and properties accessibility and manipulation and static methods in Java.
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();
}
}