so i am trying to compile this code and i get : ERROR : variable Laptop might not have been initiated.
public class Computer{
String modelName;
String motherboard;
String systemType;
int ram;
int cpu
int hdd;
public static void main(String[] args){
Computer Laptop;
Laptop.modelName = "M610";
Laptop.motherboard = "MSI";
Laptop.systemType = "Linux";
Laptop.ram = 2048;
Laptop.hdd = 50;
Laptop.cpu = 1500;
System.out.println("Model name:"+Laptop.modelName);
System.out.println("Motherboard:"+Laptop.motherboard);
System.out.println("System type: "+Laptop.systemType);
System.out.println("RAM :"+Laptop.ram);
System.out.println("HDD:"+Laptop.hdd);
System.out.println("CPU :"+Laptop.cpu);
}
}
Thank you very much in advance !
You need to do what the message says: Initialize Laptop.
Replace:
Computer Laptop;
With:
Computer Laptop = new Computer();
The former declares a new variable which the latter initializes it.
Yup as have been said, you need to instantiate the class so you have to do
Computer laptop = new Computer(); // Note lower case laptop as this is how you should define variable names
What you have wrote will do, but have a look at this example. Its more of a "correct way" in java
public class Laptop {
private String modelName;
private String motherboard;
private String systemType;
private int ram;
private int cpu;
private int hdd;
public static void main(String[] args) {
Laptop laptop = new Laptop();
laptop.setModelName("M610");
laptop.setMotherboard("MSI");
laptop.setSystemType("Linux");
laptop.setRam(2048);
laptop.setCpu(50);
laptop.setHdd(1500);
laptop.printResult();
}
public void printResult() {
System.out.println("Model name:" + getModelName());
System.out.println("Motherboard:" +getModelName());
System.out.println("System type: "+ getSystemType());
System.out.println("RAM :" + getRam());
System.out.println("HDD :" + getHdd());
System.out.println("CPU :" + getCpu());
}
public String getModelName() {
return modelName;
}
public void setModelName(String modelName) {
this.modelName = modelName;
}
public String getMotherboard() {
return motherboard;
}
public void setMotherboard(String motherboard) {
this.motherboard = motherboard;
}
public String getSystemType() {
return systemType;
}
public void setSystemType(String systemType) {
this.systemType = systemType;
}
public int getRam() {
return ram;
}
public void setRam(int ram) {
this.ram = ram;
}
public int getCpu() {
return cpu;
}
public void setCpu(int cpu) {
this.cpu = cpu;
}
public int getHdd() {
return hdd;
}
public void setHdd(int hdd) {
this.hdd = hdd;
}
}
There are two ways to solve this problem.
Declare all your fields as static
public class Computer{
static String modelName;
static String motherboard;
.
.
.
In this case there is no need of initialization. Static members belong to a class rather than to a specific initialization or an instance of it.
Access them as Computer.your-filedname.
However if you want to declare an object.
You can just change this line
Computer Laptop;
to this
Computer Laptop = new Computer();
i.e. you initialize your object before assigning your fields' values in subsequent lines.
Related
package staticassignment3;
public class Booking {
private String customerEmail;
private int seatsRequired;
private static int seatsAvailable;
private boolean isBooked;
static {
seatsAvailable = 400;
}
public Booking(String customerEmail, int seatsRequired) {
this.customerEmail = customerEmail;
this.seatsRequired = seatsRequired;
}
public String getCustomerEmail() {
return this.customerEmail;
}
public void setCustomerEmail(String customerEmail) {
this.customerEmail= customerEmail;
}
public int getSeatsRequired() {
return this.seatsRequired;
}
public void setSeatsRequired(int seatsRequired) {
this.seatsRequired = seatsRequired;
}
public static int getSeatsAvailable() {
return Booking.seatsAvailable;
}
public static void setSeatsAvailable(int seatsAvailable) {
Booking.seatsAvailable = Booking.seatsAvailable - this.seatsRequired;
}
public boolean isBooked() {
if(Booking.seatsAvailable>= this.seatsRequired) {
Booking.setSeatsAvailable(seatsAvailable);
this.isBooked = true;
}
else {
this.isBooked = false;
}
return isBooked;
}
}
In the above Booking class, I want to update the static variable seatsAvailable by using the static method setSeatsAvailable but I am passing a nonstatic variable in it i.e this.seatsRequired which is not permitted. Is there any alternative to update the seatsAvailable without changing the code so much?
package staticassignment3;
public class Tester {
public static void main(String[] args) {
Booking booking1 = new Booking("jack#email.com", 100);
Booking booking2 = new Booking("jill#email.com", 350);
Booking[] bookings = { booking1, booking2 };
for (Booking booking : bookings) {
if (booking.isBooked()) {
System.out.println(booking.getSeatsRequired()+" seats successfully booked for "+booking.getCustomerEmail());
} else {
System.out.println("Sorry "+booking.getCustomerEmail()+", required number of seats are not available!");
System.out.println("Seats available: "+Booking.getSeatsAvailable());
}
}
}
}
in above Booking class i want to update seatsAvailable static variable by using setSeatsAvailable static method but i am passing nonstatic varible in it i.e this.seatsRequired which is not permitted.is there any alternate to achive the updated seatsAvailable static varibale without doing major changes in code
When calling a static method, there is no assocated object instance. So, it is not valid to use this inside a static method, since this refers to the current object (but you have none).
Specfically, this method isn't correct:
public static void setSeatsAvailable(int seatsAvailable) {
Booking.seatsAvailable = Booking.seatsAvailable - this.seatsRequired;
}
If you want to keep the method static, you could pass an additional parameter to the method – an instance of Booking – and then replace this.seatsRequired with booking.seatsRequired, like this:
public static void setSeatsAvailable(int seatsAvailable, Booking booking) {
Booking.seatsAvailable = Booking.seatsAvailable - booking.seatsRequired;
}
I am trying to sort an ArrayList in increasing order in reference to a certain variable. This is the problem question.
q5: Create a public class named Snow with private instance variables vast, prior, ethnic, and remarkable each of type int. You may add any other methods and variables you'd like to this class.
Outside of Snow (in the Problem Set class) write a public static method named sortSnow that takes an ArrayList of Snows as a parameter and returns void. This method will sort the input by the variable remarkable in increasing order
This is what I wrote.
public class snow implements Comparable<snow> {
private int vast;
private int prior;
private int ethnic;
private int remarkable;
public snow( int vast , int prior, int ethnic ,int remarkable) {
this.vast=vast;
this.prior = prior;
this.ethnic = ethnic;
this.remarkable = remarkable;
}
public int getEthnic() {
return ethnic;
}
public void setEthnic(int ethnic) {
this.ethnic = ethnic;
}
public int getPrior() {
return prior;
}
public void setPrior(int prior) {
this.prior = prior;
}
public int getVast() {
return vast;
}
public void setVast(int vast) {
this.vast = vast;
}
public int getRemarkable() {
return remarkable;
}
public void setRemarkable(int remarkable) {
this.remarkable = remarkable;
}
public int compareTo(snow compareSnow) {
// TODO Auto-generated method stub
int compareThese = ((snow) compareSnow).getRemarkable();
//ascending order
return this.remarkable - compareThese;
}
}
public static void sortSnow(ArrayList<snow>input){
Collections.sort(input);
}
I am not understanding what the error means. The autolab is giving me this error:
Could not find class submission.ProblemSet$Snow
Java is case sensitive i.e. snow is not Snow is not sNoW. Rename your class to Snow and try again. Also, it is ArrayList and not arraylist.
Then to sort a List, you can use Collections.sort.
I think this is you want to achieve
Save below code in file called "Snow.java" compile it and try to run it.
import java.util.ArrayList;
import java.util.Collections;
//As ".java" file can contain only single public java class
//I made Problem set class non-public so we can use its main method
//to run and see output
class ProblemSet {
public static void main(String[] args) {
Snow one = new Snow(1,1,1,1);
Snow two = new Snow(1,1,1,2);
Snow three = new Snow(1,1,1,3);
Snow four = new Snow(1,1,1,4);
Snow five = new Snow(1,1,1,5);
Snow six = new Snow(1,1,1,6);
ArrayList arrayList = new ArrayList();
arrayList.add(one);
arrayList.add(three);
arrayList.add(five);
arrayList.add(two);
arrayList.add(six);
arrayList.add(four);
System.out.println("Without sort");
System.out.println(arrayList);
sortSnow(arrayList);
System.out.println("With sort");
System.out.println(arrayList);
}
//this is your static method which takes argument as array list of Snow
//And it applies sorting logic based on compareTo method which you wrote
//in Snow class. As per java best practice Class name should start with
//Upper case letters and follow camel casing I renamed your class from
//"snow" to "Snow"
public static void sortSnow(ArrayList<Snow> input){
Collections.sort(input);
}
}
//This is you public class Snow
//If you want to keep it in separate java file put it
public class Snow implements Comparable<Snow> {
private int vast;
private int prior;
private int ethnic;
private int remarkable;
public Snow(int vast, int prior, int ethnic, int remarkable) {
this.vast = vast;
this.prior = prior;
this.ethnic = ethnic;
this.remarkable = remarkable;
}
public int getEthnic() {
return ethnic;
}
public void setEthnic(int ethnic) {
this.ethnic = ethnic;
}
public int getPrior() {
return prior;
}
public void setPrior(int prior) {
this.prior = prior;
}
public int getVast() {
return vast;
}
public void setVast(int vast) {
this.vast = vast;
}
public int getRemarkable() {
return remarkable;
}
public void setRemarkable(int remarkable) {
this.remarkable = remarkable;
}
public int compareTo(Snow compareSnow) {
// TODO Auto-generated method stub
int compareThese = ((Snow) compareSnow).getRemarkable();
//ascending order
return this.remarkable - compareThese;
}
//This is added because when you use array list to print
//it will print remarkable of particular Snow object
#Override
public String toString() {
return String.valueOf(remarkable);
}
}
May be the Title isn't a specific one, I just don't know how to call it. I will explain you in detail
I have these classes:
public class ChannelComponent {
private String name;
private String mode; //(1P1C / XPXC / 1PXC)
private List<SourceProvidedPort> publishers = new ArrayList<SourceProvidedPort>();
private List<SinkRequiredPort> subscribers = new ArrayList<SinkRequiredPort>();
public ChannelComponent(String name, String mode) {
this.name = name;
this.mode = mode;
}
public boolean canISubscribe(SinkRequiredPort newPort) {
if ((mode.equals("1P1C") || mode.equals("1PXC")) && subscribers.size() < 1) {
subscribers.add(newPort);
return true;
} else if (mode.equals("XPXC")) {
subscribers.add(newPort);
return true;
}
return false;
}
public String getName() {
return name;
}
public String getMode() {
return mode;
}
public void printChannel() {
System.out.println("[" + name + "," + mode + "]" + "\n");
}
}
TestCentralRegistry
public class TestCentralRegistry {
private List<ChannelComponent> channels = new ArrayList<ChannelComponent>();
public void addChannelComponent(ChannelComponent c) {
channels.add(c);
}
public static void main(String... args) {
TestCentralRegistry demo = new TestCentralRegistry();
demo.addChannelComponent(new ChannelComponent("channel1", "1P1C"));
demo.addChannelComponent(new ChannelComponent("channel2", "XPXC"));
}
}
In the TestCentralRegistry class I created 2 channelComponents, these channels I would like to compare their mode value in the method canISubscribe (located in the ChannelComponent class). But how come, I could retrieve the values created in the TestCentralRegistry to read them in the ChannelComponent class?
what am I missing?
Because, from another class TestChannel I'm going to have a ChannelComponent reference, invoke the method canISubscribe
public class TestChannel {
ChannelComponent channelComponent;
public void callSubscribe(SinkRequiredPort newPort){
channelComponent.canISubscribe(newPort);
}
public static void main(String... args) {
TestChannel testChannel = new TestChannel();
SinkRequiredPort sinkPort = new SinkRequiredPort();
sinkPort.setWantsUse("channel1");
testChannel.callSubscribe(sinkPort);
}
}
And I need to compare the values, created in the TestCentralRegistry and TestChannel to see if there is a matching. I know that I still need to add some lines like getting the value from the newPort.getWantsUse(); and compare it with the channelComponent name ... but still I need the value created in the TestCentralRegistry
I hope my question is clear
Any suggestions?
Thank you in advance
Try holding a reference to TestCentralRegistry in ChannelComponent.
public class ChannelComponent {
private String name;
private String mode; //(1P1C / XPXC / 1PXC)
private List<SourceProvidedPort> publishers = new ArrayList<SourceProvidedPort>();
private List<SinkRequiredPort> subscribers = new ArrayList<SinkRequiredPort>();
private TestCentralRegistry testCentralRegistry;
public ChannelComponent(String name, String mode) {
this.name = name;
this.mode = mode;
}
public void registerTestCentralRegistry( TestCentralRegistry testCentralRegistry) {
this.testCentralRegistry = testCentralRegistry;
}
}
Register your TestCentralRegistry as shown below:
public class TestCentralRegistry {
private List<ChannelComponent> channels = new ArrayList<ChannelComponent>();
public void addChannelComponent(ChannelComponent c) {
channels.add(c);
}
public static void main(String... args) {
TestCentralRegistry demo = new TestCentralRegistry();
ChannelComponent cc1 = new ChannelComponent("channel1", "1P1C");
cc1.registerTestCentralRegistry( demo);
ChannelComponent cc2 = new ChannelComponent("channel2", "XPXC");
cc2.registerTestCentralRegistry( demo);
demo.addChannelComponent( cc1);
demo.addChannelComponent( cc2);
}
}
Then, you can retrieve the values created in the TestCentralRegistry by calling testCentralRegistry.getX() from ChannelComponent.
Here is what I have so far so as you can see I made a class for the powerup but I just keep getting stuck over and over again and ended up getting frustrated cause I couldn't figure it out myself.
public class Superhero {
private int heroStr;
public int powerUp;
private String name;
public Superhero(String name, int heroStr) {
this.name = name;
this.heroStr = heroStr;
System.out.println(name + " Strength is " + heroStr);
}
public Superhero(String name) {
this.name = name;
heroStr = 10;
System.out.println(name + " Strength is " + heroStr);
}
public int getStr() {
return heroStr;
}
public int powerUp(int powerUp) {
}
public static void main (String[] args) {
Superhero Gambit = new Superhero("Gambit");
Superhero Groot = new Superhero("Groot", 79);
}
}
Here you are:
public void powerUp(int powerUp){
//this.powerUp is the powerUp in your class, the powerUp without "this" is the powerUp given to the method
this.powerUp+=powerUp;
}
All you need now is to change your powerUp method:
public void powerUp(int powerUp) {
this.heroStr += powerUp;
}
and since you instantiated the superheroes, all you need is to call their methods, ex:
public static void main(String args[]){
SuperHero gambit = new SuperHero("Gambit",10);
gambit.powerUp(10);
System.out.println(gambit.getStr()); //should be 20
}
Also, as a side note:
the correct naming convention for variable names is:
Class object = new Class();
Can anyone tell me how to count the number of instances of a class?
Here's my code
public class Bicycle {
//instance variables
public int gear, speed, seatHeight;
public String color;
//constructor
public Bicycle(int gear, int speed, int seatHeight, String color) {
gear = 0;
speed = 0;
seatHeight = 0;
color ="Unknown";
}
//getters and setters
public int getGear() {
return gear;
}
public void setGear(int Gear) {
this.gear = Gear;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int Speed){
this.speed = Speed;
}
public int getSeatHeight() {
return seatHeight;
}
public void setSeatHeight(int SeatHeight) {
this.seatHeight = SeatHeight;
}
public String getColor() {
return color;
}
public void setColor(String Color) {
this.color = Color;
}
}//end class
public class Variable extends Bicycle {
public Variable(int gear, int speed, int seatHeight, String color) {
super(gear, speed, seatHeight, color);
}
}//end class
public class Tester {
public static void main(String args[]){
Bicycle bicycle1 = new Bicycle(0, 0, 0, null);
bicycle1.setColor("red");
System.out.println("Color: "+bicycle1.getColor());
bicycle1.setSeatHeight(4);
System.out.println("Seat Height: "+bicycle1.getSeatHeight());
bicycle1.setSpeed(10);
System.out.println("Speed: "+bicycle1.getSpeed());
bicycle1.setGear(6);
System.out.println("Gear: "+bicycle1.getGear());
System.out.println("");//space
Bicycle bicycle2 = new Bicycle(0, 0, 0, null);
bicycle2.setColor("black");
System.out.println("Color: "+bicycle2.getColor());
bicycle2.setSeatHeight(6);
System.out.println("Seat Height: "+bicycle2.getSeatHeight());
bicycle2.setSpeed(12);
System.out.println("Speed: "+bicycle2.getSpeed());
bicycle2.setGear(6);
System.out.println("Gear: "+bicycle2.getGear());
System.out.println("");//space
}//end method
}//end class
The class variable is to be used to keep count of the number of instances of the Bicycle class created and the tester class creates a number of instances of the Bicycle class and demonstrates the workings of the Bicycle class and the class variable. I've looked all over the internet and I can't seem to find anything, could someone show me how to do it please, thanks in advance :)
Since static variables are initialized only once, and they're shared between all instances, you can:
class MyClass {
private static int counter;
public MyClass() {
//...
counter++;
}
public static int getNumOfInstances() {
return counter;
}
}
and to access the static field counter you can use MyClass.getNumOfInstances()
Read more about static fields in the JLS - 8.3.1.1. static Fields:
If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized (§12.4).
Note that counter is implicitly set to zero
Pleae try the tool of java
jmap -histo <PDID>
Out put
num #instances #bytes class name
----------------------------------------------
1: 1105141 97252408 java.lang.reflect.Method
2: 3603562 86485488 java.lang.Double
3: 1191098 28586352 java.lang.String
4: 191694 27035744 [C
In addition, you should override finalize method to decrement the counter
public class Bicycle {
...
public static int instances = 0;
{
++instances; //separate counting from constructor
}
...
public Bicycle(int gear, int speed, int seatHeight, String color) {
gear = 0;
speed = 0;
seatHeight = 0;
color ="Unknown";
}
#Override
protected void finalize() {
super.finalize();
--instances;
}
}
You should have in mind that static variables are CLASS scoped (there is no one for each instance, only one per class)
Then, you could demonstrate instance decrement with:
...
System.out.println("Count:" + Bicycle.getNumOfInstances()); // 2
bicycle1 = null;
bicycle2 = null;
System.gc(); // not guaranteed to collect but it will in this case
Thread.sleep(2000); // you expect to check again after some time
System.out.println("Count again:" + Bicycle.getNumOfInstances()); // 0
why not using a static counter?
public class Bicycle {
private static int instanceCounter = 0;
//instance variables
public int gear, speed, seatHeight;
public String color;
//constructor
public Bicycle(int gear, int speed, int seatHeight, String color) {
gear = 0;
speed = 0;
seatHeight = 0;
color ="Unknown";
instanceCounter++;
}
public int countInstances(){
return instanceCounter;
}
........
You just need static counter in class.
public class Bicycle {
private static volatile int instanceCounter;
public Bicycle() {
instanceConter++;
}
public static int getNumOfInstances() {
return instanceCounter;
}
protected void finalize() {
instanceCounter--;
}
}
As mentioned in many comments finalize() is not recommended to use so there could be another approach to count the Bicycle instances -
public class Bicycle {
private static final List<PhantomReference<Bicycle>> phantomReferences = new LinkedList<PhantomReference<Bicycle>>();
private static final ReferenceQueue<Bicycle> referenceQueue = new ReferenceQueue<Bicycle>();
private static final Object lock = new Object();
private static volatile int counter;
private static final Runnable referenceCleaner = new Runnable() {
public void run() {
while (true) {
try {
cleanReferences();
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
static {
Thread t = new Thread(referenceCleaner);
t.setDaemon(true);
t.start();
}
private Bicycle() {
}
public static Bicycle getNewBicycle() {
Bicycle bicycle = new Bicycle();
counter++;
synchronized (lock) {
phantomReferences.add(new PhantomReference<Bicycle>(new Bicycle(), referenceQueue));
}
System.out.println("Bicycle added to heap, count: " + counter);
return bicycle;
}
private static void cleanReferences() {
try {
PhantomReference reference = (PhantomReference) referenceQueue.remove();
counter--;
synchronized (lock) {
phantomReferences.remove(reference);
}
System.out.println("Bicycle removed from heap, count: " + counter);
} catch (Exception e) {
e.printStackTrace();
}
}
public static int getNumOfBicycles() {
return counter;
}
}
public class BicycleTest {
public static void main(String[] args) {
int i = 0;
while (i++ < 1000) {
Bicycle.getNewBicycle();
}
while (Bicycle.getNumOfBicycles() > 0) {
try {
Thread.sleep(1000);
System.gc(); // just a request
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Alternatively, you can create a counter with an initializer block and a static variable.
class SomeClass
{
private static int instanceCounter;
{
instanceCounter++;
}
}
Initializer blocks get copied by the compiler into every constructor, so, you will have to write it once no matter how many constructors you will need (As referred into the above link). The block in {} runs every time you create a new object of the class and increases the variable counter by one.
And of course get the counter by something like:
public static int getInstanceCounter()
{
return instanceCounter;
}
or directly
int numOfInstances = SomeClass.instanceCounter;
If you do not make numOfInstances private
One basic approach is to declare a static numeric member field thats incremented each time the constructor is invoked.
public class Bicycle {
//instance variables
public int gear, speed, seatHeight;
public String color;
public static int bicycleCount = 0;
//constructor
public Bicycle(int gear, int speed, int seatHeight, String color) {
gear = 0;
speed = 0;
seatHeight = 0;
color ="Unknown";
bicycleCount++;
}
...
}
If you want to count and test instances based on the number of objects created, you can use a loop to see what really is happening. Create a constructor and use a static counter
public class CountInstances {
public static int count;
public CountInstances() {
count++;
}
public int getInstaces() {
return count;
}
public static void main(String []args) {
for(int i= 0; i<10; i++) {
new CountInstances();
}
System.out.println(CountInstances.count);
}
}
public class Number_Objects {
static int count=0;
Number_Objects(){
count++;
}
public static void main(String[] args) {
Number_Objects ob1=new Number_Objects();
Number_Objects ob2=new Number_Objects();
Number_Objects obj3=new Number_Objects();
System.out.print("Number of objects created :"+count);
}
}