2015-11-06 120 views
-1

我有一个构造函数接受一个字符串,看起来像“南行 - Metrotown”。Java拆分字符串ArrayIndexOutOfBoundsException

它所带的字符串总是不同,但具有相同的格式:方向 - 位置。我正在使用split()方法在连字符处拆分此字符串(unicode 44)。

构造和返回的方法是这样的

String[] splt; 
String dirn; 
String plat; 

public Arrival(String platform) { 
    this.platform = platform; 
    splt = platform.split("-"); 
    dirn = splt[0]; 
    plat = splt[1]; 
} 
public String getTravelDirn() { 
    return dirn.trim(); 
} 
public String getPlatformName() { 
    return plat.trim(); 
} 

我可以打印出来的效果很好,但是当我用JUnit测试它,

@Before 
public void setUp() { 
    arr = new Arrival(platform); 
} 

@Test 
public void testArrivalGetPlatform() { 
    System.out.println(arr.getPlatformName()); 
    assertTrue(arr.getPlatform().equals("Metrotown")); 

结果打印出来铁道镇,但assertTrue线失败。我能做些什么来解决这个问题?感谢您的时间。

+0

尝试打印您传递给构造函数的参数。我怀疑它没有'-'或其'''是不是你在你的分裂中使用的字符。或者,也许这个错误与'plat = splt [1]'行没有关系;'但是对于你没有向我们显示的其他行。 – Pshemo

+0

也许'splt = platform.split(“ - ”);'doesnt split(does not have'splt [1]')? – Sekula1991

+0

尝试'for(String str:platform.split(“ - ”))'看看你会得到什么。什么是splt的类型? – 2015-11-06 23:46:22

回答

1

platform参数值没有破折号。

当没有进行拆分匹配时,整个字符串作为单个元素数组的第一个元素返回。试图访问索引0以外的任何元素都会导致该异常。

+1

只有当我们假设错误来自'plat = splt [1]'这行时,才会出现这种情况;'但是说实话,没有堆栈跟踪,我们无法确定这一点。 OP还有机会从源代码(如某个页面)读取一些不使用标准短划线“ - ”而是其他字符的数据,例如这两个短划线是不同的字符:代码为44和8211的' - -'。 – Pshemo

+0

更正:这些破折号8210和8211的索引。是我在代码中使用的',':) – Pshemo