【问题标题】:Java error when I try to create an object with a constructor with a string parameter [closed]当我尝试使用带有字符串参数的构造函数创建对象时出现 Java 错误 [关闭]
【发布时间】:2020-03-03 06:22:29
【问题描述】:

我在 Move 类中创建了两个构造函数,一个带有两个 int 参数,一个带有 String 参数:

public Move(int row,int col)
{
  int[] [] Move = new int[row][col]; 
}   
public Move(String r)
{       
 String move = new String(r);    
}

然后我尝试制作一个对象:

Move m = new Move(1,1);
m = new Move("E1");
  //The second one does not work and I get this as an error in java:

  Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:47)
at java.base/java.lang.String.charAt(String.java:693)
at Move.<init>(Move.java:16)
at moveTester.main(moveTester.java:10)

如何解决,谢谢!

【问题讨论】:

  • 您的堆栈跟踪与您的声明不一致。请提供minimal reproducible example 并解释您认为不应发生异常的原因。
  • 另请注意:您显示的代码是无意义的。您将值分配给两个局部变量。这些变量仅存在于该构造函数的主体中。当构造函数执行完毕后,这些局部变量将消失,其他代码无法再访问它们。在一个名为 Move 的类中命名变量 move 和 Move 也是一个非常奇怪的想法。对变量使用小写,并给它们起独特的有意义的名字!
  • 我必须尊重 UML 和 Move 类的名称,这不是我的整个文件
  • 公共类移动 { 私有 int 行;私人int col; //构造函数 public Move(int row,int col) { this.row(); this.col(); int[] [] 移动 = 新 int[row][col]; } 公共移动(字符串 r){ 字符串移动 = r; } public int row() { 返回行; } public int col() { return col; } }
  • @mpl 在您的问题正文中发布,主要在哪里?

标签: java string object indexing constructor


【解决方案1】:

你已经有了String参数,可以直接使用,不需要新建,见:

public Move(String r)
{       
 String move = r;    
}

但是,move 将只是一个局部变量,您可能想要一些不同的东西,但这是另一个步骤,您需要在此之后执行。

【讨论】:

    猜你喜欢
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 2019-07-28
    • 2018-06-25
    • 2021-03-05
    • 2020-04-14
    • 2020-10-27
    • 1970-01-01
    相关资源
    最近更新 更多