更改计算器程序java(循环)

时间:2016-03-16 16:23:09

标签: java loops calculator

编写一个重复读取0到0之间的整数的程序 100代表一些美分。转换那个数字 等于相当数量的季度,硬币,镍币和 便士。该程序应输出最大数量 适合的四分之一,然后适合的最大硬币数量 进入剩下的东西,等等。然后该程序将要求下一个 量。如果金额为负数,程序应该退出。

这是我到目前为止,我不知道如何让它循环或计算数字或每个硬币。

System.out.println("Enter number of cents (Negative value to quit):");
int cents;
cents = scan.nextInt();

while (cents > 0 )
{
    if (cents >= 25)
    {
        System.out.println("Quarter");
        cents -= 25;
    }
    else if ( cents >= 10 )
    {
        System.out.println("Dime");
        cents -= 10;
    }
    else if (cents >= 5 )
    {
        System.out.println("Nickle");
        cents -= 5 ;
    }
    else if (cents >= 1 )
    {
        System.out.println("Penny");
        cents -= 1;
    }
}

2 个答案:

答案 0 :(得分:0)

您可以将问题分解为两部分:

  • do询问金额while金额为非负数
  • 使用整数除法分解给定金额

1)在主方法中询问输入

Scanner scan = new Scanner(System.in);
int input;
do {
  input = scan.nextInt();
  decompose(input);
} while (input > 0);

2)用另一种方法写下分解:

public static void decompose(int cents) {
  if(cents >= 25) {
    int quot = cents / 25;
    System.out.println(quot + " Quarter");
    cents -= quot * 25;
  }

  if(cents >= 10) {
    int quot = cents / 10;
    System.out.println(quot + " Dime");
    cents -= quot * 10;
  }

  [...]
}

答案 1 :(得分:0)

我的建议是使用HashMap。您的代码看起来像这样:

System.out.println("Enter number of cents (Negative value to quit):");
Map<String, Long> countMap = HashMap<String, Long>();
countMap.put("Quarter", 0);
countMap.put("Dime", 0);
countMap.put("Nickle", 0);
countMap.put("Penny", 0);

   int cents;
   cents = scan.nextInt();

   while (cents > 0 )
   {
       if (cents >= 25)
       {
           System.out.println("Quarter");
           countMap.put("Quarter", countMap.get("Quarter")+1L);
           cents -= 25;
        }
        else if ( cents >= 10 )
        {
            System.out.println("Dime");
            countMap.put("Dime", countMap.get("Dime")+1L);
            cents -= 10;
        }
        else if (cents >= 5 )
        {
            System.out.println("Nickle");
            countMap.put("Nickle", countMap.get("Nickle")+1L);
            cents -= 5 ;
        }
        else if (cents >= 1 )
        {
            System.out.println("Penny");
            countMap.put("Penny", countMap.get("Penny")+1L);
            cents -= 1;
        }
}

现在你拥有所需的一切。

System.out.println("Quarter: " + countMap.get("Penny"));
System.out.println("Dime: " + countMap.get("Dime"));
System.out.println("Nickle: " + countMap.get("Nickle"));
System.out.println("Penny: " + countMap.get("Penny"));