使用依赖其他方法的方法

时间:2018-11-06 22:26:09

标签: java methods netbeans

我正在尝试编写一个程序,该程序告诉您进行更改所需的最小硬币数量,并且它必须是模块化的。目前,它要求输入3次,并打印所有3个输入之和所需的硬币数量。我认为这是因为maxDimes依赖于maxQuarters,后者依赖于输入。有什么办法可以让这些方法只运行一次?我是编程和这个网站的新手,如果这个问题不清楚或已经有人提出,我深表歉意。

     public static int input()
{
    System.out.println("Please enter amount of change under 100 cents: ");
    Scanner input = new Scanner(System.in);
    int change = input.nextInt();
    if (change%5<2)
    {
        change = change+(change%5);
    }
    else if(change%5>2)
    {
        change = change-(change%5);
    }
    return change;

}
public static int[] maxQuarters()
{
    int change = input();
    int quarters = change/25;
    int leftover = change-quarters;
    return new int[] {quarters, leftover};
}
public static int[] maxDimes()
{
    int first[] = maxQuarters();
    int change = first[1];
    int dimes = change/10;
    int leftover = change-dimes;
    return new int[] {dimes, leftover};  
}
public static int maxNickels()
{
    int second[] = maxDimes();
    int change = second[1];
    int nickels = change/5;
    return nickels;
}
public static void makeChange()
{
    int first[] = maxQuarters();
    int quarters = first[0];
    int second[] = maxDimes();
    int dimes = second[0];
    int nickels = maxNickels();
    System.out.println("The minimum number of coins you could use is: "+quarters+"quarters, "+dimes+" dimes and "+nickels+" nickels");

}
public static void main(String[] args) 
{
    makeChange();
}

1 个答案:

答案 0 :(得分:0)

由于您在input()内部调用maxQuarters(),因此要求您输入3次。 在maxDimes()maxNickels()中,您呼叫maxQuarters(),因此也呼叫input()

解决此问题的一种可能方法是在input()方法中调用main并将输入作为参数传递给您的其他方法,例如:

public static int input() {
    System.out.println("Please enter amount of change under 100 cents: ");
    Scanner input = new Scanner(System.in);
    int change = input.nextInt();
    if (change % 5 < 2) {
        change = change + (change % 5);
    } else if (change % 5 > 2) {
        change = change - (change % 5);
    }
    return change;

}

public static int[] maxQuarters(int input) {

    int quarters = input / 25;
    int leftover = input - 25*quarters;
    return new int[]{quarters, leftover};
}

public static int[] maxDimes(int input) {
    int first[] = maxQuarters(input);
    int change = first[1];
    int dimes = change / 10;
    int leftover = change - 10*dimes;
    return new int[]{dimes, leftover};
}

public static int maxNickels(int input) {
    int second[] = maxDimes(input);
    int change = second[1];
    int nickels = change / 5;
    return nickels;
}

public static void makeChange(int input) {
    int first[] = maxQuarters(input);
    int quarters = first[0];
    int second[] = maxDimes(input);
    int dimes = second[0];
    int nickels = maxNickels(input);
    System.out.println("The minimum number of coins you could use is: " + quarters + " quarters, " + dimes + " dimes and " + nickels + " nickels");

}

public static void main(String[] args) {
    int input = input();
    makeChange(input);
}