Reputation: 528
So, I have some fairly simple code, but in the second class, neither method can find name
. Is this a simple issue of scope?
package rpg;
import java.util.Scanner;
public class Start {
static String name;
public static void main (String args[])
{
Engine test12 = new Engine();
name = test12.gameStart();
System.out.println("So, " + name + " it is!");
}
}
Which calls this class:
package rpg;
import java.util.Scanner;
public class Engine {
static boolean playerNameLike = false;
String name = (" ");
public String gameStart()
{
while (playerNameLike = false)
{
System.out.println("So, whats your name?");
Scanner gameStart = new Scanner(System.in);
name = (gameStart.next());
nameTest();
}
return name;
}
public boolean nameTest()
{
System.out.println("Does " + name + " sound good?");
System.out.println("(Y)es or (N)o?");
Scanner gameStart = new Scanner(System.in);
String yesNo = new String (gameStart.next());
if (yesNo.equals("Y"))
{
playerNameLike = true;
return playerNameLike;
}
if (yesNo.equals("N"))
{
playerNameLike = false;
return playerNameLike;
}
return playerNameLike;
}
}
Does anyone know what I'm doing wrong?
Upvotes: 1
Views: 2447
Reputation: 727047
You should make name
a local variable in the gameStart
method, and pass it to nameTest
as a parameter, like this:
public String gameStart()
{
String name = "";
boolean playerNameLike = false;
while (!playerNameLike)
{
System.out.println("So, whats your name?");
Scanner gameStart = new Scanner(System.in);
name = (gameStart.next());
playerNameLike = nameTest(name);
}
return name;
}
public boolean nameTest(String name) // Use your current code from here on
Also, you are assigning false
to the variable in the if
statement. This is allowed, but it does not do what you want. You should either use ==
, or (better) use !
to negate the variable:
while (!playerNameLike) ...
Upvotes: 2
Reputation: 34387
Use ==
to compare in the condition as:
while (playerNameLike == false)
or just check the negation of it as its a boolean type:
while (!playerNameLike)
Also, move the Scanner
instantiation outside the while
loop as:
Scanner gameStart = new Scanner(System.in);
while (!playerNameLike)
{
System.out.println("So, whats your name?");
name = (gameStart.next());
nameTest();
}
Upvotes: 0