3
\$\begingroup\$

I am quite new to Java and I wanted to try and make a smoking calculator that tells the user how much they would save over a certain time period. I would appreciate if someone could tell me where they would improve my code and what other features they would add?

Should I always use objects when coding in java even for a basic program like this one?

import java.util.Scanner;

public class Calculator {
    public static void main(String args[]) {

        Scanner scan = new Scanner(System.in);

        //Packets
        System.out.println("How many packets do you smoke a week?");
        double packets = scan.nextDouble();

        //cost
        System.out.println("How much is each packet?");
        double cost = scan.nextDouble();

        //weekly
        double weekly;
        weekly = (cost*packets);
        System.out.println("In one week you would save: €" + weekly);

        //monthly
        double monthly;
        monthly = (weekly*4);
        System.out.println("In one month you would save: €" + monthly);

        //threeMonths
        double threeMonths;
        threeMonths = (weekly*12);
        System.out.println("In three months you would save: €" + threeMonths);

        //sixMonths
        double sixMonths;
        sixMonths = (weekly*26);
        System.out.println("In six months you would save: €" + sixMonths);

        //yearly
        double yearly;
        yearly = (weekly*52);
        System.out.println("In one year you would save: €" + yearly);

        //user input
        System.out.println("Enter a number of years and see how much you will save over that time period...");
        double user = scan.nextDouble();
        double userInput;
        userInput = (yearly*user);
        System.out.println("You would save €" + userInput + " in " + user + " years.");

          scan.close();
    }
}
\$\endgroup\$
  • \$\begingroup\$ "Should I always use objects when coding in java even for a basic program like this one?" In short: yes. In long: almost, because using objects (and dependency injection) makes your code flexible and reusable. Especially as a beginner you should get used to use objects until you have enough experience to spot the rare cases where you might use an utility class. \$\endgroup\$ – Timothy Truckle Apr 16 '17 at 16:32
1
\$\begingroup\$

Should I always use objects when coding in java even for a basic program like this one?

How would you not? Note that you are using an object in this program now, a Scanner object. You also use a Calculator class. Because of course that's how Java works. There are no methods outside of classes.

Now, should you make an intermediate class and objects? Maybe. Maybe not. I would like to see more methods here. For example, consider

    public static void displayForTimePeriod(String message, double amount, double multiplier) {
        System.out.println(message, amount * multiplier);
    }

That would allow you to simplify most of your code to something like

        double weekly = cost * packets;
        displayForTimePeriod("In one week you would save: €", weekly, 1.0);
        displayForTimePeriod("In one month you would save: €", weekly, 30/7.0);
        displayForTimePeriod("In three months you would save: €", weekly, 13.0);
        displayForTimePeriod("In six months you would save: €", weekly, 26.0);
        displayForTimePeriod("In one year you would save: €", weekly, 52.0);

You could go further and make a class, but the main thing that it would hold would be the amount. Note that that stays the same in every call.

I might add

        System.out.println("On average, you'll save €" + (weekly/7) + " every day.");

If you wanted, you could make your years calculation more accurate by including leap years. That would require you to get the current date from the system time. Remember to handle leap centuries. 2000 was a leap year, but 1900 was not and 2100 won't be.

I made the monthly number more accurate. Unless the month is February, there are more than twenty-eight days (four weeks) in a month. The usual approximation is thirty.

I fixed the quarterly (three months) number as well. There are thirteen weeks in most quarters (the exception is the first quarter when February does not have a leap day). Twelve weeks will be too few for every quarter.

\$\endgroup\$
0
\$\begingroup\$

Should I always use objects when coding in java even for a basic program like this one?

In general, it's easier to learn something if you start easy. It's better to learn driving a car in a small car than in a 1000PS Koenigsegg. If you're not in that learning phase, it depends, if it's a 'throw-away' app or a productive app.

To your code, I just reworked a small part of it, to give you an idea

  • I moved the scanner reads into separate methods
  • I introduced the enum type 'Modifier' (wich is veeeery badly named but I didn't come up with a better name, you can name it 'ThingThinger', it gives the same idea of what that type does), because you actually do the same thing several times with different values, which is a sign that you can wrap it into a loop.
  • I moved the calculation to a separate method
  • Also check the order of the methods, it's main first, then it's ordered by the order they are called within the main method.

    public class Calculator {
    
        private static Scanner scan;
    
        public static void main(String args[]) {
            scan = new Scanner(System.in);
    
            double packetsPerWeek = askForAmountOfPacketsPerWeek();
            double cost = askForCostPerPacket();
    
            Modifier[] modifiers = Modifier.values();
            for (Modifier modifier : modifiers) {
                double savings = calculateSavings(packetsPerWeek, cost, modifier);
                System.out.printf("You save %f$ %s\n", savings, modifier.getText());
            }
    
            scan.close();
        }
    
        private static double askForAmountOfPacketsPerWeek() {
            System.out.println("How many packets do you smoke a week?");
            return scan.nextDouble();
        }
    
        private static double askForCostPerPacket() {
            System.out.println("How much is each packet?");
            return scan.nextDouble();
        }
    
        private static double calculateSavings(double packetsPerWeek, double cost, Modifier modifier) {
            return packetsPerWeek * cost * modifier.getAmountOfWeeks();
        }
    
        private enum Modifier {
            WEEKLY(1, "weekly"), MONTHLY(4, "monthly"), YEARLY(52, "yearly");
    
            private final int amountOfWeeks;
            private final String text;
    
            Modifier(int amountOfWeeks, String text) {
                this.amountOfWeeks = amountOfWeeks;
                this.text = text;
            }
    
            public int getAmountOfWeeks() {
                return amountOfWeeks;
            }
    
            public String getText() {
                return text;
            }
        }
    }
    
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.