Soren
Soren

Reputation: 1

How to turn portions of code into methods

Edit: At this point, I think I have a better understanding of how methods work, however, I don't understand how to get my method to return an arraylist. Here's the method, I need to be able to use BMI.get(i) later in the code, what am I doing wrong?

static ArrayList<Double> calcBMI(ArrayList <Integer> feet, ArrayList <Integer> inch, ArrayList <Double> wegt){
        ArrayList<Double> BMI = new ArrayList<Double>();
        for(int i = 0; i < feet.size(); i++) {
            double x = ((wegt.get(i) / (Math.pow(((feet.get(i) * 12) + inch.get(i)), 2))) * 703);
            BMI.add(x);
        }
        return ArrayList <Double> BMI;
    }

I'm taking a Java class that has us building on a code as we learn. The code is for a Body Mass Index (BMI) calculator. I'm not the best at coding, I'm really struggling to understand how methods are supposed to function and how I'm supposed to use them in the code. The way it's being explained in class doesn't make sense and I can't ask my teacher about it as I work during his office hours. I'm not asking for anyone to do my homework, I can't use someone elses code, what I'm looking for is advice and further problem solving as I figure this out.

I'm supposed to use at least 3 methods. The first method is a bmi calculation (static double calcBMI) that should take the input array lists and give me the BMI of each person. The second should, based on whether the person is male or female, return a char that tells me if the person is over, under, normal, or probably not overweight (static char weightClass). The third should take in all user inputs, and store them into relevant ArrayLists, my teacher added "You can probably create all of your ArrayLists in main, and then pass them in to a static void method".

Here's my code currently without the methods, it's fine that it can return a NaN if only one person is input, the code is exactly how the teacher wants it minus the methods:

import java.util.Scanner;
import java.util.ArrayList;

class assignment4b {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        ArrayList<String> names = new ArrayList <String>();
        ArrayList<Integer> feet = new ArrayList <Integer>();
        ArrayList<Integer> inch = new ArrayList <Integer>();
        ArrayList<Double> wegt = new ArrayList <Double>();
        ArrayList<Integer> fat = new ArrayList <Integer>();
        ArrayList<Character> sex = new ArrayList <Character>();
        char morepeople = 'y';
        int counter = 1;

        while(morepeople == 'y') {
            System.out.println("Input data for user " + counter + ":");
            counter ++;
            System.out.println("Name?");
            names.add(s.nextLine());
            System.out.println("Height:");
            System.out.println("Feet?");
            feet.add(Integer.parseInt(s.nextLine()));
            System.out.println("Inches?");
            inch.add(Integer.parseInt(s.nextLine()));
            System.out.println("Weight in pounds?");
            wegt.add(Double.parseDouble(s.nextLine()));
            System.out.println("Body fat percentage?");
            fat.add(Integer.parseInt(s.nextLine()));
            System.out.print("Enter male or female for sex.");
            sex.add(s.nextLine().charAt(0));
            System.out.println("Continue adding people? Enter y or n: ");
            morepeople = s.nextLine().charAt(0);
        }

        int undCount = 0;
        int normCount = 0;
        int probNotCount = 0;
        int overCount = 0;

        int mundCount = 0;
        int mnormCount = 0;
        int mprobNotCount = 0;
        int moverCount = 0;

        int fundCount = 0;
        int fnormCount = 0;
        int fprobNotCount = 0;
        int foverCount = 0;

        int peopleCount = names.size();
        int mCount = 0;
        int fCount = 0;

        ArrayList <Double> bmi = new ArrayList <Double>();

        for(int i = 0; i < names.size(); i++){
            String n = names.get(i);
            int f = feet.get(i);
            int in = inch.get(i);
            double w = wegt.get(i);
            int bf = fat.get(i);
            char sx = sex.get(i);
            double b = (w / (Math.pow(((f * 12) + in), 2)) * 703);
            bmi.add(b);
            System.out.println("Hello " + n + " your BMI is " + b + ".");
            if(b < 18.5){
                System.out.println("Underweight.");
                undCount ++;
                if(sx == 'f'){
                    fundCount ++;
                    fCount ++;}
                if(sx == 'm'){
                    mundCount ++;
                    mCount ++;}
                }
            else if(b < 25) {
                System.out.println("Normal weight.");
                normCount ++;
                if(sx == 'f'){
                    fnormCount ++;
                    fCount ++;}
                if(sx == 'm'){
                    mnormCount ++;
                    mCount ++;}
            }
            else if((sx == 'm' && bf > 24) || (sx == 'f' && bf > 31)){
                System.out.println("Overweight.");
                overCount ++;
                if(sx == 'f'){
                    foverCount ++;
                    fCount ++;}
                if(sx == 'm'){
                    moverCount ++;
                    mCount ++;}
            }
            else {
                System.out.println("Probably not overweight.");
                probNotCount ++;
                if(sx == 'f'){
                    fprobNotCount ++;
                    fCount ++;}
                if(sx == 'm'){
                    mprobNotCount ++;
                    mCount ++;}
            }
        }

        System.out.println("The percentage of males who are underweight is " + (100.0 * mundCount / mCount));
        System.out.println("The percentage of males who are normal weight is " + (100.0 * mnormCount / mCount));
        System.out.println("The percentage of males who are overweight is " + (100.0 * moverCount / mCount));
        System.out.println("The percentage of males who are probably not overweight is " + (100.0 * mprobNotCount / mCount));

        System.out.println("The percentage of females who are underweight is " + (100.0 * fundCount / fCount));
        System.out.println("The percentage of females who are normal weight is " + (100.0 * fnormCount / fCount));
        System.out.println("The percentage of females who are overweight is " + (100.0 * foverCount / fCount));
        System.out.println("The percentage of females who are probably not overweight is " + (100.0 * fprobNotCount / fCount));

    }
}

I managed to make the first two methods previously for a single input version of the code. The way I made the methods probably wasn't the best way but I don't understand how to do it any better, and I really don't understand how I'm supposed to use methods with array lists.

import java.util.Scanner;

class assignment3a {
    static double calcBMI(double feet, double inch, double wegt){
        double x = ((wegt / (Math.pow(((feet * 12) + inch), 2))) * 703);
        return x;
    }

    static char weightClass(double x, String sex, double pfat){
        if (x < 18.5) {
            return 'u';
        }
        else if (x >= 18.5 && x < 25) { //n
            return 'n';
        }
        else if (sex.equalsIgnoreCase("male") && pfat > 24 && x > 25) {
            return 'o';
        }
        else if (sex.equalsIgnoreCase("female") && pfat > 31 && x > 25) {
            return 'o';
        }
        else if (sex.equalsIgnoreCase("male") && pfat <= 24 && x > 25) {
            return 'p';
        }
        else if (sex.equalsIgnoreCase("female") && pfat <= 31 && x > 25) {
            return 'p';
        }
        else {
            return 5;
        }
    }

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.println("Please enter a name: ");
        String name = s.nextLine();
        System.out.println("Please enter height, feet then inches");
        System.out.println("Feet: ");
        double feet = Double.parseDouble(s.nextLine());
        System.out.println("Inches: ");
        double inch = Double.parseDouble(s.nextLine());
        System.out.println("Weight in pounds: ");
        double wegt = Double.parseDouble(s.nextLine());
        System.out.println("Body fat percentage: ");
        double pfat = Double.parseDouble(s.nextLine());
        System.out.println("Male or Female: ");
        String sex = s.nextLine();

        double x = calcBMI(feet, inch, wegt);

        weightClass(x, sex, pfat);

        System.out.println(name + "'s BMI is: " + x);

        if (weightClass(x, sex, pfat) == 'u') {
            System.out.println(name + " is underweight.");
        }
        else if (weightClass(x, sex, pfat) == 'n') {
            System.out.println(name + " is normal weight.");
        }
        else if (weightClass(x, sex, pfat) == 'o') {
            System.out.println(name + " is overweight.");
        }
        else if (weightClass(x, sex, pfat) == 'o') {
            System.out.println(name + " is overweight.");
        }
        else if (weightClass(x, sex, pfat) == 'p') {
            System.out.println(name + " is probably not overweight.");
        }
        else {
            System.out.println(name + " is probably not overweight.");
        }

    }
}

Upvotes: -7

Views: 117

Answers (1)

Gilbert Le Blanc
Gilbert Le Blanc

Reputation: 51559

I took your original code and organized it into classes and methods.

I created a User class to hold all the information for one user. This way, your code has one List, a list of User instances.

The User class is a plain Java getter/setter class. The class calculates the BMI and status of each user.

The Statistics class accumulates and prints the statistics. I could have put these methods in the main BMICalculator class. I made a separate class so the code is easier to read and understand.

I changed the statistics field names to make them more understandable. I fixed the divide by zero errors when you print the statistics.

The methods are short, do one thing, and return one primitive or class instance.

Writing code is a lot like writing an essay. Put the important points first and the details later. The reader of your code should never have to scroll up to see details. Don't use one letter field names unless the field name scope is less than 10 lines. Don't abbreviate too much. The code should be its own how documentation. The why is explained in comments.

Here's the complete runnable code. I made the additional classes inner classes so I could post the code as one block.

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class BMICalculator {

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

    public void calculateBMI(Scanner scanner) {
        List<User> userList = new ArrayList<>();
        char morePeople = 'y';
        int counter = 1;

        do {
            User user = getInputs(scanner, counter++);
            userList.add(user);
            System.out.println("Continue adding people? Enter y or n: ");
            morePeople = scanner.nextLine().toLowerCase().charAt(0);
        } while (morePeople == 'y');

        Statistics statistics = new Statistics();
        statistics.accumulateStatistics(userList);
        statistics.printStatistics();

    }

    public User getInputs(Scanner scanner, int counter) {
        System.out.println("Input data for user " + counter + ":");
        System.out.println("Name?");
        String name = scanner.nextLine();
        System.out.println("Height:");
        System.out.println("Feet?");
        int feet = Integer.parseInt(scanner.nextLine());
        System.out.println("Inches?");
        int inch = Integer.parseInt(scanner.nextLine());
        int height = feet * 12 + inch;
        System.out.println("Weight in pounds?");
        double weight = Double.parseDouble(scanner.nextLine());
        System.out.println("Body fat percentage?");
        int fatPercentage = Integer.parseInt(scanner.nextLine());
        System.out.println("Enter m(ale) or f(emale) for sex.");
        char sex = scanner.nextLine().toLowerCase().charAt(0);
        return new User(name, sex, fatPercentage, height, weight);
    }

    public class Statistics {

//      private int undCount = 0;
//      private int normaleCount = 0;
//      private int probNotCount = 0;
//      private int overCount = 0;

        private int maleUnderweightCount = 0;
        private int maleNormalCount = 0;
        private int maleProbablyNotCount = 0;
        private int maleOverweightCount = 0;

        private int femaleUnderweightCount = 0;
        private int femaleNormalCount = 0;
        private int femaleProbablyNotCount = 0;
        private int femaleOverweightCount = 0;

//      private int peopleCount = 0;;
        private int maleCount = 0;
        private int femaleCount = 0;

        public void accumulateStatistics(List<User> userList) {
            for (User user : userList) {
                char sex = user.getSex();
                if (sex == 'm') {
                    maleCount++;
                    char status = user.determineStatus();
                    if (status == 'u') {
                        maleUnderweightCount++;
                    } else if (status == 'o') {
                        maleOverweightCount++;
                    } else if (status == 'n') {
                        maleNormalCount++;
                    } else {
                        maleProbablyNotCount++;
                    }
                } else if (sex == 'f') {
                    femaleCount++;
                    char status = user.determineStatus();
                    if (status == 'u') {
                        femaleUnderweightCount++;
                    } else if (status == 'o') {
                        femaleOverweightCount++;
                    } else if (status == 'n') {
                        femaleNormalCount++;
                    } else {
                        femaleProbablyNotCount++;
                    }
                }
            }
            
//          undCount = maleUnderweightCount + femaleUnderweightCount;
//          normaleCount = maleNormalCount + femaleNormalCount;
//          overCount = maleOverweightCountt + femaleOverweightCount;
//          probNotCount = maleProbablyNotCount + femaleProbablyNotCount;
        }

        public void printStatistics() {
            System.out.println();
            double percent = calculatePercent(maleCount, maleUnderweightCount);
            System.out.println("The percentage of males who are underweight is "
                    + percent);
            percent = calculatePercent(maleCount, maleNormalCount);
            System.out.println("The percentage of males who are normal weight is "
                    + percent);
            percent = calculatePercent(maleCount, maleOverweightCount);
            System.out.println("The percentage of males who are overweight is " 
                    + percent);
            percent = calculatePercent(maleCount, maleProbablyNotCount);
            System.out.println("The percentage of males who are probably not overweight is "
                    + percent);
            System.out.println();
            
            percent = calculatePercent(femaleCount, femaleUnderweightCount);
            System.out.println("The percentage of females who are underweight is "
                    + percent);
            percent = calculatePercent(femaleCount, femaleNormalCount);
            System.out.println("The percentage of females who are normal weight is "
                    + percent);
            percent = calculatePercent(femaleCount, femaleOverweightCount);
            System.out.println("The percentage of females who are overweight is "
                    + percent);
            percent = calculatePercent(femaleCount, femaleProbablyNotCount);
            System.out.println("The percentage of females who are probably not overweight is "
                    + percent);
            System.out.println();
        }
        
        private double calculatePercent(int count, double value) {
            return (count > 0) ? (100.0 * value / count) : 0.0;
        }
    }

    public class User {

        private final char sex;

        private final double weight;

        private final int fatPercentage, height;

        private final String name;

        public User(String name, char sex, int fatPercentage, int height,
                double weight) {
            this.name = name;
            this.sex = sex;
            this.fatPercentage = fatPercentage;
            this.height = height;
            this.weight = weight;
        }

        public char determineStatus() {
            double bmi = calculateBMI();
            if (bmi < 18.5) {
                return 'u';
            } else if (bmi < 25.0) {
                return 'n';
            } else if ((sex == 'm' && fatPercentage > 24)
                    || (sex == 'f' && fatPercentage > 31)) {
                return 'o';
            } else {
                return 'p';
            }
        }

        public double calculateBMI() {
            return (weight / (Math.pow(height, 2)) * 703);
        }

        public char getSex() {
            return sex;
        }

        public int getFatPercentage() {
            return fatPercentage;
        }

        public int getHeight() {
            return height;
        }

        public double getWeight() {
            return weight;
        }

        public String getName() {
            return name;
        }

    }

}

Upvotes: -2

Related Questions