Instance Counter for a String - Java - java

String
name of the car. The name is formed by concatenating the word “Car” to the instance number of this object. For example, the first instance is Car1, the second instance is Car2, and so forth.
So I created a String named car and now I need to make it apply a incrementing number when a new instance is created.
public class CarDash {
public String Car ="Car";
public static int instanceNumber;
}
And then it needs to count how many instances were created
One class variable that is shared for all of the class instances.
instanceNumber
integer
keeps track the number of instances created.
Should i add a counter whenever a certain method is called? Or have it count when the a new Car is named/created?
instanceNumber++;
I dont know if I am making any sense...

You just need to create a constructor and increment the instanceNumber (using ++instanceNumber pre-increment ) then set the car value using instanceNumber variable.
So your constructor will be similar to below.
public CarDash(){
Car="Car"+ (++instanceNumber);
}
Whole class will be as below
public class CarDash {
public String Car = "Car";
public static int instanceNumber;
public CarDash(){
this.Car="Car"+ (++instanceNumber);
}
public static void main(String[] args) {
CarDash car=new CarDash();
CarDash car1=new CarDash();
CarDash car2=new CarDash();
System.out.println(car.Car+" "+car1.Car+" "+car2.Car);
}
}
Out put will be as below.
Car1 Car2 Car3

Try like below.
public class CarDash {
public String Car ="Car";
public static int instanceNumber;
CarDash() {
instanceNumber++;
Car = Car + instanceNumber;
}
public static int getInstanceCount() {
return instanceNumber;
}
}

You can do instanceNumber++; in your constructor.
But take special care in case you are instanceNumber as stati,as this would be shared by all instances.
So,in your case(suppose you have 10 instances),you will get name as Car10 for all instances.
e.g.
public class CarDash {
public String Car ="Car";
public static int instanceNumber;
public CarDash() {
instanceNumber++;
}
public String print(){
return Car+instanceNumber;
}
public static void main(String[] args) {
CarDash carDash=new CarDash();
CarDash carDash1=new CarDash();
CarDash carDash2=new CarDash();
System.out.println(carDash.print());
System.out.println(carDash1.print());
System.out.println(carDash2.print());
}
}
Output ::
Car3
Car3
Car3
Better way :
public class CarDash2 {
public String Car ="Car";
public static int instanceNumber;
public int carId;
public CarDash2() {
instanceNumber++;
carId=instanceNumber;
}
public String print(){
return Car+carId;
}
public static void main(String[] args) {
CarDash2 carDash=new CarDash2();
CarDash2 carDash1=new CarDash2();
CarDash2 carDash2=new CarDash2();
System.out.println(carDash.print());
System.out.println(carDash1.print());
System.out.println(carDash2.print());
}
}
Output::
Car1
Car2
Car3

Related

Can you declare class name as an attribute of another class in Java?

I have a class called Television and the second class is called Televisionshop and has Television[] television as an array attribute. And also a constructor called Televisionshop(Television [] television). How can I initialize the attribute to this constructor. ?
class Television {
String name;
Television(String name) {
this.name = name;
}
}
class TelevisionShop {
public Television[] televisions;
TelevisionShop(Television[] televisions) {
this.televisions = televisions;
}
}
public class Main
{
public static void main(String[] args) {
Television t1 = new Television("t1");
Television t2 = new Television("t2");
Television[] televisions = {t1,t2};
TelevisionShop shop = new TelevisionShop(televisions);
}
}
I guess this is the most straightforward way.

How to construct several objects in one class, then read in another class

I apologize if this is a basic question.
I am attempting to create several unique objects in one class, then get the values of one of the objects in another class.
I have created two classes and followed some examples to end with this
public class Type {
public String name;
public int healthmod;
public int strmod;
public int accmod;
public int armmod;
public int refmod;
public int intmod;
public String advantages;
public String disadvantages;
public Type() {
Type fire = new Type();
fire.name = "Fire";
fire.healthmod = 0;
fire.strmod = 1;
fire.accmod = 0;
fire.armmod = 0;
fire.refmod = 0;
fire.intmod = 1;
}
}
and then in the main class:
Player.typename = Type.fire.name;
Edit
public class Player {
public static String name, classname, racename, elementname;
public static int maxhealth, healthpts, healthptscost, healthupgnum, healthmod, currenthealth, basehealth;
public static int str, strpts, strptscost, strupgnum, strmod;
public static int acc, accpts, accptscost, accupgnum, accmod;
public static int arm, armpts, armptscost, armupgnum, armmod;
public static int ref, refpts, refptscost, refupgnum, refmod;
public static int intelligence, intpts, intptscost, intupgnum, intmod;
public static int mana, maxmana, managain, managainak;
public static int hitChance, critChance, Level, statPts, statTotal, damage, damageDealt, goldmult, itemmod, itemdefboost, itemdamboost, itemmodboost;
public static String[] focusStats;
}
What I am trying to do is create a few objects in the Type class and access them in the Main class in order to store the values in the Player class, but in the Main class, fire "cannot be resolved or is not a field"
Edited to provide more clarity on the purpose.
You are completely mixing things here.
In the concstructor of Type you are creating a new local Object named fire. This object is only available in this constructor and not outside of it, e.g. in the main class.
A valid solution can only be found if you give more information about what you try to accomplish.
I could write like that your Type construct:
public Type() {
this.name = "Fire";
this.healthmod = 0;
this.strmod = 1;
this.accmod = 0;
this.armmod = 0;
this.refmod = 0;
this.intmod = 1;
}
So when using the Player class in your Main method, like that:
public static void main(String args[]) {
Type type = new Type();
Player.typename = type.name;
}
You can also put a reference of type inside Player class like that:
public class Player {
public static Type fire;
}
So in your main method like that:
public static void main(String args[]) {
Player.fire = new Type();
System.out.println(Player.fire.name);
}

How do I use value from one class for another class Calling from main method

One.java
public class One {
String asd;
public class() {
asd="2d6"
}
public static void main(String args[]) {
Two a = new Two();
}
}
Two.java
public class Two {
ArrayList<String>data;
String asd;
public Two(String asd){
this.asd=asd;
data.add(this.asd);
}
}
How do I use this asd value of second for third class calling from first class's main method.
**Third class**
Per comments of #Maroun Maroun and #Bennyz, you can create a getter and setter method in your Two class:
import java.util.ArrayList;
public class Two {
ArrayList<String> data;
String asd;
public Two(String asd) {
this.asd = asd;
data = new ArrayList<>(); //<-- You needed to initialize the arraylist.
data.add(this.asd);
}
// Get value of 'asd',
public String getAsd() {
return asd;
}
// Set value of 'asd' to the argument given.
public void setAsd(String asd) {
this.asd = asd;
}
}
A great site to learn about this while coding (so not only reading), is CodeAcademy.
To use it in a third class, you can do this:
public class Third {
public static void main(String[] args) {
Two two = new Two("test");
String asd = two.getAsd(); //This hold now "test".
System.out.println("Value of asd: " + asd);
two.setAsd("something else"); //Set asd to "something else".
System.out.println(two.getAsd()); //Hey, it changed!
}
}
There are also some things not right about your code:
public class One {
String asd;
/**
* The name 'class' cannot be used for a method name, it is a reserved
* keyword.
* Also, this method is missing a return value.
* Last, you forgot a ";" after asd="2d6". */
public class() {
asd="2d6"
}
/** This is better. Best would be to create a setter method for this, or
* initialize 'asd' in your constructor. */
public void initializeAsd(){
asd = "2d6";
}
public static void main(String args[]) {
/**
* You haven't made a constructor without arguments.
* Either you make this in you Two class or use arguments in your call.
*/
Two a = new Two();
}
}
Per comment of #cricket_007, a better solution for the public class() method would be:
public class One {
String asd;
public One(){
asd = "2d6";
}
}
This way, when an One object is made (One one = new One), it has a asd field with "2d6" already.

How to use Arraylist over different classes

Im trying to add a dog (nyHund) which is created in a different class, to an Arraylist i created using a constructor in another class, but whenever i try to use the Arraylist in the "register" class, im getting the error that the arraylist name can't be resolved.
First 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 (ras=="tax"){
return 3.7;
}else{
return ((vikt*ålder)/10);
}
}
public String toString() {
return namn + "\n" + ålder + "\n"+ras+"\n"+vikt+"\n"+getSvanslängd();
}
}
Second Class
import java.util.ArrayList;
public class testning {
public static void main(String[] args) {
Hund nyHund = new Hund("Daisy", 13, "labrador", 22.3);
System.out.println(nyHund.toString());
Register.läggTillHund(nyHund);
}
}
And the Third class:
import java.util.ArrayList;
public class Register {
public static void läggTillHund(Hund nyHund){
hundRegister.add(nyHund);
System.out.println(nyHund);
}
private Register(){
ArrayList<Hund> hundRegister = new ArrayList<Hund>();
}
}
The problem i am experiencing is with "hundRegister.add(nyHund)"
any thoughts? or pointers where im going wrong? (very new at Java)
Best Regards
Oskar
The ArrayList you've created is local to your Register constructor. Declare it inside the class, but outside the constructor, as an instance variable, so it's in scope throughout the class.
public class Register {
private ArrayList<Hund> hundRegister;
private Register(){
hundRegister = new ArrayList<Hund>();
}
}
Additionally, it's unclear why the constructor is private. Nothing else can access that constructor. I would make it public.
Also, in getSvanslängd, replace ras=="tax" with "tax".equals(ras). See How do I compare strings in Java?.

Inherited variables are not displaying in the subclass

I'm having an issue with the inherited variables not displaying in the subclass.
Heres the code...
// Class to instantiate and call
public class UseOrder
{
public static void main(String[] args)
{
// Instantiate classes
Order objOrder=new Order();
ShippedOrder objShip=new ShippedOrder();
//Promt for data
objOrder.SetName();
objOrder.SetNum();
objOrder.SetPrice();
objOrder.SetQuantity();
// Display
objShip.Display();
}
}
//Heres the parent class
public class Order
{
//Declare variables
public String CustName;
public int CustNum,QuantityOrdered;
public double Price,TotalPrice;
//Assign Variables using set methods
public void SetName()
{
this.CustName=JOptionPane.showInputDialog("Enter customer Name");
}
public void SetNum()
{
this.CustNum=Integer.parseInt(JOptionPane.showInputDialog("Enter customer number"));
}
public void SetQuantity()
{
this.QuantityOrdered=Integer.parseInt(JOptionPane.showInputDialog("Enter quanntity ordered"));
}
public void SetPrice()
{
this.Price=Double.parseDouble(JOptionPane.showInputDialog("Enter product price"));
}
//Get methods for these variables
public String GetName()
{
return CustName;
}
public int GetNum()
{
return CustNum;
}
public int GetQuantity()
{
return QuantityOrdered;
}
public double GetPrice()
{
return Price;
}
//Method to calculate Total Price
public double ComputePrice()
{
return TotalPrice=QuantityOrdered*Price;
}
// Method to display
public void Display()
{
JOptionPane.showMessageDialog(null,CustName+" with customer number "+CustNum+" ordered "+QuantityOrdered+" products. \nThe price for one unit is " + Price+" and the total price is "+ComputePrice());
}
}
and heres the subclass
public class ShippedOrder extends Order
{
//Shipping and handling value
private double ShipFee=4.00;
// method to override ComputePrice in Order
public double ComputePrice()
{
return super.TotalPrice=(super.QuantityOrdered*super.Price)+ShipFee;
}
//Display the data
public void Display()
{
JOptionPane.showMessageDialog(null,super.GetName()+" with customer number "+super.GetNum()+" ordered "+super.GetQuantity()+" products. \nThe price for one unit is " + super.GetPrice()+" and the total price is "+ComputePrice());
}
}
You populate a different object than you're displaying, so no wonder you get no values. You should change main to
public static void main(String[] args)
{
// Instantiate classes
ShippedOrder objShip=new ShippedOrder();
//Promt for data
objShip.SetName();
objShip.SetNum();
objShip.SetPrice();
objShip.SetQuantity();
// Display
objShip.Display();
}
because every ShippedOrder is also an Order.
public static void main(String[] args)
{
// Instantiate classes
Order objOrder=new Order();
ShippedOrder objShip=new ShippedOrder();
//Promt for data
objOrder.SetName();
objOrder.SetNum();
objOrder.SetPrice();
objOrder.SetQuantity();
// Display
objShip.Display();
}
You never set anything in objShip (the derived class). All your pre-display() method invocations were on objOrder, a different object.
Maybe you meant:
public static void main(String[] args)
{
// Instantiate classes
Order objOrder=new ShippedOrder();
//Promt for data
objOrder.SetName();
objOrder.SetNum();
objOrder.SetPrice();
objOrder.SetQuantity();
// Display
objOrder.Display();
}
objShip and objOrder are separate from one another. When you change order, it will not change ship as they are different objects. You need to call the methods on objShip in this case if you want to display it from that.
ShippedOrder objShip = new ShippedOrder();
objShip.SetName();
objShip.SetNum();
objShip.SetPrice();
objShip.SetQuantity();
objShip.Display();
and remove objOrder completely.

Categories