This question already has answers here:
What is the reason behind "non-static method cannot be referenced from a static context"? [duplicate]
(13 answers)
Closed 10 years ago.
i am trying to pass the value t from one class to another, but before i even run the program i get non static method cannot be referenced from static context from this line of code :
t = (PrinterSettings.getT() * 60);
i am trying to get the value t from this code :
public int t = 1; //defualt value for amount of mintues in the future the job should wait untill sent
public int getT() {
return (t);
}
public void setT(int t) {
this.t = t;
}
what have i done wrong ? and how can i get t
EDIT :
Whole of my code where i get t from
public int t = 1; //defualt value for amount of seconds in the future the job should wait untill sent
public int getT() {
return (t);
}
public void setT(int t) {
this.t = t;
}
and this is the class that i am using that calls t from the above class to use:
public class DealyTillPrint {
public int t;
public String CompletefileName;
private String printerindx;
private static int s;
private static int x;
public static int SecondsTillRelase;
public void countDown() {
System.out.println("Countdown called");
s = 1; // interval
t = ((new PrinterSettings().getT()) * 60); //(PrinterSettings.SecondsTillRelase); // number of seconds
System.out.println("t is : " + t);
while (t > 0) {
System.out.println("Printing in : " + t);
try {
Thread.sleep(s * 1000);
} catch (Exception e) {
}
t--;
}
and here is where i set t using a spinner
<p:spinner min="1" max="1000" value="#{printerSettings.t}" size ="1">
<p:ajax update="NewTime"/>
</p:spinner>
You're using PrinterSettings.getT() but you can't do that because PrinterSettings is a class and the getT() method is for the object. You need to create an object of PrinterSettings first, then you can call getT().
PrinterSettings myObjectOfPrinterSettings = new PrinterSettings();
myObjectOfPrinterSettings.getT(); //this should work without the error
You can choose to do 1 of 2 things:
1) Make everything in your PrinterSettings file static (and make PrinterSettings static as well):
public static int t = 1;
public static int getT() {
return (t);
}
public static void setT(int t) {
this.t = t;
}
2) Don't change PrinterSettings, and just do this for your code:
//Put this somewhere at the beginning of your code:
PrinterSettings printerSettings = new PrinterSettings();
//Now have some code, which will include setT() at some point
//Then do this:
t = (printerSettings.getT() * 60);
In my opinion the latter would be more preferable.
EDIT: The edit that I just made is because if you don't keep a hold on the PrinterSettings variable that you were using, new-ing one up will have t be 1 in that new PrinterSettings object. Instead, make sure that you're instantiating an object of PrinterSettings at the beginning of your program, and just use that one the whole way through.
Instead of:
public int getT() {
return (t);
}
Write:
public static int getT() {
return (t);
}
This will solve your problem.
With this change you can access this method with its class name. As a class method.
Related
My class has a scheduled method that runs every half a second and it checks the data to see if any of the devices have timed out. If they are timed out for at least 5 seconds I am throwing an event to my database (this is done by checkSpecs method which I haven't reproduced here. The actual class is quite large so I have attempted to reduce the size while keeping relevant parts).
Now I am adding a new method to the class, checkReconnections which I want to use to throw another event to the database whenever a connection that previously timed out is regained.
Because my class is so large and I am monitoring several devices with this method, I attempted to create a helper method monitorConnectionStatus that accepts two booleans as arguments. My question is concerning this method.
I was under the impression that in passing the instance variables into monitorConnectionStatus when the method is invoked, that method gains access to them and can reassign those variables. This is my intent in order for the method to function as intended. But my IDE is telling me that the value of disconnectionStatus will always be false, which caused me to think, am I wrong in believing the instance variable will be reassigned? Is it possible that my IDE is just wrong in this case?
When I reassign the value of disconnectionStatus is it reassigning the value of the instance variable hasADisconnected or is it just doing it with a local argument variable?
Public Class OffSpecAgent {
private final DataModel dataModel;
private int deviceATimeoutCounter = 0;
private boolean isDeviceATimeout = false;
private boolean hasADisconnected = false;
private int deviceBTimeoutCounter = 0;
private boolean isDeviceBTimeout = false;
private boolean hasBDisconnected = false;
#Scheduled(fixedDelay = 500)
public void offSpecMonitor() {
checkTimeouts();
checkReconnections();
checkSpecs();
}
private void checkTimeouts() {
deviceATimeoutCounter = dataModel.getBoolean(DEVICE_A_TIMEOUT) ? deviceATimeoutCounter + 1 : 0;
isDeviceATimeout = deviceATimeoutCounter >= 10;
deviceBTimeoutCounter = dataModel.getBoolean(DEVICE_B_TIMEOUT) ? deviceBTimeoutCounter + 1 : 0;
isDeviceBTimeout = deviceATimeoutCounter >= 10;
}
private void checkReconnections() {
monitorConnectionStatus(isDeviceATimeout, hasADisconnected);
monitorConnectionStatus(isDeviceBTimeout, hasBDisconnected);
}
private void monitorConnectionStatus(boolean timeoutCondition, boolean disconnectionStatus) {
if (timeoutCondition) {
disconnectionStatus = true;
}
if (disconnectionStatus && !timeoutCondition) {
disconnectionStatus = false;
//throw reconnection event
}
}
}
In java, variables are passed by value into methods, meaning your method monitorConnectionStatus is only aware that it's getting false, false values. You would have to update your method to access the instance variable directly.
private void monitorConnectionStatus() {
if (this.timeoutCondition) {
this.disconnectionStatus = true;
}
if (this.disconnectionStatus && !this.timeoutCondition) {
this.disconnectionStatus = false;
//throw reconnection event
}
}
Note the keyword this is not required.
Also, I just want to add that you are using the term class variable incorrectly. The variables you are referring to are instance variables.
You can read more about that here:
https://www.tutorialspoint.com/What-are-class-variables-instance-variables-and-local-variables-in-Java
I refactored the class and now it looks like this:
Public Class OffSpecAgent {
private final DataModel dataModel;
private static class ConnectionTracker {
boolean timeout, timeoutExceeded, hasDisconnected;
int timeoutCounter = 0;
}
private final ConnectionTracker deviceATracker = new ConnectionTracker();
private final ConnectionTracker deviceBTracker = new ConnectionTracker();
#Scheduled(fixedDelay = 500)
public void offSpecMonitor() {
checkTimeouts();
checkReconnections();
checkSpecs();
}
private void checkTimeouts() {
trackTimeout(plcTracker, dataModel.getBoolean(DEVICE_A_TIMEOUT), 10);
trackTimeout(plcTracker, dataModel.getBoolean(DEVICE_B_TIMEOUT), 20);
}
private void trackTimeout(ConnectionTracker tracker, boolean isTimeout, int maxTimeout){
tracker.timeout = isTimeout;
tracker.timeoutCounter = isTimeout ? tracker.timeoutCounter + 1 : 0;
tracker.timeoutExceeded = tracker.timeoutCounter >= maxTimeout;
}
private void checkReconnections() {
monitorConnectionStatus(deviceATracker);
monitorConnectionStatus(deviceBTracker);
}
private void monitorConnectionStatus(ConnectionTracker tracker) {
if (tracker.timeoutExceeded) {
tracker.hasDisconnected = true;
}
if (tracker.hasDisconnected && !tracker.timeout) {
tracker.hasDisconnected = false;
//throw reconnection event
}
}
}
This seems to be much of an improvement, the tracker object actually makes the code more readable in my opinion, and now I am able to have the desired behavior. Thank you to everyone who responded to my question.
I have a little problem in a simple class.
import java.util.Random;
public class fileTest {
private static Random rand = new Random();;
private int randOne = rand.nextInt(10);
private String strOne = String.format("%02d", this.randOne);
public int getRandOne() {
return randOne;
}
public void setRandOne(int randOne) {
this.randOne = randOne +1;
}
public String getStrOne() {
return strOne;
}
}
My "launcher"
public class launch {
public static void main(String[] args) {
fileTest fileA = new fileTest();
System.out.println(fileA.getStrOne());
//FunctionDoMyStuff...
fileA.setRandOne(fileA.getRandOne());
System.out.println(fileA.getRandOne());
//RandOne is increment
System.out.println(fileA.getStrOne());
//StrOne is not
}
}
My idea is to create a random number and transform it into a string.
After finishing my stuff, I need to increment my string.
But the result after the setter is the same as in the beginning. I think I don't understand everything about a getter/setter.
Can anyone help me to understand my mistake?
This happens once at the time that your instance is created:
private String strOne = String.format("%02d", this.randOne);
It isn't automatically run again after you change randOne. The solution is to remove the strOne field altogether and construct the String inside the getter:
public String getStrOne() {
return String.format("%02d", this.randOne);
}
You don't need to store a dynamically derived value.
The behaviour of your method setRandOne doesn't match what people might reasonably expect a set method to do. A method that does what yours does could be described as setRandOneToOneHigherThan(int value). Or you could call it incrementRandOne() but then the body needs to do this.randOne = this.randOne + 1; (or this.randOne++;). Or you could make it a normal setter and do the incrementing while you call the method: fileA.setRandOne(fileA.getRandOne() + 1);.
This question already has answers here:
What causes "'void' type not allowed here" error
(7 answers)
Closed 10 months ago.
I'm learning to use classes and part of my assignment is to make this Car class. I'm getting an error on line 6 where I attempt to print of the results of the methods within the class. I think this means that I'm attempting to print something that doesn't exist and I suspect it's the mileage method. I tried changing it to return miles, but that didn't work either. Any ideas?
public class TestCar {
public static final void main(String args[]) {
Car c = new Car ();
c.moveForward(4);
System.out.println ("The car went" + c.mileage() + "miles."); // <-- L6
}
}
class Car {
public int miles = 2000;
public void moveForward(int mf) {
if (miles != 2000) {
miles += mf;
}
}
public void mileage() {
System.out.print(miles);
}
}
The error message is telling you exactly what is wrong -- you're trying to extract a result from a method that does not return a result.
Instead, have the mileage() method return a String, not print out a String.
public String mileage() {
return String.valueOf(miles);
}
Myself, I'd make this a getter method, and instead would do:
public int getMiles() {
return miles;
}
Car.mileage() is void, i.e., does not return anything. It needs to return something, like in:
public int mileage() {
return miles;
}
Just trying to run through some code for an assignment I'm doing. It is probably simple but for the life of me I can't figure out why I get the above error at the first line
(public WaterLog.......).
Later I want to pass it this line:
[ log = new WaterLog(8, damCapacity); ]
Any help would be appreciated, I am new to this sorry.
public class WaterLog(Integer windowSize, Integer maxEntry) {
private Integer size = windowSize;
private Integer max = maxEntry;
private ArrayList theLog(int windowSize);
private int counter = 0;
public void addEntry(Integer newEntry) throws SimulationException {
theLog.add(0, newEntry);
counter++;
}
public Integer getEntry(Integer index) throws SimulationException {
If (thelog.isEmpty() || thelog.size() < index) {
return null;
}
return thelog.get(index);
}
public Integer variation() throws SimulationException {
int old, recent = 0;
recent = thelog.get(0);
old = thelog.get(thelog.size-1);
return recent-old;
}
public Integer numEntries() {
return counter;
}
}
Assuming SimulationException is defined correctly:
class WaterLog{
private Integer size;
private Integer max ;
private ArrayList<Integer> theLog; //parameterize your lists
private int counter = 0;
public WaterLog(Integer windowSize, Integer maxEntry) //this is the behavior you were looking for
{
this.size = windowSize;
this.max = maxEntry;
theLog = new ArrayList<Integer>(windowSize);
}
public void addEntry(Integer newEntry) throws SimulationException {
theLog.add(0, newEntry);
counter++;
}
public Integer getEntry(Integer index) throws SimulationException {
if (theLog.isEmpty() || theLog.size() < index) { //Java is case sensitive
return null;
}
return theLog.get(index);
}
public Integer variation() throws SimulationException {
int old, recent = 0;
recent = theLog.get(0);
old = theLog.get(theLog.size()-1); //again, watch case, also size is a method
return recent-old;
}
public Integer numEntries() {
return counter;
}
}
See the comments I added.
EDIT: To explain a bit further what was going on, let's take a look at what you were doing.
public class WaterLog(Integer windowSize, Integer maxEntry) {
private Integer size = windowSize;
private Integer max = maxEntry;
private ArrayList theLog(int windowSize);
private int counter = 0;
You seem to have confused a class with a constructor. The variables you defined were attributes, which was correct. You needed to use the syntax I showed in my answer to create a constructor. For that same reason, you don't have access to variables like windowSize. To remedy this, we allow them to still be defined outside the constructor, but assigned values inside it, where we have access to windowSize and maxEntry.
If you want to pass some parameters to this class you need a constructor. By default Each and EVERY class comes with a default constructor - which is there, you just don't see it ( but can declare it). What you can then do is make an overloaded construcotr ( which takes some arguments ) and this is what you want so..
if you have a class
class WaterLog {
// no constructor
}
the above is really a
class WaterLog {
public WaterLog() {
// this is the constructor - if you do not declare it its still here, you just dont see it. Ofcourse you have option to declare it.
}
}
The overloaded constructor is something like this
class WaterLog {
public WaterLog() {
//default constructor
}
public WaterLog(Integer int, String string, etc...) {
//overloaded constructor
}
}
and the above is what you need in order to pass arguments to this class constructor. I am not briliant at explaining things but if you need more clarification just let me know :)
I have the following method that I would like to test, it simply increments an int if a Boolean condition is true:
public void incrementIfConditionMet(Boolean personCheckedIn) {
int peopleInHotel=0;
if (personCheckedIn==true){
peopleInHotel++
}
}
I am very new to unit testing in Java. How can I unit test this to check if the int has been incremented or not?
Currently your value of peopleInHotel cannot be accessed outside the method, as it was created internally. If you want to access it, you should do the following:
private int peopleInHotel=0;
public int getPeopleInHotel() {
return peopleInHotel;
}
public void incrementIfConditionMet(Boolean personCheckedIn) {
if (personCheckedIn){
peopleInHotel++
}
}
Now in your test class, you can check by calling getPeopleInHotel();
So the test case would be:
int initalValue = classInstance.getPeopleInHotel();
classInstance.incrementIfConditionMet(true);
assertEquals(classInstance.getPeopleInHotel(), initalValue +1);
This would also fix your issue where you don't keep the value once the method has been ran. At the moment, in your current code setup, your variable of peopleInHotel is discarded after you've finished with the method.
int peopleInHotel=0;
public void incrementIfConditionMet(Boolean personCheckedIn) {
if (personCheckedIn==true){
peopleInHotel++
}
}
public int getPeopleInHotel() { //test the returned value after you've incremented
return peopleInHotel;
}
Try like this:
public class Hotel {
private int peopleInHotel = 0;
//a constructor...
public int getPeopleInHotel() {
return this.peopleInHotel;
}
public void incrementIfConditionMet(Boolean personCheckedIn) {
if (personCheckedIn==true){
peopleInHotel++
}
}
}
In your Unit-Test, you now can do something like that:
//defining your TestCase
Hotel hotel = new Hotel();
int initValue = hotel.getPepleInHotel();
hotel.incrementIfconditionmet(true);
assertEquals(hotel.getPeopleInHotel(),initValue+1);