This is one of my first attempts to use Java and I tried my best, but I need to shorten it so it’s not so long.
Important is that it keeps all the coins of the Euro. It’s a German code so geld means money.
This part of the code System.out.println(rgeldt + " mal 2 Euro");
just means how often the 2 euros have to be ejected.
public static void Rueckgaberechner(Double geld) { System.out.println("Rueckgeld: "); int rgeldt = 0; while (geld >= 200) { geld = geld - 200; rgeldt = rgeldt + 1; } if (rgeldt >= 1) { System.out.println(rgeldt + " mal 2 Euro"); } int rgeldO = 0; while (geld >= 100) { geld = geld - 100; rgeldO = rgeldO + 1; } if (rgeldO >= 1) { System.out.println(rgeldO + " mal 1 Euro"); } int rgeldf = 0; while (geld >= 50) { geld = geld - 50; rgeldf = rgeldf + 1; } if (rgeldf >= 1) { System.out.println(rgeldf + " mal 50 Cent"); } int rgeldtw = 0; while (geld >= 20) { geld = geld - 20; rgeldtw = rgeldtw + 1; } if (rgeldtw >= 1) { System.out.println(rgeldtw + " mal 20 Cent"); } int rgeldten = 0; while (geld >= 10) { geld = geld - 10; rgeldten = rgeldten + 1; } if (rgeldten >= 1) { System.out.println(rgeldten + " mal 10 Cent"); } int rgeldfive = 0; while (geld >= 5) { geld = geld - 5; rgeldfive = rgeldfive + 1; } if (rgeldfive >= 1) { System.out.println(rgeldfive + " mal 5 Cent"); } int rgeldtwo = 0; while (geld >= 2) { geld = geld - 2; rgeldtwo = rgeldtwo + 1; } if (rgeldtwo >= 1) { System.out.println(rgeldtwo + " mal 2 Cent"); } int rgeldone = 0; while (geld >= 1) { geld = geld - 1; rgeldone = rgeldone + 1; } if (rgeldone >= 1) { System.out.println(rgeldone + " mal 1 Cent"); } }
Advertisement
Answer
You can put it into a own function:
public static void Rueckgaberechner(Double geld) { System.out.println("Rueckgeld: "); geld = anzahlRueckgeld(200,geld, " mal 2 Euro"); geld = anzahlRueckgeld(100,geld, " mal 1 Euro"); geld = anzahlRueckgeld(50,geld, " mal 50 cent"); geld = anzahlRueckgeld(20,geld, " mal 20 cent"); geld = anzahlRueckgeld(10,geld, " mal 10 cent"); geld = anzahlRueckgeld(5,geld, " mal 5 cent"); geld = anzahlRueckgeld(2,geld, " mal 2 cent"); anzahlRueckgeld(1,geld, " mal 1 cent"); } public static double anzahlRueckgeld(int amount, double geld ,String text) { int rgeldt =0; while (geld >= amount) { geld = geld - amount; rgeldt = rgeldt + 1; } if (rgeldt >=1) { System.out.println(rgeldt +text); } return geld; }
BTW: By convention, method names in java should start with lower case character