when I go to print out the array, it prints the value for the last object called for. How can i get it to print out the different objects in the array? I think there is an error in the method I use to call upon the location of the object's variables stored in the array.
class Recorder4 {
int xPos, yPos;
String eventType;
final int EVENT_MAX = 10;
EventInformation[] event = new EventInformation [EVENT_MAX]; //this is the array
int xevent = 0;
Recorder4 (int xPos, int yPos, String eventType) {
this.xPos = xPos;
this.yPos = yPos;
this.eventType = eventType;
}
public void recordEvent (String Time, int Datum) {
if (xevent <= EVENT_MAX) {
event[xevent] = new EventInformation(Time, Datum);
xevent++; //this is where new instances of the object are assigned a place in the array
}
else {System.out.println("Event log overflow - terminating");
System.exit(1);}
}
void printEvents() {
System.out.println("Record of " + eventType +
" events at [" + xPos + ","+ yPos + "]");
for (int i = 0; i < xevent; i++) {
System.out.println("Event number " +
i + " was recorded at " + event[i].getTime() //i think these methods is where the issue lies
+ " with datum = " + event[i].getDatum());
}
}
}
class EventInformation {
static String eventTime;
static int eventDatum;
EventInformation (String s, int i) {
eventTime = s;
eventDatum = i;}
public int getDatum() {
return EventInformation.eventDatum;}
public String getTime() {
return EventInformation.eventTime;}
}
The problem might be in how you are defining your class variables. In your EventInformation class you are defining them as static:
static String eventTime;
static int eventDatum;
This means there will only be ONE copy of each of these variables no matter how many EventInformation instances you create (ie they will all share the same copy).
Try removing the static keyword from the variable declarations to see if that resolves your issue.
Related
I am creating a class called "Crate" that will read an input file of integers representing objects dimensions in inches and output a report containing the crate sizes required for each respective item. Everything seemed fine until I tried to test my methods, as I am unable to call them from main(). When trying, I get an error message saying, "non-static method createReport() cannot be referenced from a static context."
I am a beginner, so if anything is fundamentally wrong I will happily accept criticism. I am just curious if there is a simple fix to this and what my gap in knowledge is regarding static/non-static methods.
package crate;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Crate {
private Crate[] crateList;
private int crateAmount;
private int height, width, depth, panels;
private int smallestCratePosition, smallestCrateSize;
private int largestCratePosition, largestCrateSize;
private double averageCrateSize;
public static void main(String[] args) throws IOException {
createReport();
}
public Crate() {
height = 1;
width = 1;
depth = 1;
panels = 6;
}
public void createReport() throws IOException {
Scanner infile = new Scanner(new File("ShippingSizes.txt"));
PrintWriter outfile = new PrintWriter(new File("CrateReport.txt"));
createCrateList(infile);
outfile.println("There are " + crateAmount + " crates.");
for (int i = 0; i < crateList.length; i++) {
outfile.println(i + ": height=" + crateList[i].getHeight() + ", width=" +
crateList[i].getWidth() + ", depth=" + crateList[i].getDepth() +
", panels=" + crateList[i].getPanels());
}
outfile.println("\n" + "Smallest crate is at " + smallestCratePosition +
": height=" + crateList[smallestCratePosition].getHeight() + ", width=" +
crateList[smallestCratePosition].getWidth() + ", depth=" +
crateList[smallestCratePosition].getDepth() + ", panels=" +
crateList[smallestCratePosition].getPanels());
outfile.println("Largest crate is at " + largestCratePosition + ": height," +
crateList[largestCratePosition].getHeight() + ", width=" +
crateList[largestCratePosition].getWidth() + ", depth=" +
crateList[largestCratePosition].getDepth() + ", panels=" +
crateList[largestCratePosition].getPanels());
outfile.println("Average crate size is: " + averageCrateSize);
outfile.close();
infile.close();
}
public void setCrateDimensions(Scanner scnr) {
int tempValue = scnr.nextInt();
height = tempValue/12;
if (tempValue%12 != 0)
height++;
tempValue = scnr.nextInt();
width = tempValue/12;
if (tempValue%12 != 0)
width++;
tempValue = scnr.nextInt();
depth = tempValue/12;
if (tempValue%12 != 0)
depth++;
panels = 2*((height*width)+(height*depth)+(width*depth));
}
public void createCrateList(Scanner scnr) {
crateAmount = scnr.nextInt();
for (int i = 0; i < crateAmount; i++) {
crateList[i].setCrateDimensions(scnr);
}
}
public void getSmallestCrate() {
smallestCrateSize = crateList[0].getPanels();
for (int i = 0; i < crateList.length; i++) {
if (crateList[i].getPanels() < smallestCrateSize) {
smallestCratePosition = i;
smallestCrateSize = crateList[i].getPanels();
}
}
}
public void getLargestCrate() {
largestCrateSize = crateList[0].getPanels();
for (int i = 0; i < crateList.length; i++) {
if (crateList[i].getPanels() > largestCrateSize) {
largestCratePosition = i;
largestCrateSize = crateList[i].getPanels();
}
}
}
public void getAverageCrateSize() {
double totalPanels = 0;
for (int i = 0; i < crateList.length; i++)
totalPanels += crateList[i].getPanels();
averageCrateSize = totalPanels / (double)(crateList.length);
}
public int getHeight() {
return height;
}
public int getWidth() {
return width;
}
public int getDepth() {
return depth;
}
public int getPanels() {
return panels;
}
}
I tried declaring the Scanner, PrintWriter, Crate[] object, and crateAmount integer inside of main(), however this only led to the same issue later on as I was unable to use those variables in my methods. Any help would be greatly appreciated!
because the createReport method is related to it's instance of Class Crate.
you must create an instance by new keywords, then you can call it's method createReport.
another way, if you don't want create an instance of class, you can declared method to static method by keyword static. then the method will be load when starting the jvm.
suggestion: you should deeply understand the OOP programming by reading an book or another article
Non-static methods belong to an instance of a class, not the class itself. This is why you can't access the createReport() method from main(), because main is in the static scope, while createReport is not. Try instantiating an instance of the class and calling createReport() on the object.
For example:
Crate crate = new Crate();
crate.createReport();
I am thinking I need to do some type casting to get the fan to output toString,
to output strings for my speed instead of 1, 2, and 3. I am not sure where I can makes those changes, either being sent in the test class or moving to private in the fan class. I have tried to add some calls in the toString but I am getting the hex decimal result. Some different ways to come around this would be really helpful.
public class Fan {
public final int SLOW = 1;
public final int MEDIUM = 2;
public final int FAST = 3;
private int speed; // = SLOW;
private boolean on; // on = false;
private double radius; // radius = 5;
private String color; // = "white";
public int getSpeed ( ) {return speed; }
public void setSpeed ( int speed ) { this.speed = speed; }
public boolean isOn ( ) {return on; }
public void setOn ( boolean on) {this.on = on; }
public double getRadius ( ) {return radius; }
public void setRadius ( double radius ) { this.radius = radius; }
public String getColor ( ) { return color; }
public void setColor ( String color ) { this.color = color; }
public Fan ( ) {
System.out.println("Default constructor called");
}
// default constructor
public Fan ( int speed, boolean on, double radius, String color ) {
this.speed = speed;
this.on = on;
this.radius = radius;
this.color = color;
System.out.println("Overloaded constructor called");
}
//overloaded constructor
public String toString () {
String x = "speed is " + speed + ", is the fan turned on? " + on + ",the radius "
+ "of the blades are " + radius + ", and the color of the fan is " + color;
return x;
}
}
public class FanTest {
public static void main(String[] args) {
Fan f1 = new Fan( 3, true, 10, "Yellow" ) ;
Fan f2 = new Fan();
Fan f4 = new Fan();
f1.equals(f4) ;
Fan f3 = f1;
int slow = 1;
int medium = 2;
int fast = 3;
System.out.println(f1);
System.out.println(f2);
System.out.println(f3);
if (f1.equals(f3)) {
System.out.println("Obejects r3 and r1 are the same\n");
} else {
System.out.println("Objects r3 and r1 are different");
}
while (f1.equals(f4))
f4.setOn(false);
f4.setSpeed(2);
f4.setColor("green");
f4.setRadius(8);
System.out.println(f4);
}
}
First, in the default constructor no variables are set. This means that any Fan object created with the default constructor is in an invalid state (e.g. speed is 0 by default). I suggest you to uncomment line 9-12:
private int speed = SLOW;
private boolean on = false;
private double radius = 5;
private String color = "white";
You said you wanted to "output strings for my speed instead of 1, 2, and 3". This can easily be achieved using if..else or switch.
if (speed == 1) {
str = str + " slow ";
} else if (speed == 2) {
str = str + " medium ";
} else if (speed == 3) {
str = str + " fast ";
}
Using switch:
switch (speed) {
case 1:
str = str + " slow ";
break;
case 2:
str = str + " medium ";
break;
case 3:
str = str + " fast ";
break;
}
About f1.equals(f4): These are different objects, so it is never true.
About equals: equals is a method defined in the class Object, so it can be used on any object. But unless you override it, it checks for identity, witch means that
a.equals(b)
always returns the same as
a == b
I need to write a function to College department :
Add function adds additional lecturer.
Action returns false if there is no place to add additional lecturer, and at the same true if the lecturer was successfully added.
What I had written so far:
public boolean newLecturer(Lecturer[] AllLecturer) {
int MaxLecturer = 0;
MaxLecturer = this.maxLecturer;
int sum = 0;
sum += 1;
if (sum < MaxLecturer) {
System.out.println("true");
return true;
}
else {
System.out.println("false");
return false;
}
}
The function does not work properly, It always returns true (because that the Max Lecturer always bigger than sum).
main:
public class main {
public static void main(String[]args){
Lecturer[] L1 = new Lecturer[]{new Lecturer("David",3,"Banana",1001)};
Lecturer[] L2 = new Lecturer[]{new Lecturer("Yossi",5,"apple",1002)};
Lecturer[] L3 = new Lecturer[]{new Lecturer("Y",2,"t",1003)};
College myCollege = new College("College1",20,L1,3);
//System.out.println(myCollege);
//myCollege.allLecturer=L2;
//System.out.println(myCollege);
myCollege.newLecturer(L1);
myCollege.newLecturer(L2);
myCollege.newLecturer(L3);
}
}
class College (Function here):
public class College {
public String name;
public int numOfLecturer;
public Lecturer[] allLecturer;
public int maxLecturer;
// constructor
public College(String Name, int NumOfLecturer, Lecturer[] AllLecturer,
int MaxLecturer) {
this.name = Name;
this.numOfLecturer = NumOfLecturer;
this.allLecturer = AllLecturer;
this.maxLecturer = MaxLecturer;
}
public College(String Name) {
this.name = Name;
}
public College(Lecturer[] AllLecturer) {
this.allLecturer = AllLecturer;
}
public boolean newLecturer(Lecturer[] AllLecturer) {
int MaxLecturer = 0;
MaxLecturer = this.maxLecturer;
int sum = 0;
sum += 1;
if (sum < MaxLecturer) {
System.out.println("true");
return true;
}
else {
System.out.println("false");
return false;
}
}
#Override
public String toString() {
String lecturers = "";
for (Lecturer lecturer : allLecturer) {
lecturers += lecturer;
}
return "[Name College: " + name + "] " + " [num Of Lecturer: "
+ numOfLecturer + "]" + " [all Lecturer: " + lecturers + "]"
+ " [max Lecturer " + maxLecturer + "]";
}
}
class Lecturer:
public class Lecturer {
public String name;
public int numOfTimesPenFalls;
public String favoriteIceCream;
public int autoNumber;
// constructor
public Lecturer(String Name, int NumOfTimesPenFalls,
String FavoriteIceCream, int AutoNumber) {
this.name = Name;
this.numOfTimesPenFalls = NumOfTimesPenFalls;
this.favoriteIceCream = FavoriteIceCream;
this.autoNumber = AutoNumber;
}
public Lecturer(String Name) {
this.name = Name;
}
#Override
public String toString() {
return "[name: " + name + "] " + " [num Of Times Pen Falls: "
+ numOfTimesPenFalls + "] " + " [favorite Ice Cream: "
+ favoriteIceCream + "] " + " [auto Number: " + autoNumber
+ "]";
}
}
And finally how can I print it?
Like this gives a compiler error:
myCollege.newLecturer("David",2,"Apple",1004);
thank you.
You're new; you need a lot of help.
Start by learning and following Java coding standards. Variable names should start with lower case. Classes start with upper. Deviations from that make your code hard to read.
Your method is wrong. You need something like this inside that class:
private static final int MAX_LECTURERS = 3;
private int numLecturers = 0;
private Lecturer [] lecturers = new Lecturer[MAX_LECTURERS];
public boolean addLecturer(Lecturer lecturer) {
boolean addedLecturer = false;
if (this.numLecturers < MAX_LECTURERS) {
this.lecturers[numLecturers++] = lecturer;
addedLecturer = true;
}
return addedLecturer;
}
Here's how you use this method:
Lecturer newLecturer = new Lecturer("foo", 1, "bar", 3);
college.addLecturer(newLecturer);
Please stop with all that array nonsense. The array is inside the College class.
The sum variable in your code is a local variable, its scope is only at the function level. This means the sum always get initialized to 0 and increased to 1 every time the function newLecturer() is called. That's why sum always smaller than MAX_LECTURER (1<3).
You need to use class variable numLecturers like in duffymo answer above.
I try to determine the error since yesterday, but did not find him. All I know is where he must be placed approximately. But now to the topic.
For my app I have created a separate class with the name Player. Now if I make an ArrayList with this class, a newly added object overwrites all existing objects. So:
ArrayList empty -> Player is stored in ArrayList
ArrayList already contains a Player -> ArrayList now contains the newest Player instance two times
etc.
Here is my code corresponding to:
Player Object
public Player(String n, int m, int t) {
name = n;
money = m;
tip = t;
}
public String getName() {
return this.name;
}
public int getMoney() {
return this.money;
}
public int getTip() {
return this.tip;
}
public String toString() {
return this.name + "\n Tipp: " + this.tip + " | Einsatz: " + this.getMoney() + " ,- €";
}
Creating the ArrayList
public void addPlayertoEvent(String name, int money, int tip) {
Player p = new Player(name, money, tip);
playerList.add(p);
playerListString.add(p.toString());
lvPlayers.setAdapter(null);
ArrayAdapter<String> playerAdapter = new ArrayAdapter<String>(AddEventActivity.this, R.layout.list_items, playerListString);
lvPlayers.setVisibility(View.VISIBLE);
lvPlayers.setAdapter(playerAdapter);
etTip.setText("");
etName.setText("");
for(int i = 0; i < playerList.size(); ++i) {
Log.e("AL", "" + playerList.get(i).getName() + " " + playerList.get(i).getMoney() + " " + playerList.get(i).getTip());
}
}
I'm pretty new in java and I'm doing a simple program but I don't know why I get different values, i.e., if I use getX, getY and getZ I get (6,5,8) but if I use toString I get different values for X and Y (3, 4, 8), so can anyone explain me why it happens because as far as I understand it should get the same values in both cases or what I'm doing wrong?
public class Coordinates {
private double coorX, coorY;
Coordinates()
{
coorX = 1;
coorY = 1;
}
Coordinates(double x, double y)
{
coorX = x;
coorY = y;
}
void setX(double x)
{
coorX = x;
}
void setY(double y)
{
coorY = y;
}
double getX()
{
return coorX;
}
double getY()
{
return coorY;
}
public String toString()
{
String myString = "(" + coorX + " , " + coorY + ")";
return myString;
}
public class Coordinates3D extends Coordinates{
private double coorZ;
Coordinates3D()
{
super();
coorZ = 1;
}
Coordinates3D(double x, double y, double z)
{
super(x,y);
coorZ = z;
}
public void setZ(double z)
{
coorZ = z;
}
double getZ()
{
return coorZ;
}
#Override
public String toString()
{
String myString = "(" + coorX + " , " + coorY + " , " + coorZ + ")" ;
return myString;
}
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Coordinates test1 = new Coordinates(3,4);
System.out.println(test1.toString());
System.out.println(test1.getX());
System.out.println(test1.getY());
Coordinates3D test2 = test1.new Coordinates3D(6,5,8);
System.out.println(test2.toString()); ---> here is the problem
System.out.println(test2.getX());
System.out.println(test2.getY());
System.out.println(test2.getZ());
}
}
First there is a problem on how you define the visibility of the fields of the super class:
public class Coordinates {
//defines as private
//sub classes cannot access to these fields directly
private double coorX, coorY;
This is that you cannot invoke super.coorX nor super.coorY on any sub class e.g. Coordinates3D. So, in toString method, when you have this code:
String myString = "(" + coorX + " , " + coorY + " , " + coorZ + ")" ;
It compiles and runs fine because Coordinates3D is an inner class. So, when using coorX here it's accessing to the value of coorX field stored in the instance of Coordinates class that created the instance of Coordinates3D. This can be easy to replicate if you separate the classes:
class Coordinates {
private double coorX, coorY;
}
public class Coordinates3D extends Coordinates {
//current code...
#Override
public String toString() {
//now you will get a compilaton error
String myString = "(" + coorX + " , " + coorY + " , " + coorZ + ")" ;
return myString;
}
}
The best solution would be:
mark the fields in the super class as protected
separate the classes
If you still want to keep Coordinates3D as inner class (not recommended), then:
mark the fields in the super class as protected
use super.coorX and super.coorY to not have the same unexpected behavior.
I would like to add to the existing answers that even in the class, you should not read the fields firectly, but use their getters.
#Override
public String toString() {
String myString = "(" + getX() + " , " + getY() + " , " + getZ() + ")";
return myString;
}
This also fixes the problem, but you should still not make the Coordinates3D class an inner class of Coordinates.