Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialVarun Singh
1,905 PointsWhy variable declaration is not allowed in ( boolean ) ?
Here i am trying to declare variable in boolean but compiler throws error. why? Code:
import java.io.Console;
public class TreeStory {
public static void main(String[] args) {
Console console = System.console();
/* Some terms:
noun - Person, place or thing
verb - An action
adjective - A description used to modify or describe a noun
Enter your amazing code here!
*/
int age = 10;
if(age <15)
boolean isFine= noun.equalsIgnoreCase("Dork") || noun.equalsIgnoreCase("Jerk") || noun.equalsIgnoreCase("Nerd");
{
console.printf("You should be atleast 15 year old !");
System.exit(0);
}
String name = console.readLine("Enter a name");
String adjective = console.readLine("Enter an adjective");
String verb = console.readLine("Enter a verb");
String noun = console.readLine("Enter a noun");
do
{
if (isFine)
{
console.printf(" This language is not allowed . Try again.\n");
}
} while(isFine);
String adverb = console.readLine("Enter an adverb");
}
}
2 Answers
andren
28,558 PointsIn this line:
boolean isFine= noun.equalsIgnoreCase("Dork") || noun.equalsIgnoreCase("Jerk") || noun.equalsIgnoreCase("Nerd");
You reference the noun
variable but that variable does not actually exist at that point, noun
is declared later in the method. You cannot reference a variable before it exists within a method.
If you move the above line so that it is below the line where you declare the noun
variable then you should not run into any issues.
Wannabe Engineer
9,186 PointsString name = console.readLine("Enter a name");
String adjective = console.readLine("Enter an adjective");
String verb = console.readLine("Enter a verb");
String noun = console.readLine("Enter a noun"); <---- You need to put this first, then your IF statement can access it.
Also, Your problem is in scopes. Your boolean is If statement Scope. It can't be used outside of your scope.
You need to put your boolean outside of the If statement scope if you want to use it in several If Statements or other kind of loops.
I recommend reading more about variable scopes. There are tons of resources on internet just google "Variable scopes in java".