java - Why is my constructor not instantiating the variable? -
why value of clowns equal 0 below?
if print numofdecks, prints out 3, expected.
public class cardset {  private static int numofdecks; char suits [] = {'a','s','h','c'}; char ranks [] = {'a','2','3','4','5','6','7','8','9','t','j','q','k'};  public cardset(int number){      if (number > 0) {         this.numofdecks = number;      }     else this.numofdecks = 3; }  public static int getnumofdecks(){     return numofdecks; }  static int clowns = numofdecks;  public static void main (string [] args){     cardset cards = new cardset(3);     system.out.println(clowns); //prints out 0     system.out.println(numofdecks); // prints out 3 } 
this sets parameter variable's value:
else numberofdecks = 3; which not want do. instead should be:
else this.numberofdecks = 3; which sets field's value. or more succinctly do:
public cardset(int numberofdecks){     this.numberofdecks = (numberofdecks > 0) ? numberofdecks : 3; } as side note, consider using enums suits , ranks, since 1 of classic examples given use.
Comments
Post a Comment