gpt4 book ai didi

java - 从 ATM 机取钱

转载 作者:行者123 更新时间:2023-12-02 10:07:08 27 4
gpt4 key购买 nike

我需要打印出这样的东西。

If the input is 60, then the output should be "Here is 3 $20 notes and 0 $50 notes."
If the input is 100, then the output should be "Here is 0 $20 notes and 2 $50 notes."
If the input is 120, then the output should be "Here is 1 $20 notes and 2 $50 notes."

代码:

import java.util.Scanner;

class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i, j, n = input.nextInt();
int x = 0, y = 0;

if (n % 50 == 0) {
j = n/50;
for (i = 1; i != j+1; i++) {
y++;
}
System.out.println("Here is " + x + " $20 notes and " + y + " $50 notes.");
}
else if (n % 20 == 0 && n < 100) {
j = n/20;
for (i = 1; i != j+1; i++) {
x++;
}
System.out.println("Here is " + x + " $20 notes and " + y + " $50 notes.");
}
else if ((n % 100 != 0) && (n > 100) && (n % 20 == 0)) {
y = n/100;
int l = n-(y*100);
if (l % 20 == 0) {
int k = l/20;
for (i = 1; i != k+1; i++) {
x++;
}
System.out.println("Here is " + x + " $20 notes and " + y*2 + " $50 notes.");
}
}
else if ((n % 50 != 0) && (n > 50)) {
y = n/50;
int l = n-(y*50);
if (l % 20 == 0){
int k = l/20;
for (i = 1; i != k+1; i++) {
x++;
}
System.out.println("Here is " + x + " $20 notes and " + y + " $50 notes.");
}
}
else {
System.out.println("Sorry, the value you input cannot be withdrew.");
}
}
}

这就是我到目前为止所做的。它不适用于 110、130、210 等输入。

最佳答案

为了得到你需要的东西,不需要那么多的条件。只要您的代码顺序经过深思熟虑,并且重复使用重复的代码,一个条件语句就足够了:

import java.util.Scanner;

public class ATM {

private static int input = 0;
private static int nrOf100s = 0;
private static int nrOf50s = 0;
private static int nrOf20s = 0;
private static int nrOf5s = 0;

public static void main(String[] args) {

System.out.print("Enter an amount to withdraw: ");
input = new Scanner(System.in).nextInt();

nrOf100s = getValue(100); // run these in a different order, and your result will be wrong
nrOf50s = getValue(50);
nrOf20s = getValue(20);
nrOf5s = getValue(5);

System.out.println("nr of 100s: " + nrOf100s);
System.out.println("nr of 50s: " + nrOf50s);
System.out.println("nr of 20s: " + nrOf20s );
System.out.println("nr of 5s: " + nrOf5s);
System.out.println("nr of 1s: " + input); // no special variable needed for value of 1's. the remainder applies here
}

private static int getValue(int divisor) {
if( input < divisor ) {
return 0; // this happens if you try to get nr of 100s when the input is less than 100 (for instance)
}
int result = input / divisor;
input = input % divisor; // don't forget to reduce the value of input
return result;
}
}

关于java - 从 ATM 机取钱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55275869/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com