自动售货机改变Java

时间:2016-03-05 05:19:39

标签: java casting

我对Java很新。我收到了一个错误。我知道造成它的原因是double(changeLeft),但是我需要将结果变为双倍,以便显示正确的变化,但我不知道如何做到这一点。

我不允许使用便士。最小的变化是季度。

我相信我要做的就是演员?但老实说我很失落。

非常感谢任何帮助/建议!

import java.util.Scanner;

public class Cash {


    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

    int itemCost = 0;
    int moneyInserted = 0;
    int changeLeft = 0;
    int hundred = 0;
    int fifty = 0;
    int twenty = 0;
    int ten = 0;
    int five = 0;
    int toonie = 0;
    int loonie = 0;
    double quarter = 0;

    System.out.println("Item cost?");
    itemCost = scanner.nextInt();

    System.out.println("Amount given?");
    moneyInserted = scanner.nextInt();

    changeLeft = moneyInserted - itemCost;

    hundred = changeLeft / 100;
    changeLeft = changeLeft % 100;

    fifty = changeLeft / 50;
    changeLeft = changeLeft % 50;

    twenty = changeLeft / 20;
    changeLeft = changeLeft % 20;

    ten = changeLeft / 10;
    changeLeft = changeLeft % 10;

    five = changeLeft / 5;
    changeLeft = changeLeft % 5;

    toonie = changeLeft / 2;
    changeLeft = changeLeft % 2;

    loonie = changeLeft / 1;
    changeLeft = changeLeft % 1;

    quarter = (double)changeLeft; 


    System.out.println("Change Due($): \n" +
             hundred + " Hundred\n" + fifty + " Fifty\n" + twenty +
             " Twenty\n" + ten + " Ten\n" + five + " Five\n" + toonie +
             " Toonie\n" + loonie + " Loonie\n" +
             quarter + " Quarter");        
    }
}

1 个答案:

答案 0 :(得分:0)

您可以将所有内容更新为双打。请注意扫描仪中的Double.valueOf(String)。

    public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

double itemCost = 0;
double moneyInserted = 0;
double changeLeft = 0;
double hundred = 0;
double fifty = 0;
double twenty = 0;
double ten = 0;
double five = 0;
double toonie = 0;
double loonie = 0;
double quarter = 0;

System.out.println("Item cost?");
itemCost = Double.valueOf(scanner.next());

System.out.println("Amount given?");
moneyInserted = Double.valueOf(scanner.next());

changeLeft = moneyInserted - itemCost;

hundred = changeLeft / 100;
changeLeft = changeLeft % 100;

fifty = changeLeft / 50;
changeLeft = changeLeft % 50;

twenty = changeLeft / 20;
changeLeft = changeLeft % 20;

ten = changeLeft / 10;
changeLeft = changeLeft % 10;

five = changeLeft / 5;
changeLeft = changeLeft % 5;

toonie = changeLeft / 2;
changeLeft = changeLeft % 2;

loonie = changeLeft / 1;
changeLeft = changeLeft % 1;

quarter = (double)changeLeft; 


System.out.println("Change Due($): \n" +
         hundred + " Hundred\n" + fifty + " Fifty\n" + twenty +
         " Twenty\n" + ten + " Ten\n" + five + " Five\n" + toonie +
         " Toonie\n" + loonie + " Loonie\n" +
         quarter + " Quarter");


}