有没有办法将outofbound错误默认为0?

时间:2016-10-29 20:03:54

标签: java

例如,如果您有一个大小为5的字符串,并且您执行了类似string.atChar(7)的操作,那么您是否可以将其设置为0而不是将其作为错误返回?

2 个答案:

答案 0 :(得分:1)

(我假设你的意思是charAt())

您可以创建自己的charAt()方法并将其放在字符串实用程序类中:

pulbic class MyStringUtility {
    public static char charAt(String string, int index) {
      if (index >= string.length) index = 0;

      return string.charAt(index);
    }
}

然后只需致电MyStringUtility.charAt(string, 7)

答案 1 :(得分:0)

假设您的意思是charAt(),请在try catch代码周围添加charAt(7)块。在catch块中,为您的方法返回0。

try {
  string.charAt(7);
} catch (IndexOutOfBoundsException e){
  return 0;
}

那应该有用。 :)