[英]How to count the number of coins?
Hi I'm learning Java and am producing code that converts the number of pennies entered in to change. 嗨,我正在学习Java,并且正在编写代码,以转换输入的便士数量进行更改。
So if I enter 439p it prints: 439p 2*200p 4*100p 1*20p 1*10p 1*5p 4*1p. 因此,如果我输入439p,它将打印:439p 2 * 200p 4 * 100p 1 * 20p 1 * 10p 1 * 5p 4 * 1p。 The last thing I need to implement is including how many coins there are in total in the print statement
我需要实现的最后一件事是包括打印语句中总共有多少个硬币
So in this case it should print as: 439p 13 coins 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。 I know it's probably simple but I'm really not sure how to do this so any guidance would be appreciated :)
我知道这可能很简单,但我真的不确定如何执行此操作,因此任何指导都将不胜感激:)
My code is 我的代码是
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();
}
}
简单如:
int nbCoins = twopounds + pounds + fifty + twenty + ten + five + two + one
The statement 该声明
pounds = change / 100;
left = change % 100;
should be 应该
pounds = left / 100;
left = left % 100;
Also, in addition to unxnut's remark, you could shorten your code a little bit if you replace the 此外,除了unxnut的说明外,如果您替换了
if ( x > 0 ) {
System.out.print( x > 0 ? x + "*...p " : "" );
}
statements with either 陈述与
System.out.print( x > 0 ? x + "*...p " : "" );
or 要么
if ( x > 0 ) {
System.out.print(x + "*...p ");
}
Either of those conditions will be sufficient for a conditional output of the parts that make up the change. 这些条件中的任何一个都足以构成组成变更的零件的有条件输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.