您好我正在学习Java并且正在生成代码,用于将输入的便士数量转换为更改。
所以,如果我输入439p它打印:439p 2 * 200p 4 * 100p 1 * 20p 1 * 10p 1 * 5p 4 * 1p。 我需要实现的最后一件事是在打印声明中包括总共有多少硬币
所以在这种情况下它应该打印为:439p 13个硬币2 * 200p 4 * 100p 1 * 20p 1 * 10p 1 * 5p 4 * 1p。 我知道这可能很简单,但我真的不知道如何做到这一点,所以任何指导都会受到赞赏:)
我的代码是
class Main {
public static void main( String args[] ) {
System.out.print("#Please enter the amount of change : ");
int change = BIO.getInt();
while(change > 0)
{
int twopounds, pounds, fifty, twenty, ten, five, two, one;
twopounds = change / 200;
int left = change % 200;
pounds = change / 100;
left = change % 100;
fifty = left / 50;
left = left % 50;
twenty = left / 20;
left = left % 20;
ten = left / 10;
left = left % 10;
five = left / 5;
left = left % 5;
two = left / 2;
two = left % 2;
one = left / 1;
if (change == 1)
{
System.out.print("1 coin");
}
if (change > 500)
{
System.out.print("Invalid amount " + change + "p" + "\n");
}
if (change <= 500 && change > 1)
System.out.print(change + "p ");
{
if ( twopounds > 0 )
{
System.out.print( twopounds > 0 ? twopounds + "*200p " : "" );
}
if ( pounds > 0 )
{
System.out.print( pounds > 0 ? pounds + "*100p " : "" );
}
if ( fifty > 0 )
{
System.out.print( fifty > 0 ? fifty + "*50p " : "" );
}
if ( twenty > 0 )
{
System.out.print( twenty > 0 ? twenty + "*20p " : "" );
}
if ( ten > 0 )
{
System.out.print( ten > 0 ? ten + "*10p " : "" );
}
if ( five > 0 )
{
System.out.print( five > 0 ? five + "*5p " : "" );
}
if ( two > 0 )
{
System.out.print( two > 0 ? two + "*2p " : "" );
}
if ( one > 0 )
{
System.out.print( one > 0 ? one + "*1p " : "" );
}
}
System.out.print("#Please enter the amount of change : ");
change = BIO.getInt();
}
}
答案 0 :(得分:2)
简单如下:
int nbCoins = twopounds + pounds + fifty + twenty + ten + five + two + one
答案 1 :(得分:1)
声明
pounds = change / 100;
left = change % 100;
应该是
pounds = left / 100;
left = left % 100;
答案 2 :(得分:0)
此外,除了unxnut的评论之外,如果你更换
,你可以稍微缩短你的代码。if ( x > 0 ) {
System.out.print( x > 0 ? x + "*...p " : "" );
}
的语句
System.out.print( x > 0 ? x + "*...p " : "" );
或
if ( x > 0 ) {
System.out.print(x + "*...p ");
}
这些条件中的任何一个都足以构成组成变更的零件的条件输出。