Non-static method referenced from a static context [duplicate] - java

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 8 years ago.
I have two errors both the same and they follow below:
class FBox {//...}
class FBPlayer
{
//Initialized instances
FBox game = new FBox();
**FBPillar pillar = new FBPillar();**
**FBObjects objects = new FBObjects();**
//Lots o Properties...
public boolean get_Alive() { return this.b_PlayerAlive; }
public void set_Alive(boolean alive) { this.b_PlayerAlive = alive; }
//My Error ridden Method
public void checkCollision()
{
if(get_YPos() >= **objects**.get_Ground())
^My Error was incorrect name for my instance
{
set_Alive(false);
}
else if(get_Bounds().intersects(**pillar**.get_Bounds()))
^My Error was incorrect name for my instance
{
set_Alive(false);
}
}
class FBPillar
{
public int get_Bounds() {return 'the variable'; }
}
class FBObjects
{
public int get_Ground() {return 'the variable'; }
}
The error is in the if statement as well as the else if statement
When i run it it returns the error:
FBox.java:178: error: non-static method get_Bounds() cannot be referenced from a static context
else if(get_Bounds().intersects(**FBPillar**.get_Bounds()))
The same error for the if statement but with FBObjects.get_Ground())
^

Whose bounds are you talking about? You probably mean
if (get_Bounds().intersects(pillar.get_Bounds())) {
…
}
I'd also add that
FBPlayer player = new FBPlayer();
means that a player contains a player, which is probably isn't what you intended.

Related

Java consumer with return [duplicate]

This question already has answers here:
Why does a Java method reference with return type match the Consumer interface?
(2 answers)
Why doesn't for-each method in java not throw an exception when a Function type argument is passed instead of Consumer? [duplicate]
(3 answers)
Closed 4 years ago.
I don't understand why this code is working:
class Resource {
private Resource() {
System.out.println("created...");
}
public Resource op1() {
System.out.println("op1");
return this;
}
public Resource op2() {
System.out.println("op2");
return this;
}
private void close() {
System.out.println("clean up...");
}
public static void use(Consumer<Resource> block) {
Resource resource = new Resource();
try {
block.accept(resource);
}
finally {
resource.close();
}
}
}
// method call
public class App
{
public static void main( String[] args )
{
Consumer<Resource> block = resource -> resource.op1().op2(); //here
Resource.use(block);
}
}
Consumer should accept one parameter and return void. But in this example Consumer take one parameter(resource) and return this parameter. Why it is working although I return resource instance instead of void?
Your Consumer<Resource> block = resource -> resource.op1().op2(); is equivalent to:
Consumer<Resource> block = new Consumer<Resource>() {
#Override
public void accept(Resource resource) {
resource.op1().op2(); // there is no return statement
}
};

Compare object fields in if statement and 2 arraylists [duplicate]

This question already has answers here:
Java: Error: variable might not have been initialized
(2 answers)
Closed 5 years ago.
I'm trying to do a method that checks if a book is rented and then if the book is in a directory. But I get a variable might not have been initialized error on checkIsBookAvailableToRent. I wonder it means the variable may be the out of scope. Can you help me improve this method, please?
package com.company.model;
import java.util.ArrayList;
import java.util.List;
public class BookDirectory {
private static List<Book> bookDirectoryList = new ArrayList<Book>();
RentDirectory rentedBooksList = new RentDirectory();
Book book = new Book("");
public boolean isBookAvailableToRent(String title){
boolean checkIsBookAvailableToRent;
book.setTitle(title);
for (Book bookInRentDirectory : rentedBooksList.getRentedBooks()) {
if (bookInRentDirectory.getTitle().equals(book.getTitle())) {
checkIsBookAvailableToRent = false;
}
else {
for (Book bookInBookDirectory : bookDirectoryList) {
if (bookInBookDirectory.getTitle().equals(book.getTitle())) {
checkIsBookAvailableToRent = true;
}
else {
checkIsBookAvailableToRent = false;
}
}
}
}
return checkIsBookAvailableToRent;
}
public List<Book> getBookDirectory() {
return bookDirectoryList;
}
}
When you declare checkIsBookAvailableToRent, give it a default value, for example,
boolean checkIsBookAvailableToRent = false;
This is needed in case your code does not enter the for loop for any reason, such as if rentedBooksList.getRentedBooks() is empty. In that case, the function wouldn't know what to return.
In general, whenever you do declare variables, it's a good rule of thumb to give them a default value (unless there is a reason not to). That way you don't need to be concerned with errors like this.

I cant access the acessor method of another class? java [duplicate]

This question already has answers here:
Calling Non-Static Method In Static Method In Java [duplicate]
(14 answers)
Closed 6 years ago.
when I try to access the method of another class, it gives me an error that non-static method can't be accessed from static method but none of my methods are static.
import java.util.ArrayList;
public class creatureClassDriverRathtarsGame
{
public static void main(String[] args)
{
creatureClass player = new creatureClass("name", 14,new locationClass(0, 0, 0));
ArrayList <locationClass> locationRathTars = new <locationClass> ArrayList(5);
for(locationClass r: locationRathTars)
{
int randomRow = (Math.random() * ((locationClass.getMaxRow()) + 1));
int randomCol = (Math.random() * ((locationClass.getMaxCol()) + 1));
creatureClass rathtars = new creatureClass("rathtars",0, new locationClass(randomRow, randomCol, 0));
}
and the acessor method that is being called is
public int getMaxRow()
{
return maxrow;
}
public int getMaxCol()
{
return maxcol;
}
at first you must have the basic knowledge for java classes and objects and the difference between static and non-static members
to call a method using class name it must be static
so your acessor method should look like the blew
public static int getMaxRow()
{
return maxrow;
}
public static int getMaxCol()
{
return maxcol;
}
hope this is useful

Attempt to invoke virtual method on a null object reference issue [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am developing an App which uses the following code. It is generating an unexpected error as "Attempt to invoke virtual method on a null object reference". I do not understand the reason why this is happening. The error is thrown as the line containing t[i].setTestname(getData(exams[i]));. Could someone please point out what I am doing wrong. Could use some help over here.
void processTestPerformance()
{
String exams[],rawdata;
rawdata=data.toString();
int numberoftests=getNumbers("tabletitle03",rawdata);
Tests[] t= new Tests[numberoftests];
exams=new String[numberoftests];
rawdata=rawdata+"tabletitle03";
for(int i=0;i<numberoftests;i++)
{
int j=rawdata.indexOf("tabletitle03");
int k=(rawdata.substring(j+1)).indexOf("tabletitle03");
exams[i]=rawdata.substring(j,j+1+k);
t[i].setTestname(getData(exams[i]));
rawdata=rawdata.substring(k);
}
}
The code for class Tests is as follows:
public class Tests
{
public int numberofsubjects;
public String testname;
public Subject s[];
public void setS(Subject[] s)
{
this.s = s;
}
public void setNumberofsubjects(int numberofsubjects)
{
this.numberofsubjects = numberofsubjects;
s=new Subject[numberofsubjects];
}
public void setTestname(String testname)
{
this.testname = testname;
}
}
Thanks in Advance.
You create an empty array of Tests class, of size numberoftests
If you look inside that array you will find a sequence of null. Because you never initialize it.
You just need to populate the array so that t[i] will return an instance of your class.
In your for-cycle you can for example use the default constructor:
t[i] = new Tests();
// now you can manipulate the object inside the array
t[i].etTestname(getData(exams[i]));
for(int i=0;i<numberoftests;i++)
t[i]=new Tests();
That solved my problem.

Error: 'void' type not allowed here [duplicate]

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;
}

Categories