PURPOSE: To code a program using a while-loop with a nested(embedded) if-else structure within an if-else structure
INSTRUCTIONS: Code a program that prints messages based on the validity of a password and a person’s age.
1.In a sentinel-controlled while-loop, where the first iteration of this repetition structure is automatically entered,
a.ask for a password. The password is “MonthyPython”.
i.When the password is wrong print, “Invalid Password!” and the while-loop can either continue or stop.
ii.Otherwise, the password is correct, so ask for an age.
1)If the age is greater than 17 print “Shangri-La welcomes you to your earthly paradise!”
2)Otherwise, age is less than or equal to 17, so print, “Sorry, NO under-age patrons allowed!”
b.There are 2 double-selection ifs. One is nested within the other. Is the nested if-else within the body of the if that tests for an invalid password or its else?
2.Use printf() and format specifiers.
- Exit the main()
****SAMPLE OUTPUT**** What is the password? MontyPithy
Invalid password!
Do you want to try again? Enter ‘Y’ or ‘N’: y
What is the password? MonthyPython
Enter your age: 16
Sorry, NO under-aged patrons allowed!
Do you want to try again? Enter ‘Y’ or ‘N’: y
What is the password? MonthyPython
Enter your age: 25
Shangri-La welcomes you to your earthly paradise!
Do you want to try again? Enter ‘Y’ or ‘N’: n
Thank you! Have a nice day!
****HERE IS MY CODE BELOW****CAN'T SEEM TO GET IT RIGHT**** /** * Auto Generated Java Class. */ import java.util.Scanner;
public class testLU {
public static void main(String[] args) {
//create scanner to capture input from keyboard
Scanner input = new Scanner(System.in);
String pass;
int age = 0;
char keepGoing = 'Y';
char stop = 'N';
boolean valid = true;
while(Character.toUpperCase(keepGoing) == 'Y')
{
System.out.printf("What is the password%n");
pass = input.nextLine();
if (pass.equals("MonthyPython"))
{
System.out.printf("Enter your age: %n");
age = input.nextInt();
if (age > 17)
{
System.out.printf("Shangri-La welcomes you to your "+
"earthly paradise!%n");
}
else
if (age <= 17)
{
System.out.printf("Sorry, NO underaged patrons allowed!%n");
}
}
else
{
System.out.printf("Invalid password!%n");
}
{
System.out.printf("%nDo you want to keep going? Enter \'Y\'"+
"or \'N\': ");
keepGoing = input.nextLine().charAt(0);
{
System.out.printf("Thanks you!%n"); }
}
}
}
}
Aucun commentaire:
Enregistrer un commentaire