The user will enter 30, but to get the math to work, we need to turn this into .3. You can do this by dividing by 100 or multiplying it by .01. Then you multiply by the original price to determine the amount of the discount.
This logic, to get the discount amount, should be in a separate method, which we call from the act method. We want to show we can write a method that calculates a value and return, and also that we can call that method properly. So this method will be setup to accept the price of the product, and the discount percentage (the original integer value). The logic in the method will then do the math above, converting it to a real percentage and multiplying the price. It then returns that discount amount.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.text.DecimalFormat; /** * Write a description of class MyWorld here. * * @author (your name) * @version (a version number or a date) */ public class MyWorld extends World { /** * Constructor for objects of class MyWorld. * */ public MyWorld() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super ( 600 , 400 , 1 ); } public void act() { DecimalFormat money = new DecimalFormat( "$0.00" ); double price; int discount; price=Double.parseDouble(Greenfoot.ask( "What is the price of the product?" )); discount = Integer.parseInt(Greenfoot.ask( " What is the amount of the discount? Please enter as in a numerical value of two numbers, such as 35 for 35% " )); discountAmount(); showText( "Price: " + money.format(price), getWidth()/ 2 , getHeight()/ 2 ); showText( "Discount: " + money.format(discount) , getWidth()/ 2 , getHeight()/ 2 + 20 ); showText( "Sale Price: " + money.format(disconutAmount()), getWidth()/ 2 , getHeight()/ 2 + 40 ); Greenfoot.stop(); } public double discountAmount() { double discountAmount = (price*(discount/ 100 )); return discountAmount; } } |