I am trying to get this to ask the question over and over again while the user inputs a 'Y'. and stop and return the Event.displayFinalResults(); when the user inputs a 'N'
i am getting a continuous loop right now. I am missing something or my layout it wrong. Any help would be great.
System.out.println("Is there anymore amounts you want to add?(Y/N): ");
Scanner keyboard = new Scanner(System.in);
char choice = keyboard.next().charAt(0);
choice = Character.toUpperCase(choice);
if(choice == 'Y')
{
do
{
System.out.println("Is there anymore amounts you want to add?(Y/N): ");
choice = keyboard.next().charAt(0);
choice = Character.toUpperCase(choice);
readValidateAmountType();
readValidateAmount();
}
while(choice =='Y');
}
else
{
Event.displayFinalResults();
}
thanks again.
You program asks a Yes/No question, then if you answer Yes, it enter a loop which starts by asking the same question again, before asking for the amount value.
You might want to ask for the amount value before asking the Yes/No question again.
If user answer No, the loop will exit (after asking for one more amount value), but Event.displayFinalResults() will not be executed. Drop the else clause, so Event.displayFinalResults() whether it entered the if statement or not.
System.out.println("Is there anymore amounts you want to add?(Y/N): ");
Scanner keyboard = new Scanner(System.in);
char choice = keyboard.next().charAt(0);
choice = Character.toUpperCase(choice);
if (choice == 'Y')
{
do
{
readValidateAmountType();
readValidateAmount();
System.out.println("Is there anymore amounts you want to add?(Y/N): ");
choice = keyboard.next().charAt(0);
choice = Character.toUpperCase(choice);
}
while(choice =='Y');
}
Event.displayFinalResults();
You could do this using break; as follows:
do {
System.out.println("Is there anymore amounts you want to add?(Y/N): ");
choice = keyboard.next().charAt(0);
choice = Character.toUpperCase(choice);
if (choice !='Y') {
break;
}
readValidateAmountType();
readValidateAmount();
} while(true);
Event.displayFinalResults();
One problem I see with this is, your while loop is inside the if statement. Once you exit the while loop, it's NOT going to run the code inside the else block because the if condition was already true.
So try removing the else block. This will make sure the Event.displayFinalResults method is called once the while loop exits.
System.out.println("Is there anymore amounts you want to add?(Y/N): ");
Scanner keyboard = new Scanner(System.in);
char choice = keyboard.next().charAt(0);
choice = Character.toUpperCase(choice);
if(choice == 'Y')
{
do
{
System.out.println("Is there anymore amounts you want to add?(Y/N): ");
choice = keyboard.next().charAt(0);
choice = Character.toUpperCase(choice);
readValidateAmountType();
readValidateAmount();
}
while(choice =='Y');
}
Event.displayFinalResults();
Clear code and compact:
Scanner keyboard = new Scanner(System.in);
char choice;
do {
System.out.println("Is there anymore amounts you want to add?(Y/N): ");
choice = keyboard.next().charAt(0);
choice = Character.toUpperCase(choice);
if(choice == 'Y') {
readValidateAmountType();
readValidateAmount();
}
} while(choice == 'Y');
Event.displayFinalResults();
Try the following out:
public void answering(char answer){
if(answer == 'Y' || answer == 'y'){
System.out.println("Answering");
} else if(answer == 'N' || answer == 'n'){
System.out.println("Not answering");
}
Instead of looping, call this method when you want to ask...
Related
i had this problem where while looping, the output shows the loop but the invalid is also there. how do i separate the loop and the if...else statements?
below is the program code.
Scanner scan = new Scanner(System.in);
String option = new String("Y");
while (option.equalsIgnoreCase("Y")) {
System.out.println("Good Morning!!");
System.out.print("Do you want to continue [Y/N]: ");
option = scan.nextLine();
if (option.equalsIgnoreCase("N")) {
break;
} else {
System.out.println("invalid");
}
}
this is the output of the loop. the invalid is only supposed to show up when i put in a different letter other than y or n
Do you want to continue [Y/N]: y
invalid
Good Morning!!
Do you want to continue [Y/N]: y
invalid
Good Morning!!
and it was supposed to show like this
Good Morning!!
Do you want to continue [Y/N]: y
Good Morning!!
Do you want to continue [Y/N]: y
Good Morning!!
Do you want to continue [Y/N]: n
You're just cheking if it's a "N" but not a "Y" so it'll will show invalid for Y. You just have to add another else if and the last else with the invalid.
Scanner scan = new Scanner(System.in);
String option = new String("Y");
while (option.equalsIgnoreCase("Y")) {
System.out.println("Good Morning!!");
System.out.print("Do you want to continue [Y/N]: ");
option = scan.nextLine();
if (option.equalsIgnoreCase("N")) {
break;
}else if(option.equalsIgnoreCase("Y")){
continue;
}else {
System.out.println("invalid");
}
}
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Good Morning!!");
System.out.print("Do you want to continue [Y/N]: ");
String option = scan.nextLine().toUpperCase();
if ("N".equals(option))
break;
if ("Y".equals(option))
continue;
System.out.println("invalid");
}
You could also implement else if to check for acceptable character and remove the redundant check from the condition in while:
while (true) {
System.out.println("Good Morning!!");
System.out.print("Do you want to continue [Y/N]: ");
String option = scan.nextLine();
if (option.equalsIgnoreCase("N")) {
break;
} else if (!option.equalsIgnoreCase("Y")) {
System.out.println("invalid");
}
}
Iām trying to validate inputs from the user. The user needs to enter (y + press enter) many times. If the user presses enter without (y), is there a way to validate the enter key?
public static void getInput() {
Scanner input = new Scanner(System.in);
System.out.print("Press 'y' to continue, 'n' to exit: ");
char c = input.nextLine().charAt(0);
if (c == 'n') {
System.out.println("Exiting");
System.exit(0);
}
while (c != 'y') {
System.out.println("Invalid input!");
System.out.println("Press 'y' to continue, 'n' to exit: ");
c = input.nextLine().charAt(0);
}
if (c == 'n') {
System.out.println("Exiting");
System.exit(0);
}
}
Just check if the input line is empty:
String line = input.nextLine()
if(line.isEmpty())
//handle no input
This might help.
Scanner input = new Scanner(System.in);
while(true){
System.out.print("Press 'y' to continue, 'n' to exit: ");
char c = input.nextLine().charAt(0);
if(c == 'n'){
System.out.println("Exiting...");
break;
}
else if(c == 'y'){
//call your method here
//method();
System.out.println("User has input Y");
break;
}
else{
System.out.println("Please enter a valid keyword");
}
}
Or you can use a switch case.
I'm trying to get a code that gives several options to pick from and while I can get those to work it ends immediately after when I need it to go back to the options.
public static void main(String[] args) {
System.out.println("Hello, This is the math program");
System.out.println("Select an application from below: \n");
System.out.println("(1) pythagoraen");
System.out.println("(2) Subtraction");
System.out.println("(3) Multiplication");
System.out.println("(4) Division");
System.out.println("(5) Exit");
System.out.println("What is your Choice? ");
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
if (choice == 1) {
pythagoraen();
System.out.println(pythagoraen());
} if (choice == 2) {
subtraction();
} if (choice == 3) {
multiplication();
} if (choice == 4) {
division();
} if (choice == 5){
exitprogam();
}
}
public static void subtraction(){
Scanner input = new Scanner( System.in );
int number1;
int number2;
int difference;
System.out.print( "Enter First integer: " );
number1 = input.nextInt();
System.out.print( "Enter Second integer: ");
number2 = input.nextInt();
difference = number1 - number2;
System.out.printf( "The difference is %d\n", difference);
}
I've tried several different while loops in an attempt to get it to return to the options but it either endlessly loops or doesn't work.
EDIT: I've added one of the methods to it as an example. the case suggestion doesn't work as I think the format it too different
public static void main(String[] args) {
System.out.println("Hello, This is the math program");
System.out.println("Select an application from below: \n");
System.out.println("(1) pythagoraen");
System.out.println("(2) Subtraction");
System.out.println("(3) Multiplication");
System.out.println("(4) Division");
System.out.println("(5) Exit");
System.out.println("What is your Choice? ");
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
while(choice!=5){
if (choice == 1) {
pythagoraen();
System.out.println(pythagoraen());
} if (choice == 2) {
subtraction();
} if (choice == 3) {
multiplication();
} if (choice == 4) {
division();
} if (choice == 5){
exitprogam();
}
}}
Here's the only while code i can get to run. it infinitely loops itself.
Your best bet to achieve what you are looking to do is to use a Do-While loop. Pay attention to where you ask for the input and then should the choice be equal to your stopping condition, put that as the conditional in the while part of the loop.
While loops will run 0-N times, while Do-While loops always execute 1-N times. Use this to your advantage.
This is a good reference:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
You need to put the things you need to do over and over again, in a loop.
public static void main(String[] args) {
System.out.println("Hello, This is the math program");
System.out.println("Select an application from below: \n");
System.out.println("(1) pythagoraen");
System.out.println("(2) Subtraction");
System.out.println("(3) Multiplication");
System.out.println("(4) Division");
System.out.println("(5) Exit");
System.out.println("What is your Choice? ");
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
while(choice!=5){
if (choice == 1) {
pythagoraen();
}
else if (choice == 2) {
subtraction();
}
else if (choice == 3) {
multiplication();
}
else if (choice == 4) {
division();
}
System.out.println("What is your next Choice? ");
choice = input.nextInt();
}
}
If you need the print the menu again, then you can put that also inside the loop. What you are doing here, is asking the user for input and then choosing the operation you want to do. Then at the end, you ask the user again about what to do next. If the user enters 5, the while condition becomes false and it exits the loop.
I also removed the if choice == 5 condition because the while loop will handle that scenario. Also added else before each if after the first one. That's for efficiency so that it doesn't check rest of the matches if it is matched with the first one.
There are many ways to achieve this but a better way to do it is with the use of a switch. With switch statements you can have a number of execution paths which seem to fit this situation better then the while loop being used. However, a while loop and a switch statement can not really be compared in terms of efficiency as they are fundamentally different, as can be seen in this article. here is how the implementation would look like with switches:
public static void main(String[] args) {
int exitFlag = 0;
int choice = showMenu();
do {
switch (choice) {
case 1:
System.out.println("pythagoraen()");
break;
case 2:
System.out.println("subtraction()");
break;
case 3:
System.out.println("multiplication()");
break;
case 4:
System.out.println("division()");
break;
case 5:
System.out.println("exitprogam()");
exitFlag = 1;
break;
default:
System.out.println("Invalid Option()");
break;
}
if (exitFlag != 1) {
choice = showMenu();
}
}while (choice != 5);
}
private static int showMenu() {
System.out.println("Hello, This is the math program");
System.out.println("Select an application from below: \n");
System.out.println("(1) pythagoraen");
System.out.println("(2) Subtraction");
System.out.println("(3) Multiplication");
System.out.println("(4) Division");
System.out.println("(5) Exit");
System.out.println("What is your Choice? ");
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
return choice;
}
This is a lot cleaner and easier in the long run for refactoring. For more information on switches please refer to oracle docs.
Try this with the while loop
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
while(choice != 5) {
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
if (choice == 1) {
pythagoraen();
System.out.println(pythagoraen());
} if (choice == 2) {
subtraction();
} if (choice == 3) {
multiplication();
} if (choice == 4) {
division();
} if (choice == 5){
exitprogam();
}
}
So I am trying to create a program for an assignment where the user would pick an animal, and depending on that animal (dog/chicken/fish), how many legs it has. If the user did not select one of the 3 animals, the game would then ask the user if they would like to play again. If the answer is y, then the program would start over, but if it is n, then the program would stop. The error is near the bottom where it states "String gameAnswer = input.nextLine();". It says that I have to rename gameAnswer. Could anyone help me fix this so that the program would work?
Thanks in advance!
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Choose an animal: ");
String text = input.nextLine();
char n;
char y;
char gameAnswer = 'n';
do
{
switch (text) {
case "dog":
System.out.println("How many legs does a dog have?");
int dg = input.nextInt();
if(dg == 4)
{
System.out.println("You win!");
}
else
{
System.out.println("You lose!");
}
break;
case "chicken":
System.out.println("How many legs does a chicken have?");
int chkn = input.nextInt();
if(chkn == 2)
{
System.out.println("You win!");
}
else
{
System.out.println("You lose!");
}
break;
case "fish":
System.out.println("How many legs does a fish have?");
int fsh = input.nextInt();
if(fsh == 0)
{
System.out.println("You win!");
}
else
{
System.out.println("You lose!");
}
break;
default:
break;
}
}
while(gameAnswer == 'y');
System.out.println("I don't know that animal. Do you want to try again? (y/n)");
String gameAnswer = input.nextLine();
}
The prompting and reading of the line should be within your loop
NOT
while(gameAnswer == 'y');
System.out.println("I don't know that animal. Do you want to try again? (y/n)");
char gameAnswer = input.nextLine();
BUT
System.out.println("I don't know that animal. Do you want to try again? (y/n)");
gameAnswer = input.nextLine();
while(gameAnswer == 'y');
ALSO
gameAnswer is already defined, so do not redefine it.
AND ALSO
You probably want gameAnswer = input.nextLine().charAt (0);
EDIT
also move
System.out.println("Choose an animal: ");
String text = input.nextLine();
to after
do
I'm writing a relatively simple Java program that calculates discounts for shoppers if they have certain vouchers or bonuses. It's working okay, but I have an issue when the program asks the user if they have any vouchers.
If they type "n", they still have to go through the loop as if they responded with "y" once before they can exit. I know it's probably a dumb mistake in there somewhere, but it's been driving me crazy and I'd appreciate a pair of fresh eyes to once it over.
do {
System.out.println("Please enter the total price of the goods");
price = keyboard.nextDouble();
if (price < limits[0] || price > limits[1]) {
System.out.println("Invalid price. Please try again");
validPrice = false;
} else {
validPrice = true;
}
} while (!validPrice);
keyboard.nextLine();
do {
System.out.println("Does the customer have any additional discounts? y/n");
choice = keyboard.nextLine();
if (!choice.matches(inputRegexMatchPattern)) {
System.out.println("Invalid input ā please re-enter");
} else if (choice.toLowerCase().charAt(0) == 'y') ;
{
System.out.println(choice);
do {
System.out.println("What type of discount does the customer have? [L]oyalty Card/[D]iscount Voucher");
input = keyboard.nextLine();
if (!input.matches(discountRegexMatchPattern)) {
System.out.println("Invalid input ā please re-enter");
}
} while (!input.matches(discountRegexMatchPattern));
if (input.charAt(0) == 'l' || input.charAt(0) == 'L') {
voucherDiscounts += voucherDiscountsArray[0];
System.out.println("Loyalty Card discount accepted");
} else if (input.charAt(0) == 'd' || input.charAt(0) == 'D') {
voucherDiscounts += voucherDiscountsArray[1];
System.out.println("Discount Voucher accepted");
}
}
} while (!(choice.toLowerCase().charAt(0) == 'n'));
You have a semicolon here:
else if (choice.toLowerCase().charAt(0) == 'y') ;
What that means is your loop will continue to execute in spite of the selection you make. Java interprets this if statement as not having any body.
Remove the semicolon and you should be good to go.
The do while construct always performs the content of the loop BEFORE it actually tests the condition.
I guess what you want here is a simple while loop.