This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 6 years ago.
So I have created a ArrayList within a GrownUp class that then produces a for loop to call a method from within another class. When I'm trying to call the object of this new method, I am getting an error that it is not recognising the object. This is what the method looks like:
public void personShowering()
{
PowerShower callshower = new PowerShower(1,1,1,1);
if(people.size()>1)
callshower.shower(people.get(0));
}
}
Person
import java.util.ArrayList;
public abstract class Person
{
ArrayList<Person> people;
Person(int age, String name)
{
}
public void shower(Person x)
{
people.get(0).shower(//what goes here?);
}
}
Error:
method shwer() in class perosn cannot be applied to given types;
required: Person
found: no given types
The callshower should be refering to a class called PowerShower which has been created using PowerShower callshower = new PowerShower(1,1,1,1); so I'm confused as to why it's looking in the Person class? The PowerShower class is quite big but I will post it:
PowerShower
public class PowerShower extends Shower
{
public int isOn = -1;
public int isOff = 0;
public int incrementTime;
public int varPass = -1;
#Override
public int currentState()
{
if (varPass == 0)
return isOff;
else
{
return isOn;
}
//returns isOn;
}
#Override
public void useTime(int defaultTime)
{
defaultTime = 15;
incrementTime = 1;
}
#Override
public void shower()
{
PowerShower shower = new PowerShower(1,1,1,1);
shower.timePasses();
}
#Override
public void timePasses()
{
if(varPass == isOff)
varPass = 0;
else
{
GasMeter.getInstance().incrementConsumed(waterUse);
GasMeter.getInstance().incrementConsumed(10);
int gasconsumed = GasMeter.getInstance().getGasUsed();
WaterMeter.getInstance().incrementConsumed(waterUse);
WaterMeter.getInstance().incrementConsumed(5);
int waterconsumed = WaterMeter.getInstance().getWaterUsed();
System.out.println("Power shower water consumption = " + waterconsumed);
System.out.println("Power shower gas consumption = " + gasconsumed);
}
}
PowerShower(int electricityUse, int gasUse, int waterUse, int timeOn)
{
super(electricityUse, gasUse, waterUse, timeOn);
this.electricityUse = 0 * incrementTime;
this.gasUse = 10 * incrementTime; //10x1;
this.waterUse = 5 * incrementTime; //5x1;
this.timeOn = 15 * incrementTime;
}
}
I'm not too sure why i am getting this error because I have created a object of that class and called it but it doesn't seem to be recognizing that object? Any is would be great, thanks.
What you are trying to do is not possible. I don't know why you believe it could be possible. This is not how multiple-inheritance could look like which is not supported by Java except for interfaces and default methods. If it was possible it would rather look like this (WON'T COMPILE):
public class GrownUp extends Person, SuperShower
....
people.get(0).shower()
You can call a method of an object. What you can't do is this:
people.get(0).callshower
A Person probably has no method (or field) callshower. callshower is a variable containing an object. You can call the method shower on it if existing.
It seems that you want to put the person and to have a shower together. What you can do is:
Add a method shower to Person and call it: people.get(0).shower()
Change PowerShower.shower() to have a parameter Person and then do the following call: callshower.shower(people.get(0))
Related
This question already has answers here:
java ArrayList contains different objects
(5 answers)
Closed 6 years ago.
I have an abstract class with several subclasses. A tester class has an ArrayList with 1 object of each subclass in it. They each have a method of the same name, how can I iterate through the ArrayList and call that method for each object?
One of my subclasses (others basically the same):
public class MyMath extends Homework {
private int pagesRead;
private String typeHomework;
public MyMath(int pagesRead, String typeHomework) {
super(pagesRead, typeHomework);
}
public void createAssignment(int p) {
setPagesRead(p);
setTypeHomework(typeHomework);
}
public void toString(int pagesRead, String typeHomework) {
System.out.println("Homework type: " + typeHomework + ". Number of pages read: " + pagesRead + ".");
}
}
In my tester class main method:
ArrayList homework = new ArrayList();
homework.add(new MyMath(5, "Math"));
homework.add(new MyScience(5, "Science"));
homework.add(new MyEnglish(5, "English"));
homework.add(new MyJava(5, "Java"));
Well, if the method is specified in your abstract class, and you have already built the ArrayList with all the objects inside it, you should simply be able to iterate through the ArrayList (for-loop) and just call the .method()
If your ArrayList is of type and your interface also has the method then you can call them like so
for(int i = 0; i < list.length();i++)
{
list[i].METHOD_NAME();
}
You can iterate through the arraylist ant it contains objects and you can call the method on that object. for example,
ArrayList<AbstractClass1> objs = new ArrayList<AbstractClass1>();
objs.add(); // you have added objects already.
Then
for(int i = 0; i< objs.size() ; i++){
objs.get(i).methodYouDefined();
}
If you haven't covered generics yet in class, you have to cast manually. If you have covered generics, you should use them! See lak91's answer.
public abstract class AbstractTest
{
public abstract void oneTwo( int i, String s );
public static void main(String[] args) {
List list = new ArrayList();
list.add( new One() );
list.add( new Two() );
for( Object test : list ) {
AbstractTest abTest = (AbstractTest) test;
abTest.oneTwo( 0, "test" );
}
}
}
class One extends AbstractTest {
#Override
public void oneTwo( int i, String s )
{
System.out.println("One");
}
}
class Two extends AbstractTest {
#Override
public void oneTwo( int i, String s )
{
System.out.println("Two");
}
}
I just learnt how to use Arrays i wrote this program in Java on Netbeans. It compiled with no errors but gave me a blank output my if was true but when it jumped to the else the output was ok
THIS IS MY JAVA CLASS
public class VacationScale {
public int[] vacationDays;
public int yearsOfService;
public void setVacationScale(){
vacationDays = new int[7];
vacationDays[0] = 10;
vacationDays[1] = 15;
vacationDays[2] = 15;
vacationDays[3] = 15;
vacationDays[4] = 20;
vacationDays[5] = 20;
vacationDays[6] = 25;
}
public void displayVacationDays(){
if (yearsOfService >= 0){
System.out.println("Vacation days: " + vacationDays[yearsOfService]);
}else {
System.out.println("invalid number of years");
}
}
}
AND THIS IS MY MAIN CLASS (TESTING)
public class VacationScaleTest {
public static void main(String[] args) {
VacationScale personOne;
personOne = new VacationScale();
personOne.yearsOfService = 2;
personOne.displayVacationDays();
}
}
BOTH IN THE SAME PROJECT
i tried debugging and got Debugger stopped on uncompilable source code at
System.out.println("Vacation days: " + vacationDays[yearsOfService]);
That's because you still haven't set the array vacationDays[] at the point you make the call to displayVacationDays().
Do the following - add this line before the line where you have personOne.displayVacationDays(),
personOne.setVacationScale();
// Now make the call to display vacation days
I got the same error message in a completely different constellation.
I'm using java fx
I googled for it and found no similar cases. After some tests, I found out that when creating a new PropertyValueFactory I got this nerving error message.
The line of code that caused the problem was:
TableColumn<Values, String> col = new TableColumn<>(val.getName());
col.setCellValueFactory(
new PropertyValueFactory<Values,String>("Value")
);
The class Values is a subclass and looks like this:
private class Values {
private final SimpleStringProperty vall;
public Values(String d) {
this.vall = new SimpleStringProperty(d);
}
public String getValue() {
return vall.get();
}
public void setValue(String value) {
vall.set(value);
}
}
Solution:
After a lot of checking, I found out that my Values class must be PUBLIC and not private.
public class Values {
...
}
I hope it can be useful for someone.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
getting a frustrating null exception error when the class junction is being used in functions. The class should be initialised so this shouldn't be an issue. Help ;_;
class RobotData {
class Junction {
public int juncX;
public int juncY;
public int arrivalHeading;
}
private static int maxJunctions = 10000; //Max junctions likely to occur
private static int junctionCounter;
private static Junction[] junction;
RobotData() {
junctionCounter = 0;
junction = new Junction[maxJunctions];
}
public void resetJunctionCounter() { junctionCounter = 0; }
public void recordJunction(IRobot robot) {
junction[junctionCounter].juncX = robot.getLocation().x;
junction[junctionCounter].juncY = robot.getLocation().y;
junction[junctionCounter].arrivalHeading = robot.getHeading();
junctionCounter++;
}
public void printJunction() {
System.out.println(junction[junctionCounter].juncX);
System.out.println(junction[junctionCounter].juncY);
System.out.println(junction[junctionCounter].arrivalHeading);
}
}
The class RobotData is being initialised properly, but when the functions are being called I get the null error indicating that junction[junctionCounter] hasn't been initialised yet. Unsure why (obviously) as it should be initialised when RobotData is.
When you write this line:
junction = new Junction[maxJunctions];
You create an array of maxJunctions references to Junction instances on the heap. All of them are null until you point them to an object on the heap by calling new.
Here's another idea:
public class Junction {
public final int juncX;
public final int juncY;
public final int arrivalHeading;
public String toString() {
return String.format("x = %d y = %d arrivalHeader = %d", juncX, juncY, arrivalHeading);
}
}
public class RobotData {
private List<Junction> junctions;
RobotData() {
this.junctions = new ArrayList<Junction>();
}
public void recordJunction(IRobot robot) {
Junction junction = new Junction();
junction.juncX = robot.getLocation().x;
junction.juncY = robot.getLocation().y;
junction.arrivalHeading = robot.getHeading();
junctions.add(junction);
}
}
This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 9 years ago.
I am trying to make a Java package 'mylib' with classes Library{} and Book{}.
Here is the code for class Library{}:
/*
Create collection of books
List books and status
User input:
'B' - Borrow a book
'R' - Reserve a book
'I' - Return a book
'X' - Exit program
*/
package mylib;
public class Library {
public static void main(String[] args) {
Book[] MyBooks = new Book[3];
Book x;
MyBooks[0] = new Book("The Lover's Dictionary", "Levithan, D.", 211);
MyBooks[1] = new Book("White Tiger", "Adiga, A.", 304);
MyBooks[2] = new Book("Thirteen R3asons Why", "Asher, J.", 336);
for (int i = 0; i < MyBooks.length; i++) {
x = MyBooks[i];
System.out.println((i + 1) + " " + x.sTitle);
}
}
}
Here is the code for class Book{}:
package mylib;
class Book {
// Declare fields
byte iStatus;
int iPages;
String sTitle, sAuthor;
String sBorrowedBy, sReservedBy;
String sDueDate, sReturnDate;
public static final byte BORROWED = 0, AVAILABLE = 1, RESERVED = 2;
// Constructor
public Book(String Title, String Author, int Pages) {
this.sTitle = Title;
this.sAuthor = Author;
this.iPages = Pages;
this.iStatus = this.AVAILABLE;
}
// Borrow method
static void borrowBook(String Borrower, String Due) {
if (this.iStatus == this.AVAILABLE) {
this.sBorrowedBy = Borrower;
this.sDueDate = Due;
this.iStatus = this.BORROWED;
} else if (this.iStatus == this.RESERVED
&& this.sReservedBy == Borrower) {
this.sBorrowedBy = Borrower;
this.sDueDate = Due;
this.sReservedBy = "";
this.iStatus = this.BORROWED;
}
}
/*
* static int reserveBook(String Borrower) {
*
* }
*
* static void returnBook(String Return) {
*
* }
*/
}
The partial codes above are given by the professor. I commented out the empty methods and tested the program just to see if it would compile.
I am having 14 errors with the this keyword. Any help?
in this method
static void borrowBook(String Borrower, String Due) {
You cannot use this in a static context
As I see ,there is no need of making that method static.
Prefer to read Understanding Instance and Class Members
You cannot use this in static context , like static methods. Why are you making your borrowBook() method as static. It should be an instance method without the static keyword.
static methods belong to the class and is shared by all its instances. You can invoke them directly using the classname like Book.borrowBook(....) , if this happens the run time will have no idea what/which object this refers to in that context .
Read JLS.3 15.8
The keyword this may be used only in the body of an instance method, instance initializer, or constructor, or in the initializer of an instance variable of a class. If it appears anywhere else, a compile-time error occurs.
In your case better to make the borrowBook() method an instance method as it changes the state of the invoking object i.e. modifies its attributes.Just change the method declaration and remove static:
void borrowBook(String Borrower, String Due) {....... }
Since you are using this in a static context it is giving you the error. Try the following code:
package myLib;
class Book {
// Declare fields
byte iStatus;
int iPages;
String sTitle, sAuthor;
String sBorrowedBy, sReservedBy;
String sDueDate, sReturnDate;
public static final byte BORROWED = 0, AVAILABLE = 1, RESERVED = 2;
// Constructor
public Book(String Title, String Author, int Pages) {
this.sTitle = Title;
this.sAuthor = Author;
this.iPages = Pages;
this.iStatus = Book.AVAILABLE;
}
// Borrow method
//Remove the static keyword
//Refer to the remaining static variables like AVAILABLE OR BORROWED using Book and not this keyword.
void borrowBook(String Borrower, String Due) {
if(this.iStatus == Book.AVAILABLE) {
this.sBorrowedBy = Borrower;
this.sDueDate = Due;
this.iStatus = Book.BORROWED;
}
else if(this.iStatus == Book.RESERVED && this.sReservedBy == Borrower) {
this.sBorrowedBy = Borrower;
this.sDueDate = Due;
this.sReservedBy = "";
this.iStatus = Book.BORROWED;
}
}
}
I suggest you to use IDE to coding since this issue will understand by your own. because error is here use this in a static block.
this keyword is used to refer non-static variables from non-static methods. You are referring to non-static variables from static method.
just change this line :
static void borrowBook(String Borrower, String Due) {
to
public void borrowBook(String Borrower, String Due) {
The goal is to produce this:
Picture of the task summary here
These are the errors I get when I try to compile:
screen shot
I have changed and fixed most of the more obvious errors I think which was mainly just stupid of me. Sorry.
I have this code
public class Ex5Program {
public void start() {
Tutor[] tutors = createTutorsArray();
printTutors(tutors);
printOnLeaveList(tutors);
updateTutorDetails(tutors[1]);
printNewTutorDetails(tutors[1]);
Tutor tutorWithMostPapers = getTutorWithMostPapers(tutors);
printTutorWithMostPapers(tutorWithMostPapers);
}
private Tutor[] createTutorsArray() {
String[] noPapers = {};
String[] introductoryPapers = {"CompSci101", "CompSci111"};
String[] coreStage1Papers = {"CompSci101", "CompSci105"};
String[] allStageOnePapers = {"CompSci111", "CompSci101", "CompSci105"};
String[] stageTwoPapers = {"CompSci210", "CompSci220", "CompSci225", "CompSci230"};
Tutor[] tutors = new Tutor[7];
tutors[5] = new Tutor("Sad Sack", 86302, introductoryPapers, false);
tutors[4] = new Tutor("Crystal Ball", 49123, introductoryPapers, false);
tutors[2] = new Tutor("Earl Lee Riser", 40879, allStageOnePapers, true);
tutors[3] = new Tutor("Tom Katt", 50876, stageTwoPapers, false);
tutors[1] = new Tutor("Candy Kane", 30869, noPapers, false);
tutors[0] = new Tutor("Carrie Oakey", 30987, coreStage1Papers, true);
tutors[6] = new Tutor("Sonny Day", 49586, stageTwoPapers, true);
return tutors;
}
private void printTutors(Tutor[] tutors) {
System.out.println("Current Tutors");
System.out.println("==============");
for (int i = 0; i < tutors.length; i++) {
System.out.print(i + 1 + ". ");
System.out.println(tutors[i].toString());
}
}
private void printOnLeaveList(Tutor[] tutors) {
System.out.println();
System.out.println("Tutors Currently on Leave");
System.out.println("=========================");
for (int i = 0; i < tutors.length; i++) {
if (tutors[i].isOnLeave()) {
System.out.println(tutors[i].getName());
}
}
}
private void updateTutorDetails(Tutor tutor) {
tutor.setName("Ali Katt");
tutor.setStaffId(23456);
String[] stage1Papers = {"CompSci101", "CompSci105", "CompSci111"};
tutor.setPapers(stage1Papers);
tutor.setOnLeave(true);
}
private void printNewTutorDetails(Tutor tutor) {
System.out.println();
System.out.println("Updated details");
System.out.println("===============");
System.out.println("Name: " + tutor.getName());
System.out.println("Id: " + tutor.getStaffId());
String[] papers = tutor.getPapers();
System.out.print("Papers: ");
if (papers.length > 0) {
for (int i = 0; i < papers.length; i++) {
System.out.print(papers[i] + " ");
}
} else {
System.out.print("None");
}
System.out.println();
if (tutor.isOnLeave()) {
System.out.println("Currently on leave");
}
}
private Tutor getTutorWithMostPapers(Tutor[] tutors) {
Tutor tutorWithMostPapersSoFar = tutors[0];
for (int i = 0; i < tutors.length; i++) {
if (tutors[i].teachesMorePapersThan(tutorWithMostPapersSoFar)) {
tutorWithMostPapersSoFar = tutors[i];
}
}
return tutorWithMostPapersSoFar;
}
private void printTutorWithMostPapers(Tutor tutorWithMostPapers) {
System.out.println();
System.out.println("Most papers");
System.out.println("===========");
System.out.println(tutorWithMostPapers.getName() + " teaches more papers than any other tutor.");
}
}
and I created this code here(It has been changed):
public class Tutor {
// instance variables
private String name;
private int staffId;
private String[] papers;
private boolean onLeave;
public Tutor(String name, int staffId, String[] papers, boolean onLeave) {
// Complete this constructor method
this.name = name;
this.staffId = staffId;
this.papers = papers;
this.onLeave = onLeave;
}
// Insert getName() method here
public String getName(){
return name;
}
// Insert setName() method here
public void setName(String name){
this.name = name;
}
// Insert getStaffId() method here
public int getStaff(){
return staffId;
}
// Insert setStaffId() method here
public void setStaffId(int StaffId){
this.staffId = staffId;
}
// Insert getPapers() method here;
public String[] getPapers(){
return papers;
}
// Insert setPapers() method here
public void setPapers(String[] papers){
this.papers = papers;
}
// Insert isOnLeave() method here
public boolean isOnLeave(){
return onLeave;
}
// Insert setOnLeave() method here
public void setOnLeave(boolean OnLeave){
this.onLeave = onLeave;
}
// Insert toString() method here
public String toString(){
return name + "(Staff id:"+staffId+")";
}
// Insert teachesMorePapersThan() method here
public Tutor teachesMorePapersThan(Tutor other){
return(papers.length>other.papers.length);
}
}
Typo: toString() not tostring(), which results in Object.toString() is being invoked and the intended formatted string is not being returned. Change to:
#Override public String toString()
Using the #Override annotation would have produced a compiler error in the case of tostring() being the method name and alerted you to the error, because no method of that name exists in a superclass.
Several of the setter methods have missing parameters:
// Insert setPapers() method here
public void setPapers(){
this.papers = papers;
}
// Insert setOnLeave() method here
public void setOnLeave(){
this.OnLeave = OnLeave;
}
First error: setStaffID()
You are calling it using an int, but on your method you say it doesn't have any parameter.
Take a look that you have some others errors caused by the same mistake. Correct them first...
You need to look at the error text to find the problems. While a newbie may instinctively just dismiss the error messages as uselesss (as a result of years of clicking the x or cancel or whatever on windows dialogues), The error text is actually the most useful resource for figuring out what the error is, 90% of the time.
For instance, the first error reads
File: F:\course related stuff\101\Lab06\Ex5\Ex5Program.java [line: 54]
Error: method setStaffId in class Tutor cannot be applied to given types;
required: no arguments
found: int
reason: actual and formal argument lists differ in length
If you read it carefully, you can see it tells you the name of the file, the line number, the method call name, the class name containing the method, and some additional information about the exact type of error. It is even telling you what you did wrong in calling the method, by putting an "int" where "no arguments" were required, that the "actual and formal argument lists differ in length".
Read the other error messages, and you will see that they actually tell you what the problem is.
This code also needs newlines inserted to group blocks of stuff, comments added to explain exactly how it works, and a few java style violations fixed - some teachers grade for style and clarity as well as just functionality.
Also, if the reason you are failing your class is because you don't understand how to program, it may be because of excessive use of stack overflow to solve the problems. In the real world, if you can just use somebody else's code, that's great, but the point of a programming class is is to teach you how to come up with your own code, not how to use somebody else's.
Well it's not easy to help, because i think you don't know what you are doing. But first thing when you create a set method like this:
public void setPapers(){
this.papers = papers;
}
you should declare the arguments like this:
public void setPapers(String[] papers){
this.papers = papers;
}
and you should know that variables names is caseSensitive so :
private boolean onLeave;
public boolean isOnLeave(){
//return OnLeave; this variable is not declared
return onLeave;
}
I think you need to study a little more, because you can't read the compilation errors.