Getting an else without if statement:
import java.util.Scanner;
public class LazyDaysCamp
{
public static void main (String[] args)
{
int temp;
Scanner scan = new Scanner(System.in);
System.out.println ("What's the current temperature?");
temp = scan.nextInt();
if (temp > 95 || temp < 20);
System.out.println ("Visit our shops");
else if (temp <= 95)
if (temp >= 80)
System.out.println ("Swimming");
else if (temp >=60)
if (temp <= 80)
System.out.println ("Tennis");
else if (temp >= 40)
if (temp < 60)
System.out.println ("Golf");
else if (temp < 40)
if (temp >= 20)
System.out.println ("Skiing");
}
}
I need to use a cascading if which is why it looks like that. Also, could you please let me know if I did the cascading if correctly? I haven’t been able to find a good example of cascading if so I just did my best from knowing what cascading means.
LazyDaysCamp.java:14: error: 'else' without 'if'
else if (temp <= 95)
^
1 error
That’s the error I’m getting
Óscar López
230k37 gold badges309 silver badges383 bronze badges
asked Oct 25, 2012 at 0:07
3
Remove the semicolon at the end of this line:
if (temp > 95 || temp < 20);
And please, please use curly brackets! Java is not like Python, where indenting the code creates a new block scope. Better to play it safe and always use curly brackets — at least until you get some more experience with the language and understand exactly when you can omit them.
answered Oct 25, 2012 at 0:09
Óscar LópezÓscar López
230k37 gold badges309 silver badges383 bronze badges
0
The issue is that the first if if (temp > 95 || temp < 20);
is the same using normal indentation as
if (temp > 95 || temp < 20)
{
}
That is if the temp is not between 20 and 95 then execute an empty block. There is no else for this.
The next line else then has no if corresponding to it and thus produces your error
The best way to deal with this is always uses braces to show what is executed after the if. This does not mean the compiler catches the errors but first you are more likely to see any issues by seeing the indentation and also the errors might appear more readable. However you can use tools like eclipse, checkstyle or FindBugs that will tell you if you have not used {} or used an empty block.
A better way might be, sorting out the logic as you are retesting things
if (temp > 95 || temp < 20)
{
System.out.println ("Visit our shops");
} else if (temp >= 80)
{
System.out.println ("Swimming");
} else if (temp >=60)
{
System.out.println ("Tennis");
} else if (temp >= 40)
{
System.out.println ("Golf");
} else if (temp >= 20)
{
System.out.println ("Skiing");
}
answered Oct 25, 2012 at 0:13
mmmmmmmmmmmm
32k27 gold badges88 silver badges115 bronze badges
I am going to reformat this for you. If you use curly brackets, you will never have this problem.
public class LazyDaysCamp
{
public static void main (String[] args)
{
int temp;
Scanner scan = new Scanner(System.in);
System.out.println ("What's the current temperature?");
temp = scan.nextInt();
if (temp > 95 || temp < 20) //<-- I removed the semicolon that caused the error
{
System.out.println ("Visit our shops");
}
else if (temp <= 95)
{
if (temp >= 80)
{
System.out.println ("Swimming");
}
else if (temp >=60)
{
if (temp <= 80)
{
System.out.println ("Tennis");
}
else if (temp >= 40)
{
if (temp < 60)
{
System.out.println ("Golf");
}
else if (temp < 40)
{
if (temp >= 20)
{
System.out.println ("Skiing");
}
}
}
}
}
}
}
answered Oct 25, 2012 at 1:28
byteherderbyteherder
3312 silver badges9 bronze badges
Содержание
- Java Hungry
- [Solved] else without if error
- [Fixed] error: ‘else’ without ‘if’
- Example 1: Producing the error by ending if statement with a semi-colon
- Explanation:
- Solution:
- Example 2: Producing the error by missing the closing bracket in if condition
- Explanation:
- Solution:
- Example 3: Producing the error by having more than one else clause for an if statement
- Explanation:
- Solution:
- Understanding Common Errors In Java
- 1. ’;’ expected
- 2. cannot find symbol
- 3. illegal start of expression
- 4. class, interface, or enum expected
- 5. reached end of file while parsing
- 6. missing return statement
- 7. ‘else’ without ‘if’
- 8. ‘(‘ expected or ‘)’ expected
- 9. case, default, or ‘>’ expected
- 10. ‘.class’ expected
- 11. invalid method declaration; return type required
- 12. unclosed character literal
- 13. unclosed string literal
- 14. incompatible types
- 15. missing method body
- 16. unreachable statement
Java Hungry
Java developers tutorials and coding.
[Solved] else without if error
else without if error is mostly faced by the java beginners. As the name suggests java compiler is unable to find an if statement associated with your else statement. else statements do not execute unless they are associated with the if statement. As always, first, we will produce the error before moving on to the solution.
[Fixed] error: ‘else’ without ‘if’
Example 1: Producing the error by ending if statement with a semi-colon
Output:
/ElseWithoutIf.java:8: error: ‘else’ without ‘if’
else <
^
1 error
Explanation:
The statement if(input > 100); is equivalent to writing
if (input > 100)
<
>
i.e. input is greater than 100 then execute an empty block. There is no else block for this. As a result, the next line else block does not have a corresponding if block, thus, produces the error: else without if.
Solution:
The above compilation error can be resolved by removing the semicolon.
Output:
input is less than or equal to 100
Example 2: Producing the error by missing the closing bracket in if condition
Just like the above example, we will produce the error first before moving on to the solution.
Explanation:
In the above example, if condition closing bracket is missing, hence, we are getting the else without if error.
Solution:
The above compilation error can be resolved by inserting the missing closing bracket as shown below.
Output:
inside else
Example 3: Producing the error by having more than one else clause for an if statement
Output:
/ElseWithoutIf3.java:12: error: ‘else’ without ‘if’
else
^
1 error
Explanation:
In the above scenario, you are chaining the two elses together that is not correct syntax, hence, resulting in the error. The correct syntax is given below:
Solution:
The above compilation error can be resolved by providing correct if-elseif-else syntax as shown below.
Output:
input is less than 100
The best way to deal with error: ‘else’ without ‘if’ is always to use curly braces to show what is executed after if. Learn to indent the code too as it helps in reading and understanding.
Источник
Understanding Common Errors In Java
When we were building our automated common error feedback feature on Mimir Classroom, we analyzed millions of stack traces that our students received when completing their coursework on our platform. In this post, you will find the errors we found to be most troubling to students in Java and some tips on how to approach them.
To start off, here is a quick refresher on how to read an error in the Java stack trace.
1. ’;’ expected
This error means that you forgot a semicolon in your code. If you look at the full error statement, it will tell you where in your code you should check within a few lines. Remember that all statements in Java must end in a semicolon and elements of Java like loops and conditionals are not considered statements.
2. cannot find symbol
This error means that Java is unable to find an identifier that it is trying to work with. It is most often caused by the following:
- You misspelled a variable name, class name, or a keyword somewhere. Remember that Java is case sensitive.
- You are trying to access a variable or class which does not exist or can not be accessed.
- You forgot to import the right class.
3. illegal start of expression
This error usually occurs when your code does not follow Java’s standard structure. Check the nesting of your variables and ensure that all your < >and ( ) are in the right place..
4. class, interface, or enum expected
This error is usually caused by misplaced < >. All code in Java needs to be contained within a class, interface, or enum. Ensure that all of your code is within the < >of one of those. We often have seen this error when there is an extra > at the end of your code.
5. reached end of file while parsing
This error usually occurs when you are missing a > somewhere in your code. Ensure that for every < you have one >in the right place.
6. missing return statement
This error usually means one of two things:
- Your method is expecting a return statement but is missing one. Ensure that if you declared a method that returns something other than void and that it returns the proper variable type.
- Your return statements are inside conditionals who’s parameters may not be reached. In this case, you will need to add an additional return statement or modify your conditionals.
7. ‘else’ without ‘if’
This error means that Java is unable to find an if statement associated to your else statement. Else statements do not work unless they are associated with an if statement. Ensure that you have an if statement and that your else statement isn’t nested within your if statement.
8. ‘(‘ expected or ‘)’ expected
This error means that you forgot a left or right parenthesis in your code. If you look at the full error statement, it will tell you where in your code you should check. Remember that for every ( you need one ).
9. case, default, or ‘>’ expected
This error means that your switch statement isn’t properly structured. Ensure that your switch statement contains a variable like this: switch (variable). Also ensure that every case is followed by a colon (:) before defining your case.
10. ‘.class’ expected
This error usually means that you are trying to declare or specify a variable type inside of return statement or inside of a method calls. For example: “return int 7;» should be «return 7;»
11. invalid method declaration; return type required
Every Java method requires that you declare what you return even if it is nothing. «public getNothing()» and «public static getNumber()» are both incorrect ways to declare a method.
The correct way to declare these is the following: «public void getNothing()» and «public static int getNumber()»
12. unclosed character literal
This error occurs when you start a character with a single quote mark but don’t close with a single quote mark.
13. unclosed string literal
This error occurs when you start a string with a quotation mark but don’t close with a second quotation mark. This error can also occur when quotation marks inside strings are not escaped with a backslash.
14. incompatible types
This error occurs when you use the wrong variable type in an expression. A very common example of this is sending a method an integer when it is expecting a string. To solve this issue, check the types of your variables and how they are interacting with other types. There are also ways to convert variable types.
15. missing method body
This error commonly occurs when you have a semicolon on your method declaration line. For example «public static void main(String args[]);». You should not have a semicolon there. Ensure that your methods have a body.
16. unreachable statement
This error means that you have code that will never be executed. Usually, this is after a break or a return statement.
Источник
- the
error: 'else' without 'if'
in Java - Reasons for
error: 'else' without 'if'
in Java - Fix the
error: 'else' without 'if'
in Java
Today, we will learn about an error saying 'else' without 'if'
while writing code in Java. We will also figure out the possible reasons causing this error and find its solution.
the error: 'else' without 'if'
in Java
Usually, this kind of error is faced by newbies in Java programming. Before moving toward the causes and solution for this error, let’s write a program that produces this error and understand it.
So, assuming that we are Python experts and beginners in Java. So, we will write the Java program containing if-else
as follows.
Example Code:
//import libraries
import java.util.Scanner;
//decide future activity based on the current temperature
public class Test{
public static void main (String[] args){
int temp;
Scanner scan = new Scanner(System.in);
System.out.println ("What's the current temperature?");
temp = scan.nextInt();
if (temp > 95 || temp < 20);
System.out.println ("Visit our shops");
else if (temp <= 95)
if (temp >= 80)
System.out.println ("Swimming");
else if (temp >=60)
if (temp <= 80)
System.out.println ("Tennis");
else if (temp >= 40)
if (temp < 60)
System.out.println ("Golf");
else if (temp < 40)
if (temp >= 20)
System.out.println ("Sking"); }//end main()
}//end Test Class
Error:
In this program, we get the current temperature from the user and decide our future activity based on the current temperature. The image above shows that we are getting a logical error about which NetBeans IDE informs at compile time.
So, we cannot even execute the code until we resolve the error. For that, we will have to know the possible reasons below.
Reasons for error: 'else' without 'if'
in Java
The error itself is explanatory, which says that a Java compiler cannot find an if
statement associated with the else
statement. Remember that the else
statement does not execute unless they’re associated with an if
statement.
So, the possible reasons are listed below.
- The first reason is that we forgot to write the
if
block before theelse
block. - The closing bracket of the
if
condition is missing. - We end the
if
statement by using a semi-colon.
How to solve this error? Let’s have a look at the following section.
Fix the error: 'else' without 'if'
in Java
Example Code:
//import libraries
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int temp;
Scanner scan = new Scanner(System.in);
System.out.println("What's the current temperature?");
temp = scan.nextInt();
if (temp > 95 || temp < 20) {
System.out.println("Visit our shops");
}//end if
else if (temp <= 95) {
if (temp >= 80) {
System.out.println("Swimming");
} //end if
else if (temp >= 60) {
if (temp <= 80) {
System.out.println("Tennis");
}//end if
else if (temp >= 40) {
if (temp < 60) {
System.out.println("Golf");
}//end if
else if (temp < 40) {
if (temp >= 20) {
System.out.println("Sking");
}//end if
}//end else-if
}//end else-if
}//end else-if
}//end else-if
}//end main()
}//end Test Class
Output:
What's the current temperature?
96
Visit our shops
We removed the semi-colon (;
) from the end of the if
statement and placed the {}
for each block to fix an error saying 'else' without 'if'
.
It is better to use curly brackets {}
until we are expert enough and know where we can omit them (we can omit them when we have a single statement in the block).
[ Return to Main Page |
Next: Run-time Errors ]
A «compile-time» error is one which prevents your code from compiling. This page describes 14 of the most common errors you will encounter. Compile-time errors are divided into three categories:
- Lexical: These generally occur when you include disallowed characters in your code (e.g.
int #people = 10;
). - Syntactical: These occur when your code is «out of order» (e.g.
for (int i=0; i++; i<10)
). - Semantic: These occur when the meaning of your code is unclear (e.g. two variables with the same name).
Note that the exact wording of these errors may vary, depending on which development environment you are using.
Errors described on this page (click to jump to that error):
- Cannot return a value from a method of type void
- ‘Class’ or ‘interface’ expected
- Class should be delcared abstract; it does not define…
- Else without if
- Expected: ;, {, }, (, or )
- Identifier expected / Illegal character
- Incompatible types / Inconvertible types (cannot cast)
- Method does not return a value / Missing return statement
- Method not found
- Not a statement
- Return type required
- Unreachable statement
- Variable already defined
- Variable not declared
Cannot return a value from a method of type void
When a method is declared as having a return type of void
, it cannot contain any return
statements which return a value (it can, however, contain a return
statement by itself, which will simply end the execution of the method). This problem is usually caused by accidentally making a method be of type void
when it shouldn’t be or by accidentally including a return
statement where there shouldn’t be one.
Example 1: Incorrect Code | Example 1: Fixed Code |
This method has a return type of |
We change the return type of this method in order to fix the problem. |
01 public void getName() 02 { return this.name; 03 } |
01 public String getName() 02 { return this.name; 03 } |
‘Class’ or ‘interface’ expected
This error will most likely be caused when you omit the keyword class
or interface
, as seen in the example below.
Example 1: Incorrect Code | Example 1: Fixed Code |
Here, we do not have either keyword present. |
We add in |
01 public Test 02 { 03 public void someMethod() 04 { System.out.println("Hello, world!"); 05 } 06 } |
01 public class Test 02 { 03 public void someMethod() 04 { System.out.println("Hello, world!"); 05 } 06 } — OR — 01 public interface Test 02 { 03 public void someMethod(); 04 } |
Class should be delcared abstract; it does not define…
This error arises when implementing an interface. Recall that when you say implements SomeInterface
for a certain class, you guarantee that you have written all of the methods specified within that interface. If you are missing at least one of the methods which is listed in the interface, Java will not let your code compile.
As an example, consider an interface TestInterface
which looks like:
public interface TestInterface { public int methodOne(); public String methodTwo(String z); public boolean methodThree(); }
Using TestInterface
, consider the following example.
Example 1: Incorrect Code | Example 1: Fixed Code |
We receive an error message in this case because we implement |
To allow this program to compile, we add in a «stub» for the required method. This is the quick way around the problem: in most cases, you will want to actually write a method body for this method so that it does what it was intended to do. |
01 public class Test implements TestInterface 02 { 03 private int y = 700; 04 05 public int methodOne() 06 { int x = this.y - 1; 07 return x; 08 } 09 10 public String methodTwo(String z) 11 { String label = "Val: " + z; 12 return label; 13 } 14 } |
01 public class Test implements TestInterface 02 { 03 private int y = 700; 04 05 public int methodOne() 06 { int x = this.y - 1; 07 return x; 08 } 09 10 public String methodTwo(String z) 11 { String label = "Val: " + z; 12 return label; 13 } 14 15 public boolean methodThree() 16 { return false; 17 } 18 } |
Note that when you are implementing methods in the interface, the method signatures must match exactly. That is, if the interface expects that you implement a method public String longer(String a, String b)
, then you must write a method with exactly the same name, exactly the same return type, and exactly the same parameters (in this case, two String
s).
Else without if
This error occurs when you have an else
or else if
clause without an if
clause above it. This is most likely because you have accidentally forgotten/added extra { or } braces, or you have placed an else
clause in the wrong place, as illustrated in the example below. The key idea is that every else
clause needs to have an associated if
clause which occurs before it.
Example 1: Incorrect Code | Example 1: Fixed Code |
Here, we have accidentally placed the |
We place the |
01 String text = "abaaba"; 02 03 if (text.length() >= 6) 04 { text += text; 05 else 06 { text += text.substring(3); 07 } 08 } |
01 String text = "abaaba"; 02 03 if (text.length() >= 6) 04 { text += text; 05 06 } 07 else 08 { text += text.substring(3); 09 } |
Expected: ;, {, }, (, or )
Java is very specific about use of characters such as semicolons, brackets, or braces. Forgetting a semicolon is the simplest of these errors, and is fixed by placing a semicolon at the end of the line which causes the error. Brackets can be more complicated, because you may have to read through several nested if
statements or loops in order to make sure that all brackets «match up» with each other properly. This is one of the reasons why indenting your code properly is a good idea.
Example 1: Incorrect Code | Example 1: Fixed Code |
Here, lines 6, 7, and 10 will give us compile-time errors because we have forgot to include brackets, a semicolon, and a close-brace respectively. |
We add these in to fix the problems. |
01 public class Test 02 { 03 public void getName() 04 { int k = 10; 05 06 if k == 10 07 { k++ 08 } 09 } 10 |
01 public class Test 02 { 03 public void getName() 04 { int k = 10; 05 06 if (k == 10) 07 { k++; 08 } 09 } 10 } |
Identifier expected / Illegal character
An identifier is another term for a variable. In Java, every variable name must begin with a letter/underscore and can then have any combination of letters, numbers, and underscores. The example below illustrates two cases you may run into.
Example 1: Incorrect Code | Example 1: Fixed Code |
The variable name |
To fix this, we change these to valid variable names. |
01 private String[] 10Names; 02 private int wtPer#ofPeople; |
01 private String[] tenNames; 02 private int wtPerNumberOfPeople; |
Incompatible types / Inconvertible types (cannot cast)
In a Java assignment statement, the type of the variable on the left hand side must be the same as the type of the variable on the right hand side (or it needs to be able to be cast first in order to make it work). The example below would give three ‘incompatible types’ error messages.
Example 1: Incorrect Code | Example 1: Fixed Code |
Lines 5, 6, and 7 all give us errors. This is because an |
We change these three statements so that the primitive type / Object type is the same on both sides of the assignment (=) sign. |
01 String theAge = "Twenty-two"; 02 int x = 22; 03 boolean b = false; 04 05 theAge = x; 06 x = b; 07 b = theAge; |
01 String theAge = "Twenty-two"; 02 int x = 22; 03 boolean b = false; 04 05 theAge = "Thirty-three"; 06 x = 33; 07 b = true; |
Note that one common exception to this rule is that an int
value can be assigned to a char
value and vice-versa (this is because every character is actually represented as an integer ASCII value).
This error may also occur when trying to pass a value of one type into a method which expects another. An example of this is below.
Example 2: Incorrect Code | Example 2: Fixed Code |
Here, we try to pass a |
To fix this, we change the type of the variable which is being passed. Alternately, we could have also changed the type of the actual parameter to be a |
01 String theAge = "Twenty-two"; 02 int result = calcNewAge(theAge); 03 04 public int calcNewAge(int theAge) 05 { return theAge / 2 + 7; 06 } |
01 int theAge = 22; 02 int result = calcNewAge(theAge); 03 04 public int calcNewAge(int theAge) 05 { return theAge / 2 + 7; 06 } |
You may also get a similar error if you are attempting to cast incorrectly. Recall that a primitive type may not be cast to an object or vice-versa. When casting between two objects, recall that object «A» may be cast to be of the same type as object «B» only if B’s class extends A’s class. As an example, consider a class Cat
which extends the class Animal
.
Example 3: Incorrect Code | Example 3: Fixed Code |
Here, lines 2 and 3 are incorrect attempts at casting because neither |
Line 2 is a correct cast because |
01 Cat c = new Cat("Sparky", "black"); 02 Animal a = (Animal) c; 03 String theCat = (String) c; |
01 Animal a = new Animal("Sparky"); 02 Cat c = (Cat) a; |
Method does not return a value / Missing return statement
In Java, every method which does not have a return type of void
must have at least one return
statement.
Example 1: Incorrect Code | Example 1: Fixed Code |
The return type of this method is |
Instead of printing these values to the screen, we return them. |
01 public String getFortune() 02 { if (this.age >= 19) 03 { System.out.println("Good times ahead"); 04 } 05 else 06 { System.out.println("Hailstorms unavoidable"); 07 } 08 } |
01 public String getFortune() 02 { if (this.age >= 19) 03 { return "Good times ahead"; 04 } 05 else 06 { return "Hailstorms unavoidable"; 07 } 08 } |
This compile-time error can have a very subtle point which is often overlooked. If the return type of a method is not void
, Java needs to ensure that the method will return a value in every possible case. That is, if all of your return
statements are nested within if
statements, Java will disallow the compilation process to continue because there is a chance that no return
statement will be reached. The example below illustrates this.
Example 2: Incorrect Code | Example 2: Fixed Code |
In this example, we get a compile-time error because Java sees a possibility of this method not returning a value (if |
To fix this, we ensure that the method will return a value in all possible cases by adding an |
01 public String chatMethod() 02 { if (this.age <= 18) 03 { return "MSN"; 04 } 05 else if (this.age > 19 && this.age <= 30) 06 { return "ICQ"; 07 } 08 } |
01 public String chatMethod() 02 { if (this.age <= 18) 03 { return "MSN"; 04 } 05 else if (this.age > 19 && this.age <= 30) 06 { return "ICQ"; 07 } 08 else 09 { return "BBS"; 10 } 11 } |
Note that an easy way to «fix» this error is to simply add a meaningless return
statement at the end of the method, such as return -1;
or return null;
. This often leads to problems elsewhere, such as causing the method to return unintended values.
Method not found
In Java, recall that a method’s signature consists of the method’s name and the types of its actual parameters. For example, the method public void move(int howFar)
has the signature move(int)
. When a method call is made, a method with a signature exactly matching that of the method call must exist (e.g. the method name, the number of parameters, and the types of all parameters must match exactly). This error is illustrated below.
Example 1: Incorrect Code | Example 1: Fixed Code |
Line 3 calls a method which has signature |
To fix this, we can modify the |
01 String first = "CN Tower"; 02 String second = "Calgary Tower"; 03 String res = this.larger(first, second); 04 05 public int larger(int a, int b) 06 { if (a > b) 07 { return a; 08 } else 09 { return b; 10 } 11 } |
01 String first = "CN Tower"; 02 String second = "Calgary Tower"; 03 String res = this.larger(first, second); 04 05 public String larger(String a, String b) 06 { if (a.length() > b.length()) 07 { return a; 08 } else 09 { return b; 10 } 11 } |
Also note that this error may occur if you do not have the correct import
statements at the top of your class.
Not a statement
Each line of Java code must have some sort of meaningful purpose. The compile-time error «not a statement» is usually the result of typing only part of a statement, leaving it incomplete and meaningless. One example of how this may occur (there are many) is seen below. In general, asking yourself «what was I trying to do with this line of code?» is sufficient to fix the problem.
Example 1: Incorrect Code | Example 1: Fixed Code |
Line 5 will cause the error in this case, as the line |
We change this line to be a valid, meaningful statement («set the value of |
01 int grades[] = new int[2]; 02 int x; 03 grades[0] = 96; 04 grades[1] = 93; 05 grades[1]; 06 System.out.println(x); |
01 int grades[] = new int[2]; 02 int x; 03 grades[0] = 96; 04 grades[1] = 93; 05 x = grades[1]; 06 System.out.println(x); |
Return type required
For each method, Java requires a return type (e.g. String, int, boolean
). Note that void
is also considered to be a «return type» even though a method with a void
return type does not return a value.
Example 1: Incorrect Code | Example 1: Fixed Code |
An error is caused because the |
Two possible solutions to this problem are suggested (each would depend on the context of how the method is to be actually used in your program). |
01 private theAnswer() 02 { System.out.println("42"); 03 } |
01 private void theAnswer() 02 { System.out.println("42"); 03 } — OR — 01 private int theAnswer() 02 { return 42; 03 } |
Unreachable statement
This error usually occurs if you have a statement placed directly after a return
statement. Since Java executes code line-by-line (unless a method call is made), and since a return
statement causes the execution of the program to break out of that method and return to the caller, then anything placed directly after a return
statement will never be reached.
Example 1: Incorrect Code | Example 1: Fixed Code |
Line 4 is directly after a |
We switch lines 3 and 4 to ensure that nothing is after the |
01 public String oneMoreA(String orig) 02 { String newStr = orig + "A"; 03 return newStr; 04 this.counter++; 05 } |
01 public String oneMoreA(String orig) 02 { String newStr = orig + "A"; 03 this.counter++; 04 return newStr; 05 } |
You (may) also get this error if you place a statement outside of a method, which could be the result of { and } braces not being matched up properly.
Variable already defined
This compile-time error is typically caused by a programmer attempting to declare a variable twice. Recall that a statment such as int temp;
declares the variable named temp
to be of type int
. Once this declaration has been made, Java can refer to this variable by its name (e.g. temp = 15;
) but does not let the programmer declare it a second time by including the variable type before the name, as seen in the example below.
Example 1: Incorrect Code | Example 1: Fixed Code |
Here, we have declared the variable |
We have fixed the problem by only declaring the variable once (at line 3) and we refer only to the variable’s name on line 6. |
01 int a = 7; 02 int b = 12; 03 int temperature = Math.max(a, b); 04 05 if (temperature > 10) 06 { int temperature = 0; 07 } |
01 int a = 7; 02 int b = 12; 03 int temperature = Math.max(a, b); 04 05 if (temperature > 10) 06 { temperature = 0; 07 } |
You may also get this error if you have tried to declare two variables of different types using the same variable name (in Java, every variable must have a unique name). The example below illustrates this using two variables of type int
and String
.
Example 2: Incorrect Code | Example 2: Fixed Code |
Here we are trying to declare two variables using the same variable name of |
We fix the problem by ensuring that each variable has a unique name. |
01 int temperature = 22; 02 String temperature = "Hot Outside"; |
01 int temperature = 22; 02 String tempDescription = "Hot Outside"; |
The only time where repetition of variable names or declarations are allowed is if the two variables are in different scopes. Recall that the scope of a variable is determined by the set of braces, { and }, in which it is enclosed. This is illustrated in the two examples below.
Example 3: Correct Code | Example 4: Correct Code |
This is allowed because the delarations on lines 4 and 7 are being done within different scopes. One is within the scope of the |
Similarly, this is also allowed because |
01 int temp = 22; 02 03 if (temp >= 20) 04 { String desc = "Hot"; 05 } 06 else if (temp >= 10 && temp < 20 ) 07 { String desc = "Nice"; 08 } |
01 public void cold() 02 { int temp = -27; 03 } 04 05 public void hot() 06 { int temp = 27; 07 } |
Variable not declared
This error occurs when a variable is not declared within the same (or an «outer») scope in which it is used. Recall that the scope of a variable declaration is determined by its location with { and } braces. The example below illustrates a simple case of this error. To fix this problem, make sure that the variable is declared either in the same scope in which it is being used, or it being delcared in an «outer» scope.
Example 1: Incorrect Code | Example 1: Fixed Code |
The variable |
To fix the problem, we declare |
01 boolean newAcct = true; 02 double deposit = 17.29; 03 04 if (newAcct == true) 05 { double balance = 100.0; 06 } 07 08 if (deposit > 0) 09 { balance += deposit; 10 } |
01 boolean newAcct = true; 02 double deposit = 17.29; 03 double balance = 0; 04 05 if (newAcct == true) 06 { balance = 100.0; 07 } 08 09 if (deposit > 0) 10 { balance += deposit; 11 } |
Return to Main Page
Created by Terry Anderson (tanderso at uwaterloo dot ca) for use by ISG, Spring 2005