samedi 29 décembre 2018

Using an If/Else statement with toString but boolean is only read as false [duplicate]

This question already has an answer here:

I'm still a basic programmer and am starting on a small program to help me with workouts. In my code, I'm using a boolean to determine two different statements in my toString method. However, I'm having trouble getting the if/else statement to read the boolean as true when necessary and as a result only the false toString statement is being printed on the console. What am I doing wrong?

package workoutPackage;

import java.util.Scanner;

public class WorkoutRegimeMenu {

    public static void main(String[] args) {
        Scanner menuChoice = new Scanner(System.in);
        int choice;
        do {
            System.out.println("*****Workout Regime Menu*****\n");
            System.out.println("1. Enter todays workout information");

            choice = menuChoice.nextInt();

            switch (choice) {
            case 1:
                Scanner sInput = new Scanner(System.in);
                Scanner iInput = new Scanner(System.in);
                boolean bWalk = false;

                System.out.println("What is the date of this workout?");
                String date = sInput.nextLine();

                System.out.println("What was your weight the morning of the workout? (in pounds)");
                int weight = iInput.nextInt();

                System.out.println("Did you walk at least an hour on this day? (y or n)");
                String walk = sInput.nextLine();
                if(walk == "y") {
                    bWalk = true;
                }
                WorkoutInformation enterInfo = new WorkoutInformation();
                enterInfo.setInfo(date, weight, bWalk);
                System.out.println(enterInfo);
                break;

            default:
                System.out.println("Please enter one of the numbered choices above");
                break;
            }
        } while (choice != 0);
    }
}



package workoutPackage;

public class WorkoutInformation {
    private String date;
    private int morningWeight;
    private boolean walk;

    public void setInfo(String workoutDate, int weight, boolean bWalk) {
        this.date = workoutDate;
        this.morningWeight = weight;
        this.walk = bWalk;

    }
    public String toString() {

        if (walk == true) {
            return String.format("On %s you weighed %d pounds, walked for about an hour, and then performed your workouts.", date, morningWeight);
        } else {
            return String.format("On %s you weighed %d pounds and then performed your workouts.", date, morningWeight);
        }
    }
}

If walk is true, then the first toString statement should print. However it is always read as false so only the second toString statement is printed.

Aucun commentaire:

Enregistrer un commentaire