Why is value of variable not incremented in constructor - java

I created a program that creates a card, which will contain a number, name and status. I want the user to be able to set the name for the user of the card but I want the number to be sequential, so a new one for every card created starting at 1. I set the value of the first card at 1 and then call the method to increment its value for the next card inside the constructor but when I run it in a test class it always gives out number 2. Help's appreciated!
Leaving the variables, constructor, increment method, toString method and test class below.
public class CartaoCliente {
long numCartao = 1;
String nome;
Boolean estado;
public void incCartao(){
numCartao++;
}
public CartaoCliente(String nomeCartao){
incCartao();
this.nome = nomeCartao;
}
#Override
public String toString(){
return "Número: " + numCartao + ", Nome: " + nome; //overriden to print below
}
}
public class TesteCartao {
public static void main(String[] args) {
CartaoCliente c = new CartaoCliente("José");
CartaoCliente d= new CartaoCliente("Esdrubal");
System.out.println(c.toString());
System.out.println(d.toString());
}
}

solution from #Progman
public class CartaoCliente {
static long numCartao = 1;
String nome;
Boolean estado;
long novoNum;
public void incCartao(){
novoNum = numCartao++;
}
#Override
public String toString(){
return "Número: " + novoNum + ", Nome: " + nome; //overriden to print below
}
}

Related

Changing fields of class in java

So, I'm still learning java and coding so the resolution may be obvious but I just can't see it.
I'm writing a code about stars and constelations for uni assignment.
package com.company;
import java.util.*;
public class Main {
static public class Constellation {
public List<Star> constellation;
public String nameOfConstellation;
public Constellation(List<Star> constellation, String nameOfConstellation) {
this.constellation = constellation;
this.nameOfConstellation = nameOfConstellation;
}
public List<Star> getConstellation() {
return constellation;
}
}
static public class Star {
// private String categoryName;
private Constellation constellation;
private String nameOfConstelation;
public String getCategoryName() {
int index = constellation.getConstellation().indexOf(this);
String categoryName;
return categoryName = GreekLetter.values[index] + " " + this.constellation.nameOfConstellation;
}
public void deleteStar(Star x) {
this.constellation.constellation.remove(x);
}
}
public enum GreekLetter {
alfa,
beta,
gamma,
delta,
epsilon,
dzeta,
eta;
static public final GreekLetter[] values = values();
}
public static void main(String[] args)
{
Star x = new Star();
List<Star> fishCon = new ArrayList<>();
Constellation Fish = new Constellation(fishCon, "Fish");
x.constellation=Fish;
fishCon.add(x);
x.getCategoryName();
Star y = new Star();
y.constellation=Fish;
fishCon.add(y);
y.getCategoryName();
x.deleteStar(x);
for (Star w : Fish.constellation)
{
System.out.println(w.getCategoryName());
}
}
}
My point is to Update field categoryName after deleting one star. categoryName value is set in order of adding another star. For example I have first star - the name will be Alfa + nameOfConstelation. Second star - Beta + nameOfConstelation. When I call method deleteStar() I want to update all categoyName of my stars in constelation. Calling methods in deleteStar() doesn't work probably due to add() in setCategoryName. I would really appreciate any hints!
Since this appears to be homework, I am not posting code in this answer but rather giving suggestions that can help you create your own workable code:
Create a class called Constellation that holds the Stars in an List<Star> starList = new ArrayList<>();
Give Constellation a public List<Star> getStarList() method
Give each Star a Constellation field to hold the Constellation that contains this Star
Give each Star a getCategoryName() method that gets the Constellation object, iterates through its starList using a for-loop until it finds the this Star, and then that returns the appropriate name based on the index of the Star in the list.
Thus, if a Star is removed from the starList, the category names of all the other Stars held by that Constellation will update automatically and dynamically
Also,
You can give Constellation a public void deleteStar(Star star) method where it removes the Star parameter from its starList
You can also give Star a public void deleteFromConstellation() method where it checks its Constellation field, constellation, and if not null, calls constellation.deleteStar(this); and then sets the constellation field to null
Get rid of the private String categoryName; field in Star. This should be a calculated field, meaning the public String getCategoryName() does not return a field, but a String based on code (as described above).
It first checks that Star's constellation field is not null
It then gets the index of the Star in the Constellation's starList (I have given my Constellation class a public int getIndexOfStar(Star star) method.
It then uses this, the GreekLetter class, and the constellation.getName() method to create a String to return
Done.
Since you've figured this out, this is another way to code it:
public class SkyMain {
public static void main(String[] args) {
Constellation fish = new Constellation("Fish");
Star x = new Star();
Star y = new Star();
fish.addStar(x);
fish.addStar(y);
System.out.println("before removing x");
System.out.println("x category name: " + x.getCategoryName());
System.out.println("y category name: " + y.getCategoryName());
System.out.println("fish constellation: " + fish);
fish.removeStar(x);
System.out.println();
System.out.println("after removing x");
System.out.println("x category name: " + x.getCategoryName());
System.out.println("y category name: " + y.getCategoryName());
System.out.println("fish constellation: " + fish);
}
}
public class Star {
private Constellation constellation;
public void setConstellation(Constellation constellation) {
this.constellation = constellation;
}
public void removeFromConstellation() {
if (constellation != null) {
constellation.removeStar(this);
}
}
public String getCategoryName() {
if (constellation != null) {
int index = constellation.getIndexOfStar(this);
return GreekLetter.getGreekLetter(index).getName() + " " + constellation.getName();
} else {
return "";
}
}
#Override
public String toString() {
return getCategoryName();
}
}
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Constellation implements Iterable<Star> {
private String name;
private List<Star> starList = new ArrayList<>();
public Constellation(String name) {
this.name = name;
}
public String getName() {
return name;
}
public List<Star> getStarList() {
return starList;
}
public void addStar(Star star) {
starList.add(star);
star.setConstellation(this);
}
public void removeStar(Star star) {
if (starList.contains(star)) {
starList.remove(star);
star.setConstellation(null);
}
}
public int getIndexOfStar(Star star) {
return starList.indexOf(star);
}
#Override
public Iterator<Star> iterator() {
return starList.iterator();
}
#Override
public String toString() {
return "Constellation [name=" + name + ", starList=" + starList + "]";
}
}
public enum GreekLetter
{
ALPHA("alpha", 0),
BETA("beta", 1),
GAMMA("gamma", 2),
DELTA("delta", 3),
EPSILON("epsilon", 4),
ZETA("zeta", 5),
ETA("eta", 6);
private String name;
private int index;
private GreekLetter(String name, int index) {
this.name = name;
this.index = index;
}
public String getName() {
return name;
}
public int getIndex() {
return index;
}
public static GreekLetter getGreekLetter(int index) {
if (index < 0 || index > values().length) {
throw new IllegalArgumentException("for index " + index);
} else {
return values()[index];
}
}
}

Syntax on printing objects? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Directions: http://imgur.com/kw6A0JX
I don't think I am printing out the objects correctly. My teacher helped me with the first part so I believe I am assigning them correctly. When printing them out, do I use "this" command? What is the right syntax for this type of situation?
Thank you.
public static void main(String [ ] args) {
Dog1 Rover = new Dog1("Rover", 4);
Sheep1 Wooly = new Sheep1("Wooly", 4);
Duck1 Daffy = new Duck1("Daffy", 2);
Cat1 Ketty = new Cat1("Ketty", 4);
System.out.println(name.Dog1, getHello.Dog1, isCarnivorous.Dog1, isMammal.Dog1);
System.out.println(name.Sheep1, getHello.Sheep1, isCarnivorous.Sheep1, isMammal.Sheep1);
System.out.println(name.Duck1, getHello.Duck1, isCarnivorous.Duck1, isMammal.Duck1);
System.out.println(name.Cat11, getHello.Cat1, isCarnivorous.Cat1, isMammal.Cat1);
}
Updated:
public abstract class Animal1 { //creating Animal1 which is the base and parent class, it is abstract so abstract classes can be created below
private String animalName; //defining animalName as private
public int numberOfLegs; //# of legs as public
public Animal1(final String name){ //first constructor with only assigning name
animalName = name;
}
public Animal1(final String name, final int legs){ //second constructor assigning both name and number of legs
animalName = name;
numberOfLegs = legs;
}
public String getName(){ //first getMethod for animalName
return animalName;
}
public int getLegs(){ //second getMethod for returning numberOfLegs
return numberOfLegs;
}
public boolean isMammal(){ //returning true value with boolean
return true;
}
public boolean isCarnivorous(){ //returning true value with boolean
return true;
}
public abstract String getHello(); //creating an abstract method, possible because base class is also abstract
}
public class Cat1 extends Animal1{ //child class of Animal1
public Cat1(final String name){ //Creating class constructor taking a name, within the constructor call the parent class constructor taking one argument
super(name, 4);
}
#Override
public String getHello(){ //Overriding getHello to return "Meow"
return "Meow";
}
}
public class Dog1 extends Animal1{ //another child of Dog1
public Dog1(final String name){ //Creating class constructor taking a name, within the constructor call the parent class constructor taking one argument
super(name, 4);
}
#Override
public String getHello(){ //Overriding getHello to return "Woof"
return "Woof";
}
}
public class Duck1 extends Animal1{ //third child class of Animal1
public Duck1(final String name){ //Creating class constructor taking a name, within the constructor call the parent class constructor taking one argument
super(name, 2);
}
#Override
public boolean isMammal(){ //Overriding isMammal() function to return false, as a duck is not a mammal
return false;
}
#Override
public boolean isCarnivorous(){ //Overriding isCarnivorous() function to return false as a duck is not a carnivore
return false;
}
#Override
public String getHello(){ //Overriding getHello to return "Quack"
return "Quack";
}
}
public class Sheep1 extends Animal1{ //fourth child class of Animal1
public Duck1(final String name){ //Creating class constructor taking a name, within the constructor call the parent class constructor taking one argument
super(name, 2);
}
#Override
public boolean isCarnivorous(){ //Overriding isCarnivorous() function to return false as a sheep is not a carnivore
return false;
}
#Override
public String getHello(){ //Overriding getHello to return "Baa"
return "Baa";
}
}
public static void main(String [ ] args) {
Dog1 Rover = new Dog1("Rover", 4);
Sheep1 Wooly = new Sheep1("Wooly", 4);
Duck1 Daffy = new Duck1("Daffy", 2);
Cat1 Ketty = new Cat1("Ketty", 4);
System.out.println(Rover.getName() + ", " + Rover.getHello() + ", " + Rover.isCarnivorous() + ", " + Rover.isMammal());
System.out.println(Wooly.getName() + ", " + Wooly.getHello() + ", " + Wooly.isCarnivorous() + ", " + Wooly.isMammal());
System.out.println(Daffy.getName() + ", " + Daffy.getHello() + ", " + Daffy.isCarnivorous() + ", " + Daffy.isMammal());
System.out.println(Ketty.getName() + ", " + Ketty.getHello() + ", " + Ketty.isCarnivorous() + ", " + Ketty.isMammal());
}
Your syntax is wrong. You need to refer to the variable by name, not by class. And the method comes after the object. And System.out.println() doesn't accept multiple arguments. Try this:
System.out.println(Rover.getName() + ", " + Rover.getHello() + ", " + Rover.isCarnivorous() + ", " + Rover.isMammal());
Similarly for the other lines.
You've got your syntax reversed. If these are all methods that you're calling, then they're done like Dog1.name(). If they're just public variables, you can call them like Dog1.name.
Also, a word of advice - most object instants in java follow the syntax of first word lowercase, following words uppercase (like your methods). Not crucial, but helpful to know.
Edit: Yep, it's just what the first line of this answer reads. To get the boolean from your animal class, just call them with first the object's name, then .exampleMethod().
Also, for your print statements, the println method might print the statements funny if you leave it as it is. What you can do instead is just add some strings in between like so:
System.out.println("Name: " + Dog1.getName() + ", Hello: " + Dog1.getHello()...); // rest of line excluded for brevity
The keyword this refers to the current object.
public class Test
{
public static void main(String[] args)
{
Dog1 dog = new Dog1("Rover", 4);
System.out.println(dog.name() + " " + dog.hello() + " " + dog.carnivorus() + " " + dog.mammal() + ".");
}
}
class Dog1
{
private String name;
private int age;
private String hello;
private boolean carnivorus;
private boolean mammal;
public Dog1(String name, int age)
{
this.name = name;
this.age = age;
this.hello = "woof woof";
this.carnivorus = true;
this.mammal = true;
}
public String name()
{
return this.name;
}
public String hello()
{
return this.hello;
}
public boolean carnivorus()
{
return this.carnivorus;
}
public boolean mammal()
{
return this.mammal;
}
}

How to sum the number of instances of an object in Java?

Right now I'm working on a basic java program that takes a few parameters into a constructor for a cup of coffee. That is easy enough but I'm having trouble creating a method for summing the number of coffee cups I've created.
So far this is the UseCoffee class I've created:
public class UsesCoffee{
public static void main(String args[]) {
System.out.println("cups created: " + Coffee.totalCups());
Coffee cup1 = new Coffee(350, "mint", true);
System.out.println("cup1: " + cup1);
Coffee cup2 = new Coffee(500, "mocha", false);
System.out.println("cups created: " + Coffee.totalCups());
System.out.println("cup2: " + cup2);
Coffee cup3 = new Coffee(350, "no flavour used", false);
cup3.doubleSize();
System.out.println("cup3: " + cup3);
Coffee cup4 = new Coffee(-10, "mocha", false);
System.out.println("cup4: " + cup4);
System.out.println("cups created: " + Coffee.totalCups());
if (Coffee.bigger(cup3,cup2))
System.out.println("cup3 is bigger than cup2");
if (Coffee.bigger(cup1,cup2))
System.out.println("cup1 is bigger than cup3");
if (Coffee.bigger(cup1,cup1))
System.out.println("cup1 is bigger than itself");
} // end main
} // end UsesCoffee
And this is the Coffee Class I've created:
public class Coffee {
private int coffeeVol;
private String coffeeFlav;
private boolean yesCream;
public Coffee(int volume, String flavour, boolean cream) {
this.coffeeFlav = flavour;
this.coffeeVol = volume;
this.yesCream = cream;
if (volume < 0) {
System.out.println("error: negative size. Defaultsize of 250 ml used");
coffeeVol = 250;
}
}
public String toString() {
return coffeeVol +"ml, " + coffeeFlav + ", " + yesCream;
} // end toString
public static int totalCups() {
//THIS IS WHERE I'M HAVING TROUBLE
}
public int doubleSize() {
coffeeVol = coffeeVol*2;
return coffeeVol;
}
}
Is there a way to sum the number of coffee cups? I'm truly lost in this respect, and any help is appreciated!
You could add a static variable to your Coffee class and increment it in your constructor.
Something like that:
public class Coffee {
private static int numberOfCups = 0;
private int coffeeVol;
private String coffeeFlav;
private boolean yesCream;
public Coffee(int volume, String flavour, boolean cream) {
this.coffeeFlav = flavour;
this.coffeeVol = volume;
this.yesCream = cream;
if (volume < 0) {
System.out.println("error: negative size. Defaultsize of 250 ml used");
coffeeVol = 250;
}
numberOfCups++;
}
public String toString() {
return coffeeVol +"ml, " + coffeeFlav + ", " + yesCream;
} // end toString
public static int totalCups() {
return numberOfCups;
}
public int doubleSize() {
coffeeVol = coffeeVol*2;
return coffeeVol;
}
public static boolean bigger(Coffee cup1, Coffee cup2) {
if (cup1.coffeeVol > cup2.coffeeVol) {
return true;
}
return false;
}
}
What you want to do is create a static field and increment it every time the constructor is called.
public class Coffee {
private static int totalCups;
// rest of the code ...
public Coffee(int volume, String flavour, boolean cream) {
totalCups++;
// rest of the code...
}
public static int getTotalCups() {
return totalCups;
}
}
// rest of the code ...
You want to make the field and method static because it will be shared by all instances of Coffee. You want to make totalCups a private field because of data encapsulation (you do not want to allow someone to change the total number of cups, which can only be modified logically via the constructor) and then retrieve it with a public getter method (which allows you to run additional data validation)
You might want to use something called an initialization block, and a static integer field to hold the current number of instances of your class. This is the best way of doing what you want, in my opinion.
public class Coffee
{
// Hold the number of instances.
private static int instances;
// This snippet of code will run whenever one of the //
// constructors below is called. All subclasses will //
// automatically inherit this too, by the way. //
{
instances++;
}
// first constructor
public Coffee() {}
// second constructor
public Coffee(int Foo) {}
// third constructor
public Coffee(double Bar) {}
// return the number of instances you have.
public static int totalCups()
{
return instances;
}
}
If you want to count the #/cups ... and you also want to compare each of the cups with each other ("which cup is largest") ... then you really ought to consider using a Collection.
EXAMPLE:
public class UsesCoffee{
public static void main(String args[]) {
ArrayList<Coffee> cups = new ArrayList<Coffee>();
System.out.println("cups created: " + cups.size());
cups.add(new Coffee(350, "mint", true));
cups.add(new Coffee(500, "mocha", false));
System.out.println("cups created: " + cups.size());
Coffee biggestCup = cups.get(0);
for (Coffee cup : cups) {
if (cup.coffeeVol > biggestCup.coffeeVol)
biggestCup = cup;
}
System.out.println("biggest cup is " + biggestCup.coffeeVol);
}
}

make a global object in java

I want to make an array of objects and use it in different functions. I wrote this pseudocode
privat stock[] d;
privat stock example;
public void StockCheck(){
d =new stock[2];
d[0]= new stock("a","test1", 22);
d[1]= new stock("b","test2", 34);
}
#Override
public stock getStock(String name) throws StockCheckNotFoundException{
int i;
System.out.println("ok" + name + d.legth); // error
example = new stock("example","example",2);
return example;
}
In class test I make an instance of getStock and I call the function getStock stock.getStock();
I get a NullPointerExeption when I do d.length. d is null but I don't understand why.
Hmmmm. If that is in any way like your real code, then the problem is that your "constructor" isn't really a constructor, as you've declared it to return void, making it an ordinary method instead. Remove tbat "void" and it may fix the problem!
Perhaps this example of code will do what you need, using three classes
Test - the main test code
Stock - the implied code for Stock from your question
StockCheck - the corrected code from your question.
(Note: you may really want to use an ArrayList inside StockQuote so you can add and delete Stocks.)
Test class
package stackJavaExample;
public class Test {
public static void main(String[] args) {
String[] testNames = {"test1","test2","notThere"};
StockCheck mStockCheck = new StockCheck();
for (int i=0; i<testNames.length; i++) {
Stock result = mStockCheck.getStock(testNames[i]);
if (result == null) {
System.out.println("No stock for name: " + testNames[i]);
} else {
System.out.println("Found stock: " + result.getName() + ", " + result.getSymbol() + ", " + result.getValue());
}
}
}
}
Stock class
package stackJavaExample;
public class Stock {
private String symbol;
private String name;
private double value;
public Stock(String symbol, String name, double value) {
this.symbol = symbol;
this.name = name;
this.value = value;
}
public String getSymbol() { return symbol;}
public String getName() { return name;}
public double getValue() {return value;}
}
StockCheck class
package stackJavaExample;
public class StockCheck {
private Stock[] d;
public StockCheck() {
d = new Stock[2];
d[0] = new Stock("a","test1", 22);
d[1] = new Stock("b","test2", 34);
}
public Stock getStock(String name) {
for (int i=0; i < d.length; i++) {
if (d[i].getName().equalsIgnoreCase(name)) {
return d[i];
}
}
return null;
}
}

The type of the expression must be an array type but it resolved to

Im new to java. I dont understand why these errors are occurring. trying to make an array list so that it saves each object. The errors im getting are The type of the expression must be an array type but it resolved to ArrayList on the line 'newbug1[i].setspecies();'
Thankyou in advance
import javax.swing.JOptionPane;
import java.util.ArrayList;
public class Abug2 {
private String species;
private String name;
private char symbol = '\0';
private int horposition = 0, verposition = 0, energy = 0, uniqueID = 1, counter;
public Abug2(String species, String name, char symbol)
{
uniqueID = counter;
counter++;
}
public void setspecies(){
species = JOptionPane.showInputDialog(null, "Enter the species: ");
}
public String getspecies(){
return species;
}
public void setname(){
name = JOptionPane.showInputDialog(null, "Enter the name: ");
}
public String getname(){
return name;
}
public void setsymbol(){
symbol = name.charAt(0);
}
public char getsymbol(){
return symbol;
}
public int getid(){
return uniqueID;
}
public int gethorizontal(){
return horposition;
}
public int getvertical(){
return verposition;
}
public int getenergy(){
return energy;
}
//The class ABug has a set of methods: two or more constructors, toString, toText, and getters and setters for the attributes
public String toString(){
String tostring = "\nName: " + name + "\nHorizontal Position: " + horposition + "\nVertical Position: " + verposition + "\n";
return tostring;
}
public String toText(){
String totext = getspecies() + getname() + getsymbol() + getid() + gethorizontal() + getvertical() + getenergy();
return totext;
}
public static void main (String [] args){
ArrayList<Abug2> newbug1 = new ArrayList<Abug2>();
String choice = JOptionPane.showInputDialog(null, "Would you like to add another bug?: ");
do{for (int i = 0; i < 3; i++) {
newbug1.add(new Abug2("Bug", "Spider", 's'));
newbug1[i].setspecies();
newbug1[i].setname();
newbug1[i].setsymbol();
System.out.println(newbug1[i].toString());
} }while(choice != "yes");
}
}
For arraylists use get() instead:
newbug1.get(i).setspecies();
newbug1.get(i).setname();
newbug1.get(i).setsymbol();
Because it stores object references any setFoo calls affect the original object referenced in the arraylist.
In order to access an element in an ArrayList you have to use a method called get.
In your code, replace newbug1[i] by newbug1.get(i)
And moreover, you should store that reference in a variable instead of recalling it again and again:
Abug2 currentBug = newbug1.get(i);
currentBug.setSpecies();
Your code will gain in clarity.

Categories

Resources