vendredi 28 août 2020

IF ELSE user input to set a string for printing later, not immediately

I've starting learning JAVA and we have a task but we were given a lot of info and I'm very confused.

We are sequentially taking input details from a user and printing it in a specific format at the end.

The last detail : Age needs to be taken as the number and then later printed in as an Age Bracket (i.e: 20 and under, 21 to 35, 36 - 70, 71 and over) depending on the input.

I have this for when the user enters their age:

    System.out.println("Enter Your Age:");
        age=input.nextInt();
            if (age <= 20) {
                String aB = "20 or under";
            }
            else if (age < 35 && age > 21) {
                String aB = "21-35";
            }
            else if (age < 70 && age > 36) {
                String aB = "36-70";
            }
            else {
                String aB = "71 or Over";
            }

And then this at the end to print it along with the other data collected. The error is stating variable aB cannot be found.

System.out.println( "\n" + fN + ". " + mN + ". " + lastName + "\n" + "\n" + houseNumber + " " + streetName + " " + streetType + "\n" + cityName + "\n" + "Age Bracket: " + aB);

I feel like I am over complicating it and confusing myself. The rest of the print statement works its just aB at the end. So I assume I've done something wrong in the if - else code.

I have found a lot of code on here for printing the answer right away after the user input but not for setting the if else outcome as a sting to be printed later. Not sure if it can even be done.

Aucun commentaire:

Enregistrer un commentaire