1

所以,我有一些相当简单的代码,但是在第二类中,两个方法都找不到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;
    }
 }

有谁知道我做错了什么?

4

2 回答 2

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) ...
于 2012-11-05T15:03:46.447 回答
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();
  }
于 2012-11-05T15:06:34.597 回答