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

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

Related

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

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.

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

Nullpointerexception and no compilation errors. Can't find cause [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
been struggling with this problem since a couple of hours. Including looking through the previous questions answered. (Im really new in Java, basicly started a couple of days ago)
it keeps giving me NullpointerExceptions between Register.läggTillhund(nyHund); in the first class and hundRegister.add(nyHund); in the second class.
I have no idea what might be causing them. Does anyone have Ideas?
The purpose of the code (when finished) is to add an object from the 3rd class, into a list in the secondclass using the firstclass as the "main program".
Thanks for the help!
Oskar
First Class (Main)
public class testning {
public static void main(String[] args) {
Hund nyHund = new Hund("Daisy", 13, "labrador", 22.3);
System.out.println(nyHund.toString());
System.out.println(nyHund);
Register.läggTillHund(nyHund);
}
}
Second Class:
import java.util.ArrayList;
public class Register {
private static ArrayList<Hund> hundRegister;
public static void läggTillHund(Hund nyHund){
hundRegister.add(nyHund);
System.out.println(nyHund);
}
public Register(){
hundRegister = new ArrayList<Hund>();
}
}
Third Class
public class Hund {
private String namn;
private int ålder;
private double vikt;
private String ras;
public Hund(String hundnamn, int hundålder, String hundras, double hundvikt) {
this.namn = hundnamn;
this.ålder = hundålder;
this.ras = hundras;
this.vikt = hundvikt;
}
public String getNamn() {
return namn;
}
public int getÅlder() {
return ålder;
}
public double getSvanslängd() {
if ("tax".equals(ras)){
return 3.7;
}else{
return ((vikt*ålder)/10);
}
}
public String toString() {
return namn + "\n" + ålder + "\n"+ras+"\n"+vikt+"\n"+getSvanslängd();
}
}
You're accessing static method. In this case constructor never working. Use private static ArrayList<Hund> hundRegister = new Arraylist<>() ;and delete the constructor. To see what's going on add System.out.println line to construct and you'll see it will never works

Java - use class defned in Main in another class

I'm new to Java and we have to make this little project. So i have 3+ classes.
MY code is in pastebin
http://pastebin.com/GEq9DLiP
etc. etc.
Problem is, that in 3rd class it sais
"kangelane cannot be resolved"
but kangelane is already "defined" in Main.java and they are in same package.
Oh and Eclipse also wants to add "open bracet" after
int sook = 4; or
int dam;
and also "clode bracket" to the end
even though all open brackets are closed and vice versa
I have Getters and Setters in "Voitleja.java", so that works.
It also worked, when i only had 2 classes not 3 (Voitlus was in Main)
The problem is that main is a static class, if you want to use a variable in both main and in an oter class, you have to defined it as a static variable, for your example you should do :
public class Main {
static Voitleja kangelane;
public static void main(String[] args) {
String nimi = JOptionPane.showInputDialog("Sisestage võitleja nimi");
kangelane = new Voitleja(nimi, 55, 12);
}
}
Then in your other class (assuming the import are correct)
public class Voitlus{
Random generator = new Random();
int dam;
int sook = 4;
while (true) {
Main.kangelane.setElud(kangelane.getElud() + 7);
}
}
public static void main(String[] args) {
String nimi = JOptionPane.showInputDialog("Sisestage võitleja nimi");
Voitleja kangelane = new Voitleja(nimi, 55, 12);
}
(later)
while (true) {
kangelane.setElud(kangelane.getElud() + 7);
}
The variables are in a different scope. You have to declare kangelane right after your public class declaration so both methods can "see" it.

non static method cannot be referenced from static context - JAVA [duplicate]

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.

Categories