簡體   English   中英

使用變量在Java中設置對象數組

[英]Using a variable to set an object array in java

當我設置一個對象數組如:

Player[] player = new Player[amountOfPlayers];

我用:

amountOfPlayers = br.read();

要獲取變量amountOfPlayers 每當我運行程序時,當系統amountOfPlayers我設置amountOfPlayers時,我都會輸入3,但我的輸出顯示有51位玩家。

但是,當我將new Player數組設置為: new Player[3] 有用。

有人知道為什么會這樣嗎?

問題是您讀取了一個char並將其解釋為整數。 字符3具有ASCII碼51

正如Prasad建議的那樣,使用Scanner可能比BufferedReader讀取輸入要容易。

用它來讀取輸入,而不是BufferedReader Scanner in = new Scanner(System.in); amountOfPlayers = in.nextInt();

這可能是因為br.read()讀取字符值whichis 513

使用in.nextInt()將確保將其轉換為int。

嘗試這個,

Integer.parseInt(bufferedReader.readLine());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM