Reputation: 13854
I have the following code snippet where some strings are initialized in the if
block:
String serialmask = request.getParameter( "serialmask");
String serialincrement = request.getParameter( "serialincrement");
if (serialmask == "1") {
String tserialmask = "aaa########";
}
else {
String tserialmask = "";
}
if (serialincrement == "1") {
String tserialincrement = "aaa^^^^^^^^";
}
else {
String tserialincrement = "";
}
out.println(
itemimport(
partnumber,
itemcost,
itemlistprice,
itemdescription,
PurchProdLineKey,
UnitMeasKey,
itemclasskey,
trackmethod,
tserialmask,
tserialincrement
)
);
The error I'm getting is "cannot find symbol"
symbol : variable tserialmask
in the out.println(itemimport(....tserialmask,tserialincrement));
statement.
I tried declaring the variables outside of the if
block and this seems to bring on even more errors saying it's already been declared.
Upvotes: 0
Views: 6656
Reputation: 346387
You need to declare the variables tserialmask and tserialincrement outside the if branches and not try to redeclare them inside, like this:
String tserialmask;
if (serialmask == "1") {
tserialmask = "aaa########";
} else {
tserialmask = "";
}
Upvotes: 0
Reputation: 88806
You need to declare tserialmask and tserialincrement outside of the if/else blocks. Otherwise, they go out of scope when that block ends.
String serialmask = request.getParameter( "serialmask");
String serialincrement = request.getParameter( "serialincrement");
String tserialmask;
String tserialincrement;
if (serialmask == "1")
{
tserialmask = "aaa########";
}
else
{
tserialmask = "";
}
if (serialincrement == "1")
{
tserialincrement = "aaa^^^^^^^^";
}
else
{
tserialincrement = "";
}
out.println(itemimport(partnumber,itemcost,itemlistprice,itemdescription,PurchProdLineKey,UnitMeasKey,itemclasskey,trackmethod,tserialmask,tserialincrement));
Upvotes: 3
Reputation: 29139
You are declaring String variables within the if else statements then trying to access them outside the statements. You need to declare the variables before your if statements and then only assign them within the if/else statements.
Upvotes: 0
Reputation: 1502216
You need to declare the variable first, but then just assign it. Here's the version for tserialincrement
(the same is true for tserialmask
)
String tserialincrement;
if (serialincrement == "1")
{
tserialincrement = "aaa^^^^^^^^";
}
else
{
tserialincrement = "";
}
However, there are two things wrong with this:
equals
You can do it in one statement (per variable) with the conditional operator:
String tserialmask = "1".equals(serialmask) ? "aaa########" : "";
String tserialincrement = "1".equals(serialincrement) ? "aaa^^^^^^^^" : "";
In addition, I'd suggest nicer variable names, using Pascal casing (e.g. serialMask
) and something more useful than just "t" as a prefix. (What does that mean?)
Upvotes: 5