Reputation: 47
This is the code.
do {
System.out.println("Enter Product Code: ");
medicine = machine1.nextInt();
if (medicine==1) {
machine1.buy1();
machine1.addproduct();
}
if (medicine==2); {
machine1.buy2();
machine1.addproduct();
}
} while((String answer=='y') || (String answer=='Y'));
And it gives this error:
enter code drugstore1.java:96: error: ')' expected }while((String answer=='y'))||((String answer=='Y')); ^ drugstore1.java:96: error: ';' expected }while((String answer=='y'))||((String answer=='Y')); ^ drugstore1.java:96: error: ';' expected }while((String answer=='y'))||((String answer=='Y')); ^
It poof'ed after fixing other errors. I think I'm using it right.. But what is wrong?
Upvotes: 1
Views: 122
Reputation: 8387
Try to use double quote
and equalsignorecase
method in all you while condition like this:
while(answer.equalsignorecase("y"));
Before try to use nextLine()
when you want to insert string "y" with creating variable:
String answer= machine1.nextLine();
Like this:
System.out.println("Enter Product Code: ");
medicine = machine1.nextInt();
System.out.println("Enter y if you want leave: ");
String answer= machine1.nextLine();
Upvotes: 4
Reputation: 34424
it should be
while("y".equalsIgnoreCase(answer)){// will avoid null pointer exception if answer is null
if(medicine==1)
{
machine1.buy1();
machine1.addproduct();
}
else if(medicine==2) // better for performance as both if conditions are mutually exclusive
{
machine1.buy2();
machine1.addproduct();
}
}
Upvotes: 2
Reputation: 49656
I suggest you to write
while(answer.equalsIgnoreCase("y"));
intead of
while((String answer=='y'))||((String answer=='Y'));
You cannot define new variables inside logical conditions.
1. String answer [X] -> answer [V]
2. answer=='y' [X] -> answer.equals("y") [V]
3. answer.equals("y") || answer.equals("Y") [V] -> answer.equalsIgnoreCase("y") [V]
4. if(medicine==2); [X] -> if (medicine == 2) [V]
Upvotes: 5
Reputation:
Here are some guidelines:
Do not declare objects inside while() statements. Did you mean while(answer=="y")
?
Do not compare Strings using the == operator. Strings are compared with .equals()
. The ==
only checks if the two operands are at the same physical memory location.
Upvotes: 2
Reputation: 219077
You're trying to declare variables inside your condition:
String answer=='y'
How would a variable declaration be usable as a comparison?
Where should answer
be coming from? It doesn't exist anywhere in your code, so it's not clear at all what you're trying to accomplish there.
But once you do have an answer
variable in your code which potentially contains some 'y'
or 'Y'
value, you can compare it like this:
while(answer.equalsIgnoreCase("y"))
Additionally, you have a bug here:
if(medicine==2);
That semi-colon is going to silently terminate the if
block, and the following block of code will always execute regardless of the condition. Remove that semi-colon.
Upvotes: 2