別のメインクラスでchar のAを加えたんですが、top が未だに空なのですが、どうしてかわかりません。
t0.add('A');とした場合には、
add (char block){
return new Tower(block, this);
} なので、t0のトップは'A'になり、t0のrest にはt0が入ると理解しているのですが、間違っているんでしょうか?確認してもtopは空になっています。
Main.java
1public static void main(String [] args){ 2Tower t0 = new Tower(); 3t0.add('A'); 4System.out.println(t0.isEmpty()); 5 6 7}
Java
1 2 3 4/** 5 * A recursive representation of a tower of blocks. 6 * 7 * @author Michael Albert 8 */ 9public class Tower{ 10 11 /** The top block. */ 12 private char top; 13 14 /** The rest of the tower. */ 15 private Tower rest; 16 17 /** 18 * Creates a new empty Tower. 19 */ 20 public Tower() { 21 this.top = ' '; 22 this.rest = null; 23 } 24 25 /** 26 * External classes can only create empty towers and manipulate 27 * them using public methods, because this constructor is 28 * private. 29 * @param top the top block in this tower 30 * @param rest the rest of the tower 31 */ 32 private Tower(char top, Tower rest) { 33 this.top = top; 34 this.rest = rest; 35 } 36 37 /** 38 * Returns true if this tower is empty, otherwise false. Empty 39 * towers are represented with the top block being a space 40 * character. 41 * @return whether the tower is empty or not. 42 */ 43 public boolean isEmpty() { 44 return top == ' '; 45 } 46 47 /** 48 * Creates a new tower by adding the given block to the top of 49 * this tower. 50 * @param block a block to add to the top of this tower. 51 * @return a new tower created by adding a block to the top of 52 * this tower. 53 */ 54 public Tower add(char block) { 55 return new Tower(block, this); 56 } 57 /** 58 * A method that returns an int equal to the height, 59 * i.e., number of blocks, in the tower. 60 * @return an int equal to the height. 61 */ 62 63 public String toString(){ 64 return "this Tower is " + this.top; 65 66 } 67// the number of blocks , in the tower. 68// return int equal to the height 69// ブロックの数をint でリターンする 70public int height(){ 71??? 72} 73 74 75} 76
回答2件
あなたの回答
tips
プレビュー