所以,我有一些相当简单的代码,但在第二类中,两种方法都找不到name
。这是一个简单的范围问题吗?
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!");
}
}
这个叫这个班级:
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;
}
}
有谁知道我做错了什么?
答案 0 :(得分:2)
您应该在name
方法中将gameStart
作为局部变量,并将其作为参数传递给nameTest
,如下所示:
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
此外,您要将false
分配给if
语句中的变量。这是允许的,但它没有做你想要的。您应该使用==
或(更好)使用!
来否定变量:
while (!playerNameLike) ...
答案 1 :(得分:0)
使用==
在条件中进行比较:
while (playerNameLike == false)
或者只是将它的否定视为一个布尔类型:
while (!playerNameLike)
另外,将Scanner
实例化移到while
循环之外:
Scanner gameStart = new Scanner(System.in);
while (!playerNameLike)
{
System.out.println("So, whats your name?");
name = (gameStart.next());
nameTest();
}