Java 创建硬币计算
我正在创建一个硬币计算器,它可以将便士值分解为面值,但我希望这样做,以便用户可以选择排除硬币的面值,请参阅下面的代码。我在这里遇到了一堵墙,正在努力想一个代码来允许这种情况发生,如果有人有一个指针,我会非常感激。我可以创建一个代码,用户可以选择包含哪种面额Java 创建硬币计算,java,eclipse,loops,if-statement,switch-statement,Java,Eclipse,Loops,If Statement,Switch Statement,我正在创建一个硬币计算器,它可以将便士值分解为面值,但我希望这样做,以便用户可以选择排除硬币的面值,请参阅下面的代码。我在这里遇到了一堵墙,正在努力想一个代码来允许这种情况发生,如果有人有一个指针,我会非常感激。我可以创建一个代码,用户可以选择包含哪种面额 int money; int denom; Scanner sc=new Scanner(System.in); System.out.println("Please ente
int money;
int denom;
Scanner sc=new Scanner(System.in);
System.out.println("Please enter the amount of coins you have in penny value");
money = sc.nextInt();
System.out.println("Also the denomiation you would like exclude; 2, 1, 50p, 20p, 10p");
denom = sc.nextInt();
while (money > 0){
if (money >= 200) {
System.out.println("£2");
money -= 200;
}
else if (money >= 100) {
System.out.println("£1");
money -= 100;
}
else if (money >= 50) {
System.out.println("50p");
money -= 50;
}
else if (money >= 20) {
System.out.println("20p");
money -= 20;
}
else if (money >= 10) {
System.out.println("10p");
money -= 10;
}
else if (money >= 1) {
System.out.println("1p");
money -= 1;
}
我想说这可能是最基本的方法,不用为它创建单独的方法。将denom设置为排除的值,然后在减法之前检查一枚硬币是否等于denom可能会起作用,因为反正硬币并不多
int money;
int denom;
Scanner sc=new Scanner(System.in);
System.out.println("Please enter the amount of coins you have in penny value");
money = sc.nextInt();
System.out.println("Also the denomiation you would like exclude; 2, 1, 50p, 20p, 10p");
String input = sc.next(); //saving user input as a string
if (input.contains("p"))
{ //converting string to int by removing the p
denom = Integer.parseInt(input.substring(0, input.indexOf("p")));
}
else
{ //if there's no p, multiply its value by 100
denom = Integer.parseInt(input) * 100;
}
while (money > 0){
if (money >= 200 && denom != 200) {
System.out.println("£2");
money -= 200;
}
else if (money >= 100 && denom != 100) {
System.out.println("£1");
money -= 100;
}
else if (money >= 50 && denom != 50) {
System.out.println("50p");
money -= 50;
}
else if (money >= 20 && denom != 20) {
System.out.println("20p");
money -= 20;
}
else if (money >= 10 && denom != 10) {
System.out.println("10p");
money -= 10;
}
else if (money >= 1) {
System.out.println("1p");
money -= 1;
}
}
非常感谢。我不知道我以前怎么没有看到这一点,你对我帮助很大:)没问题,很乐意帮忙。