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.
Related
I've written this code:
while (choice > 2 && count <= 2) {
System.out.println("The number you have typed is invalid. Please try again.");
choice = s.nextInt();
count++;
}
if (choice == 1 && count <= 2) {
System.out.println("You have chosen teacher's information.");
t.information();
} else if (choice == 2 && count <= 2) {
System.out.println("You have chosen student's information.");
st.info();
} else {
System.out.println("You have been blocked.");
}
It works how I intended to, if I try more than 2 times, I'll be blocked, however, in this other project:
while (!rusern.equalsIgnoreCase(username) || !rpass.equals(password) && attempts <= 2) {
System.out.println("Login error. Your username is: " + rusern.equalsIgnoreCase(username) + " ,and password is: " + rpass.equals(password) + "\nPlease try again.");
System.out.println("Please enter your username:");
rusern = s.nextLine();
System.out.println("Enter your password:");
rpass = s.nextLine();
attempts++;
//here i have to use break;
}
if (rusern.equalsIgnoreCase(username) && rpass.equals(password) && attempts <= 2) {
System.out.println("You have succesfully logged in! Please continue: ");
} else {
System.out.println("You have been blocked.");
}
I have to use break; in the while loop, where I mentioned in the comment, because unless I used the break, it would show the questions over and over if I didn't answer correctly, without stopping, and when I finally answered right, it would have me blocked. So my question is, why wouldn't it work without the break like in the first project?
Both variables, the 'attempts' and 'count' and initialized the same, = 0.
a || b && c means a || (b && c) while I believe you intended it to mean (a || b) && c.
See Java operator precedence table: || and && don't have equal precedence.
So your loop should be:
while ((!rusern.equalsIgnoreCase(username) || !rpass.equals(password)) && attempts <= 2) {
package javaapplication1;
import java.util.Scanner;
public class JavaApplication1 {
public static void main(String[] args) {
System.out.println("What is the password?");
Scanner new2 = new Scanner(System.in);
int input = 0;
while(input <= 5 )
{
String password = new2.nextLine();
if(!password.equals("bluesky123")){
System.out.println("Incorrect password");
input++;
}
else if("bluesky123".equals(password)) {
System.out.println("You got it right!");
break;
}
else if(input == 5) {
System.out.println("maximum number of attempts reached");
break;
}
}
}
}
basically, once I hit the 5 loops, it just says "incorrect password" and breaks. not the "maximum attempts" message.
Allow me to annotate:
This if statement will always be evaluated:
if(!password.equals("bluesky123")){
System.out.println("Incorrect password");
input++;
}
This if statement will only be evaluated if the password is "bluesky123". In this case, it will always evaluate to true.
else if("bluesky123".equals(password)) {
System.out.println("You got it right!");
break;
}
There is no case when this if statement will ever be evaluated. Once if-else finds a statement that is true, it will skip all others in that section.
else if(input == 5) {
System.out.println("maximum number of attempts reached");
break;
}
In your case, you should consider a nested if (i.e. an if inside another if).
while(input <= 5 )
{
String password = new2.nextLine();
if(!password.equals("bluesky123")){
System.out.println("Incorrect password");
input++;
}
else {
System.out.println("You got it right!");
break;
}
if((input == 5) && (!password.equals("bluesky123"))) {
System.out.println("maximum number of attempts reached");
break;
}
}
Your logic has some flaws. You have to pay attention to how JAVA processes if / else if
https://www.tutorialspoint.com/java/if_else_statement_in_java.htm
I tested your code it is working! The only thing that you need to do is to move the follow line to inside the while loop
System.out.println("What is the password?");
Doing this it will print "Incorrect password" and then it will print again
"What is the password?"
Because in the way that it is working now seems that the software is not waiting the password to be retyped when in fact it is.
do {
System.out.println("Set the A param: ");
if(input.hasNextDouble() == true) {
A = input.nextDouble();
if(A == 0) {
System.out.println("Param A cannot be a 0!");
}
} else if(input.hasNextDouble() == false) {
System.out.println("Param A must be a number!");
}
} while(A == 0 || input.hasNextDouble() == false);
Hello, I'm really new in Java and I found an obstacle I can't resolve by myself.
Everything is okay until I enter some letter instead of number, then this do..while loop keeps repeating itself.
After some search I suppose this might be a problem with a Scanner buffer becouse I should clear it before every loop with input.nextLine() but I don't really know where in code should I put it.
Thanks for any help.
You only actually consume data from the scanner if input.hasNextDouble() is true.
Currently, if A == 0 and there are non-numeric data in the buffer then you'll indeed loop indefinitely.
You need to consume data from the buffer on all control paths. In particular, if there is something non-numeric in the buffer, then you need to consume and immediately discard it: input.next(); would be adequate.
Seems like you just want to get the value of A which should not be equal to 0 . Read comments
double A=0;
do {
System.out.println("Set the A param: ");
if(input.hasNextDouble() == true) { //check for valid value
A = input.nextDouble();
if(A == 0) {
System.out.println("Param A cannot be a 0!");
}
} else{ // no valid value found , print msg and jump over the previous input
input.nextLine();
System.out.println("Param A must be a number!");
}
} while(A == 0); // just check , if the desired value is received
// previously input.hasNextDouble() had no use cuz we already
// checked no double value found so will be false, don't use it
First, you should not write the opposing check in an else if. Just use else. And you shouldn't check == true, since the value is already a boolean.
Now, for you infinite loop problem, when hasNextDouble() is false, it means that the user entered something wrong (ignoring the potential end-of-stream issue). In that case you need to discard that bad input, which is best done by calling nextLine().
Java naming convention states that variables should start with lowercase letter, so A should be a.
Your code then becomes:
double a = 0;
do {
System.out.println("Set the A param: ");
if (input.hasNextDouble()) {
a = input.nextDouble();
if (a == 0) {
System.out.println("Param A cannot be a 0!");
}
} else {
input.nextLine(); // discard bad input
System.out.println("Param A must be a number!");
}
} while (a == 0);
Thank you for both answers, after first I wrote this:
do
{
System.out.println("Podaj wartość parametru A: ");
if(input.hasNextDouble() == true)
{
A = input.nextDouble();
if(A == 0)
{
System.out.println("Parametr A nie może być zerem!");
}
}
else if(input.hasNextDouble() == false)
{
System.out.println("Parametr A musi być liczbą!");
input.nextLine();
A = 0;
}
} while(A == 0);
And it worked but thanks to the second answer now I know how to do it better. :)
Thanks both of you once again.
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...
I was working on my assignment for my Java 1 class and I am getting an error that does not seem like it should be one. Can I get some help? It is saying that I have an else w/out if.
here is the if block
char placement = scan.next().toUpperCase().charAt(0);
if(placement == 'F')
{
System.out.print("Please Enter The Show To Be Added At The Beginning Of The List: ");
String show = scan.next();
TVShows.add(0, show);
}
else if(placement == 'R');
{
System.out.print("Please Enter The Show To Be Added At The End Of The List");
String show = scan.next();
TVShows.add(show);
}
else
{
System.out.println("Invalid Choice Please Try Again");
}
Remove the semi colon
else if (placement == 'R');
^
which is terminating the else if block statement