Delete this token (else) - java

ok so i was playing round with some code and adding new line as i'm learning java. i got this error "syntax error token "else" delete this token".
As im new to this could some one explain this error and what i should do, so i do not make the same mistake again.
class Years {
public static void main (String[] args){
int age = 30;
if (age <30){
System.out.println("you are young");
}else{
System.out.println("you are old ");
if (age > 1240);
}else{
System.out.println("dam son your still a bady");
if (age < 25);
{
System.out.println("You are Really old son!!");
}else{
System.out.println("you better Hide your age son!!");
}
}
}
}

You have an unconditional else block - you can't follow that with another else. So this is fine:
if (condition) {
...
} else if (otherCondition) {
...
} else {
...
}
But this isn't - because it doesn't make sense:
if (condition) {
...
} else {
...
} else {
...
}
An else block without a condition is meant to run unconditionally if the condition above it was not satisfied - in your case, the middle block is always run, so it's meaningless to have another.
Also note that you have:
if (age > 1240);
... which I suspect you didn't really intend. Likewise:
if (age < 25);
Both of these are if statements with empty bodies.
It's really unclear what you expect to achieve in each case - but I'd strongly advise you to have something like:
// List all the age boundaries in increasing order...
if (age < 25) {
...
} else if (age < 30) {
...
} else if (age < 1240) {
...
} else {
...
}
Now exactly one of those bodies will be executed.

You have a condition which doesn't make sense:
if (something) {
} else {
} else {
}
How do you expect the system to know which "else" block to use? else logically means "otherwise, do this" and effectively captures all remaining conditions. You can't do that more than once.

It looks like you've got an if statement that's in the wrong place. Try this instead:
if (age <30){
System.out.println("you are young");
}else if (age > 1240){
System.out.println("you are old ");
}else{
System.out.println("dam son your still a bady");
if (age < 25);
{
System.out.println("You are Really old son!!");
}else{
System.out.println("you better Hide your age son!!");
}
}
}

First understand how if statements work in any programming language. For example this is a good resource for you to understand if statements in java. I'm not 100% sure about what are you trying achieve by this code. But I can give you one hint. When branching, use not only else but also else if().

Related

if...else statement will only print my if line

I've run into a problem with my multi branch if...else statements. In the challenge question they ask us to print out a line if certain variables are true|false. My statements will only print my if statement, however they compile. I feel I'm either missing something in my if statement that allows it to continue if a statement is not true|false.
Here is what I have:
if ( isBalloon && isRed ) {
isBalloon=false;
isRed=false;
System.out.println("Not a balloon");
}
else if ( isBalloon && isRed ) {
isBalloon=true;
isRed=false;
System.out.println("Balloon");
}
Also, for clarity; when we do a multi branch statement (else if) requires variable declaration, where as (else) is just anything that makes our if statement false. Is this correct?
I think this is easiest explained by pointing out that 'else if' in java isn't a separate keyword. So it is equivalent to the following (which is harder to read but points out why your code is executed only once)
if ( isBalloon && isRed ) {
isBalloon=false;
isRed=false;
System.out.println("Not a balloon");
} else {
if ( isBalloon && isRed ) {
isBalloon=true;
isRed=false;
System.out.println("Balloon");
}
}
this is what else if really does. When your code runs it hits the first if condition and when it is correct it will run the associated block. it then doesn't process the else block. (that is the idea: only if or else runs, not both).
It looks like if / else if / else if / else has multiple blocks on the same level but secretly they are nested.
for instance
if (a) {
// case a
} else if (b) {
// case b
} else if (c) {
// case c
} else {
// otherwise:
}
is actually:
if (a) {
// case a
} else {
if (b) {
// case b
} else {
if (c) {
// case c
} else {
// otherwise
}
}
}

Optimization for: while (true)

I'm using a
while (true)
{
if (x == y)
{
break;
}
else
{
//do stuff
}
}
loop like so, the frame is just an example frame, as the actual code itself is convoluted and overly complicated that it requires a "break;" statement in multiple different areas for multiple different conditions.
My question is; Is there a way to write a loop statement without the loop checking for a condition at all? Is there a more efficient way to write an infinite loop other than while(true)?
edit: (java)
edit2:
while (a < b)
{
while (true)
{
if (c < d)
{
if (e == null)
{
//do alot of stuff
break;
}
else
{
//do something
}
}
else if (d > c)
{
if (e == null)
{
//do alot of stuff
break;
}
else
{
//do something
}
}
else if (d == c)
{
break;
}
}
a = a + 1;
}
Is there a way to write a loop statement without the loop checking for a condition at all? Is there a more efficient way to write an infinite loop other than while(true)?
You can write an infinite loop in multiple ways, but they are all equivalent. Neither is really more efficient than the others:
while (true) { ... }
do { ... } while (true);
for (;;) { ... }
Depending on the actual code, it may make sense to reverse the "break-loop-logic" into "continue-loop-logic", as in:
boolean continueLoop;
do {
continueLoop = false;
// ... do stuff ...
if ( some condition ) {
continueLoop = true;
}
// ... do stuff ...
} while (continueLoop);
For your particular example, you may move the logic for breaking in the if statement to the while condition:
while (x != y) {
// do stuff
}
In fact, if your original while loop had multiple conditions for breaking, you might be able to move them all to the while condition, e.g.
while (!cond1 && !cond2 ... ) {
// execute
}
Yes there are a lot ways you can do this. For example you can declare a variable outside a loop put a condition based on variable value and reset that variable inside a loop, hence loop will run infinitely without checking internal conditions.
Read this for examples :-
https://en.wikipedia.org/wiki/Infinite_loop

Why does nothing happen when a "if ... <=0" criteria is met?

I have a player controlled object which is set to 100 health. With each hit from an enemy it goes down. The problem is, after it reaches 0 health, it still keeps going further into the negatives. I have a popup set
private void playerHealth(){
if (player.health <= 0)
JOptionPane.showMessageDialog(null, "you lose");
System.exit(0);
}
so that in theory, it should pop up after health is <=0. However, when I try to run it, it just opens and closes immediately. I can see the window for a split second. If I delete the
JOptionPane.showMessageDialog(null, "you lose");
System.exit(0);
and replace it with say,
player.isAlive = false;
(isAlive is set true for player, enemies and all bullets), the health will continue to decrease past the negatives.
This part might help as well: Its the code to delete the dead enemies and bullets, there is nothing similar for player, so that may be the problem.
private void removeDead(){
for (int i = 0; i <bullets.size(); i++){
if (bullets.get(i).isAlive == false )
bullets.remove(i);
}
for (int i = 0; i <mobs.size(); i++){
if (mobs.get(i).isAlive == false )
mobs.remove(i);
}
for (int i = 0; i <mobBullets.size(); i++){
if (mobBullets.get(i).isAlive == false )
mobBullets.remove(i);
}
bullets.trimToSize();
mobs.trimToSize();
mobBullets.trimToSize();
}
So any help is appreciated. Thank you. (all the code is from an online tutorial, which is why I dont know anything.)
If you want both statements to be executed, surround them in a block :
private void playerHealth() {
if (player.health <= 0) {
JOptionPane.showMessageDialog(null, "you lose");
System.exit(0);
}
}
Without the curly braces, System.exit(0); is not part of the if statement and will always be executed, which explains the it just opens and closes immediately.
I agree with the previous answer.
However, you need to know how to avoid such problems in the future. Use an IDE or other editor that will automatically indent your code for you. Here is what one did to the failing if-statement:
private void playerHealth() {
if (player.health <= 0)
JOptionPane.showMessageDialog(null, "you lose");
System.exit(0);
}
The problem becomes much more obvious.
It looks like you missed a { on your if statement, if you want to execute a block of code in an if statement you need to do
if(something){
response;
}
So it should be this:
private void playerHealth() {
if (player.health <= 0) {
JOptionPane.showMessageDialog(null, "you lose");
System.exit(0);
}
}

I think I'm using IF statements wrongly

So I'm trying to make a GPA calculator using Java and I'm stuck on one of the first steps. I'm trying to write a code that takes the input of the user and then converts it into a number, I will then use that number later on to calculate the GPA. Here's my code so far:
public class data {
public static void main(String[] args) {
String english;
double v1 = 0;
Scanner reader = new Scanner(System.in);
System.out.println("Enter your english grade");
english= reader.nextLine();
if (strcmp(english,"A+")==0) {
v1 = 4.4;
}
if (strcmp(english,"A")==0) {
v1= 4.0;
}
if (strcmp(english,"A-")==0) {
v1= 3.6;
}
if (strcmp(english,"B+")==0) {
v1= 3.4;
}
if (strcmp(english,"B")==0) {
v1= 3;
}
if (strcmp(english,"B-")==0) {
v1= 2.6;
}
if (strcmp(english,"C+")==0) {
v1= 2.4;
}
if (strcmp(english,"C")==0) {
v1= 2;
}
if (strcmp(english,"C-")==0) {
v1= 1.6;
}
if (strcmp(english,"D+")==0) {
v1= 1.4;
}
if (strcmp(english,"D")==0){
v1= 1;
}
if (strcmp(english,"D-")==0) {
v1= 0.6;
}
if (strcmp(english,"F")==0) {
v1= 0.0;
}
else {
v1=0.0;
}
System.out.println(v1);
As you can see, Im printing out V1 at the end just for checking, But it keeps giving V1 as 0.0, the value when the user enters "F". If I comment that piece of the code like this:
/*if (strcmp(english,"F")==0) {
v1= 0.0;
}*/
then the output value it gives is 0.6, the value when the user enters D-. I think I'm supposed to put a return system somewhere? Although I really am not sure. Any help would be greatly appreciated.
(If it wasn't established already, I am a beginner to java :P )
EDIT: Guys when I try to use the Switch method (Im using eclipse) it gives me this error: "Cannot switch on a value of type String for source level below 1.7. Only convertible int values or enum constants are permitted". The solution it provides then leads to further complications so I'd like to avoid switch statements :/
if (strcmp(english,"F")==0) {
v1= 0.0;
}
else {
v1=0.0;
}
with that else you say - as long as it is not F, put 0.0 in v1.
The way you've written it, v1 will be 0.0 unless english is "F".
You need to use else if:
if (strcmp(english,"A+")==0) {
v1 = 4.4;
} else if (strcmp(english,"A")==0) {
// and so on
Some Java folk like to switch on strings. But that's a reasonably new feature in Java and the break statements that you'll need to introduce can obfuscate.
use switch case, as mentioned. It will be helpful as you may get confused with large number of if statements.
switch(english){
case "A+":
v1=4.4
break;
case "D-":
v1=0.6
break;
default:
v1=0.0;
break;
}
You might find this quite useful:
if(english.equalsIgnoreCase("A+"))
//do stuff...
else if(english.equalsIgnoreCase("A-"))
//do other stuff and so on...
the equalsIgnoreCase() method ignores case sensitive, if this is not what you're looking for you might try equals() instead.
The new Java version also introduced switch-case for Strings too so your code can become this one:
switch(english){
case "A+":
//do stuff...
break;
case "A-":
//do other stuff... and so on...
break;
}
Remove the last else part. it should be good.It is because no matter what the grade is, if it is not "F", it is going to the else statement and setting it to 0.0
An else attaches to the previous if; you do a lot of stuff and then at the end you do if(...) { v1 = 0.0 } else { v1 = 0.0 }, setting the value to 0.0 in any case.
You might want to use else if at every step, which will solve the immediate problem.
You are saying if string is not F, set the value of v1= 0.0
if(strcmp(english,"F")==0) {
v1= 0.0;
}
else {
v1=0.0;
}
Basically, you are setting the value to zero whether the user enters F, or anything else:
if (strcmp(english,"F")==0) {
v1= 0.0;
}
else {
v1=0.0;
}
see here, you've set v1 to 0.0 if (strcmp(english,"F")==0), but also if the user didn't enter F. I think you meant to put something else in stead of 0.0 in the if part, like this:
if (strcmp(english,"F")==0) {
v1= /*something else*/;
}
else {
v1=0.0;
}
because that's what seemed to surprise you.
Replace the code strcmp(english,"F")==0 with following english.equal ("A+")
Try this:
String english= reader.nextLine();
if (english.equals("A+")) {
v1 = 4.4;
}
else if (english.equals("A")) {
v1= 4.0;
}
else if (english.equals("A-")) {
v1= 3.6;
}
else{
v1=0.0;
}

Why is it saying my If statement is unreachable?

The compiler is saying that the statement is unreachable on the line with the if statement. I'm not overly familiar with Java.
public double calculate()
{
total_usage_charge = getUsageCharge();
total_charge = rate + total_usage_charge;
return total_charge;
if("A".equals(package_plan.toUpperCase()) && getUsageCharge() > 14.95)
{
sB = getUsageCharge() - 14.95;
System.out.println("You're spending more money than you should. If you switched to Plan B you would save:$" + sB);
}
}
Because you're returning from the method by executing this:
return total_charge;
So the next statement is never going to be executed.
You return (return total_charge;) from your method just before the if statement. No code after a return can ever be executed (except the relevant finally block if your return statement is located in a try...catch...finally).
You are returning before calling if statement so its unreacheable .
A method returns to the code that invoked it when it reaches a return statement.
return total_charge;
You method returns at this point, post which any code won't be reachable.
you have putted return statement above IF. so when compiler comes on this statement everytime it returns from there and if can not executed anytime so, remove returns statement or put it below if Condition.
Code will not be executed after return statement.following block of code is causing problem i.e.
return total_charge;
So you will have to remove this line or put it at the end.!
public double calculate()
{
total_usage_charge = getUsageCharge();
total_charge = rate + total_usage_charge;
if("A".equals(package_plan.toUpperCase()) && getUsageCharge() > 14.95)
{
sB = getUsageCharge() - 14.95;
System.out.println("You're spending more money than you should. If you switched to Plan B you would save:$" + sB);
}
return total_charge;
}
Just like that ;)
**if("A".equals(package_plan.toUpperCase()) && getUsageCharge() > 14.95)
{
sB = getUsageCharge() - 14.95;
System.out.println("You're spending more money than you should. If you switched to Plan B you would save:$" + sB);
}
else if("A".equals(package_plan.toUpperCase()) && getUsageCharge() > 19.95)
{
sC = getUsageCharge() - 19.95;
System.out.println("You're spending more money than you should. If you switched to Plan C you would save:$" + sC);
}
else if("B".equals(package_plan.toUpperCase()) && hours < 10)
{
sA = getUsageCharge() - 9.95;
System.out.println("You're spending more money than you should. If you switched to Plan A you would save:$" + sA);
}
else if("B".equals(package_plan.toUpperCase()) && getUsageCharge() > 19.95)
{
sC = getUsageCharge() - 19.95;
System.out.println("You're spending more money than you should. If you switched to Plan C you would save:$" + sC);**
}**
Did u meant to comment it, if yes do it right. or this is error and unreachable statement according to the code provided.
Comment it with /* your code to comment */

Categories

Resources