Java 从自动取款机取款
我需要打印出这样的东西 如果输入是60,那么输出应该是3$20和0$50。 如果输入是100,那么输出应该是0$20和2$50。 如果输入是120,那么输出应该是1$20和2$50。 代码: 导入java.util.Scanner; 班长{ 公共静态无效字符串[]args{ 扫描仪输入=新的ScannerSystem.in; int i,j,n=input.nextInt; int x=0,y=0; 如果n%50==0{ j=n/50; 对于i=1;i!=j+1;i++{ y++; } System.out.println这里有+x+20美元的钞票和+y+50美元的钞票。; } 否则,如果n%20==0&&n<100{ j=n/20; 对于i=1;i!=j+1;i++{ x++; } System.out.println这里有+x+20美元的钞票和+y+50美元的钞票。; } 否则,如果n%100!=0&&n>100&&n%20==0{ y=n/100; int l=n-y*100; 如果l%20==0{ int k=l/20; 对于i=1;i!=k+1;i++{ x++; } System.out.println这里有+x+20美元的钞票和+y*2+50美元的钞票。; } } 否则,如果n%50!=0&&n>50{ y=n/50; int l=n-y*50; 如果l%20==0{ int k=l/20; 对于i=1;i!=k+1;i++{ x++; } System.out.println这里有+x+20美元的钞票和+y+50美元的钞票。; } } 否则{ System.out.println抱歉,无法提取您输入的值。; } } }Java 从自动取款机取款,java,Java,我需要打印出这样的东西 如果输入是60,那么输出应该是3$20和0$50。 如果输入是100,那么输出应该是0$20和2$50。 如果输入是120,那么输出应该是1$20和2$50。 代码: 导入java.util.Scanner; 班长{ 公共静态无效字符串[]args{ 扫描仪输入=新的ScannerSystem.in; int i,j,n=input.nextInt; int x=0,y=0; 如果n%50==0{ j=n/50; 对于i=1;i!=j+1;i++{ y++; } Syst
这就是我到目前为止所做的。它不适用于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的精明方法。应该被接受。如果您的输出需要是单个字符串,您可以将所有nrOf*变量连接起来。