Issue
I am creating a coin calculator which breaks the penny value down into denominations, but I wish to make it so the user may choose to exclude a denomination of a coin, please see my code below. Im running into a wall here and struggling to think of a code that would allow this to happen, if anyone has a pointer I would really appreciate it. I have no problem creating a code where the user may choose which denomination to include.
int money;
int denom;
Scanner sc=new Scanner(System.in);
System.out.println("Please enter the amount of coins you have in penny value");
money = sc.nextInt();
System.out.println("Also the denomiation you would like exclude; 2, 1, 50p, 20p, 10p");
denom = sc.nextInt();
while (money > 0){
if (money >= 200) {
System.out.println("£2");
money -= 200;
}
else if (money >= 100) {
System.out.println("£1");
money -= 100;
}
else if (money >= 50) {
System.out.println("50p");
money -= 50;
}
else if (money >= 20) {
System.out.println("20p");
money -= 20;
}
else if (money >= 10) {
System.out.println("10p");
money -= 10;
}
else if (money >= 1) {
System.out.println("1p");
money -= 1;
}
Solution
I'd say this is the probably the most basic way of doing it without creating a separate method for it. Setting the denom to the excluded value and then checking whether a coin is equal to the denom before subtracting could work, as there aren't that many coins anyway.
int money;
int denom;
Scanner sc=new Scanner(System.in);
System.out.println("Please enter the amount of coins you have in penny value");
money = sc.nextInt();
System.out.println("Also the denomiation you would like exclude; 2, 1, 50p, 20p, 10p");
String input = sc.next(); //saving user input as a string
if (input.contains("p"))
{ //converting string to int by removing the p
denom = Integer.parseInt(input.substring(0, input.indexOf("p")));
}
else
{ //if there's no p, multiply its value by 100
denom = Integer.parseInt(input) * 100;
}
while (money > 0){
if (money >= 200 && denom != 200) {
System.out.println("£2");
money -= 200;
}
else if (money >= 100 && denom != 100) {
System.out.println("£1");
money -= 100;
}
else if (money >= 50 && denom != 50) {
System.out.println("50p");
money -= 50;
}
else if (money >= 20 && denom != 20) {
System.out.println("20p");
money -= 20;
}
else if (money >= 10 && denom != 10) {
System.out.println("10p");
money -= 10;
}
else if (money >= 1) {
System.out.println("1p");
money -= 1;
}
}
Answered By - Sankeeth Ganeswaran