我的任务是(我必须使用继承):
设计并实现了一个名为MonetaryCoin的类,它是从Coin类派生的。将价值存储在表示其价值的货币硬币中,并添加返回其价值的方法。创建一个ClientTester类来实例化和计算几个不同MonetaryCoin对象的和。例如,一角硬币、四分之一和HalfDollar的总价值为85美分。钱币继承了父母被抛出的能力。
我的硬币课是
import java.util.Random;
public class Coin
{
private final int HEADS = 0;
private final int TAILS = 1;
private int face;
// Constructor... sets up the coin by flipping it initially
public Coin()
{
flip();
}
// flips the coin by randomly choosing a face value
public void flip()
{
face = (int)(Math.random()*2); //random numbers 0 or 1
}
// returns true if the current face of the coin is head
public boolean isHeads()
{
return (face == HEADS);
}
// returns the current face of the coin as a string
public String toString()
{
String faceName;
if(face==HEADS)
{ faceName = "Heads"; }
else
{ faceName = "Tails"; }
return faceName;
}
}我的MonetaryCoinClass是
public class MonetaryCoin extends Coin
{
private int value;
public MonetaryCoin( int value )
{
this.value = value;
}
public int getValue()
{
return this.value;
}
public void setValue( int value )
{
this.value = value;
}
public int add( MonetaryCoin [] mc )
{
if ( mc.length >= 0 )
return -1;
int total = this.value;
for ( int i = 0; i < mc.length; i++ )
{
total += mc[i].getValue();
}
return total;
}
}最后我的客户是
public class Client
{
public static void main()
{
MonetaryCoin mc1 = new MonetaryCoin( 25 );
MonetaryCoin mc2 = new MonetaryCoin( 13 );
MonetaryCoin mc3 = new MonetaryCoin( 33 );
int total = mc1.add( mc2, mc3 );
int value = mc2.getValue();
}
}我的Client是唯一不编译的。我不知道我在为客户做什么。我必须使用我之前所做的翻转命令。
请帮帮我!
最新消息:我的客户现在
public class Client
{
public static void main()
{
MonetaryCoin mc1 = new MonetaryCoin( 25 );
MonetaryCoin mc2 = new MonetaryCoin( 13 );
MonetaryCoin mc3 = new MonetaryCoin( 33 );
MonetaryCoin[] test = new MonetaryCoin[2];
test[0] = mc2;
test[1] = mc3;
int total = mc1.add(test);
int value = mc2.getValue();
System.out.println("total: " +total+ " values: " +value);
}
}它会编译。然而,我如何使它,使硬币继承其父母的能力被翻转?
发布于 2015-12-17 01:52:16
您应该使用MonetaryCoin... mc而不是MonetaryCoin[] mc,如下所示:
public class MonetaryCoin extends Coin{
// All your other methods
// ...
public int add(MonetaryCoin... mc)
{
if ( mc.length >= 0 )
return -1;
int total = this.value;
for ( int i = 0; i < mc.length; i++ )
{
total += mc[i].getValue();
}
return total;
}
}MonetaryCoin[] mc意味着您将传入一个数组,比如{ m1, m2, m3 }。MonetaryCoin... mc意味着您将传入一个未知数量的MonetaryCoins。https://stackoverflow.com/questions/34325303
复制相似问题