我无法将(String-)值传递给另一个类的setter方法

时间:2017-01-04 20:10:14

标签: java attributes setter

我知道我还没有编写一个catch块。(原因?,但我认为这实际上不是问题;“Game”类的属性完全可以改变)

当我尝试在Player中调用setName方法时,我总是得到一个IOException(即使我在Player中将“name”设置为public并直接更改它。)

    public class game{



    protected static int amountPlayers;
    protected static Player[] playerList = new Player[amountPlayers];

public static void main (String[] args) throws IOException{
        //Scanner reader = new Scanner(System.in);
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
        String input;

        System.out.println("new round? (1 for yes; enter for no):");
        int boo = Integer.parseInt(br.readLine());

        if (boo == 1) {
          Rounds.setNew(true);
        } // end of if

        if (Rounds.getNew() == true) {
          //SavingManagement.createFile();                            
          System.out.println("# of players:");
          int amount = Integer.parseInt(br.readLine());
          setAmountPlayers(amount);
        } // end of if

        for (int i = 0; i < amountPlayers; i++) {
          System.out.println("Name player No. " + (i + 1) + ":");
          input = br.readLine();
          playerList[i].setName(input);      
        } // end of for
        }


    public class Player {


      protected static int score;     
      protected static String name = "";



      public static void setName(String input) {
        name = input;
      }
    }

3 个答案:

答案 0 :(得分:-1)

您是否需要将Player类作为公共内部类? 你需要制作得分和名字吗?

否则这应该有效:

public class game {

    protected static int amountPlayers;
    protected static Player[] playerList = new Player[amountPlayers];

    public static void main(String[] args) throws IOException {
        for (int i = 0; i < amountPlayers; i++) {
            playerList[i].setName("test");
        }
    }
}

class Player {
    private int score;
    private String name = "";

    public void setName(String input) {
        name = input;
    }
}

答案 1 :(得分:-1)

假设您在amountPlayers中提供有效大小,通过编写以下语句,您只是创建了Player数组而不是初始化它。

protected static int amountPlayers = 100;

/* This will just create the array */
protected static Player[] playerList = new Player[amountPlayers];

在使用setName()之前,您必须按如下方式初始化数组:

for(int x = 0; x < amountPlayers; x++) {
    playerList[x] = new Player();
}

或者你可以这样做:

/* Create a new object of class Player */
Player myPlayer = new Player();

/* Set Name */ 
myPlayer.setName(input); 

/* Assign it to your array */
playerList[i] = myPlayer;

答案 2 :(得分:-2)

PlayerList包含Player对象,所以当你像这样调用setName方法时:playerList[i].setName(input)它是通过类Player的实例,但该方法实际上是静态的,应该以这种方式被召唤:

Player.setName() 

虽然,你可以做的最好的事情是在类Player中添加一个构造函数,在数组playerList中添加新的Player对象,并在类中创建方法setName()和其他变量玩家非静态。