【问题标题】:Using a variable to set an object array in java在java中使用变量设置对象数组
【发布时间】:2013-08-07 10:10:11
【问题描述】:

当我设置对象数组如:

Player[] player = new Player[amountOfPlayers];

我使用:

amountOfPlayers = br.read();

获取变量amountOfPlayers。每当我运行我的程序时,当被要求设置 amountOfPlayers 时我会输入 3,但我的输出显示有 51 个玩家。

虽然当我将新的Player 数组设置为:new Player[3];它有效。

有人知道为什么会这样吗?

【问题讨论】:

  • 您能否发布实际的完整代码,因为很难猜出这里发生了什么?
  • 你能解释一下吗?什么是播放器?

标签: java arrays object


【解决方案1】:

问题是您读取了char 并将其解释为整数。字符3 的ASCII 码为51

按照Prasad 的建议,使用Scanner 可能比BufferedReader 更容易读取输入。

【讨论】:

  • 感谢您的提及 :) 为我忘记提及的 ASCII 这个词点赞。
【解决方案2】:

使用它来读取输入而不是BufferedReader 扫描仪输入 = 新扫描仪(System.in); amountOfPlayers = in.nextInt();

这可能是因为br.read() 读取了51 的字符值3

使用 in.nextInt() 将确保将其转换为 int。

【讨论】:

    【解决方案3】:

    试试这个,

    Integer.parseInt(bufferedReader.readLine());
    

    【讨论】:

      猜你喜欢
      • 2020-08-10
      • 1970-01-01
      • 2013-03-06
      • 1970-01-01
      • 2017-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多