如何测试数组中的位置是否存在

时间:2015-04-29 01:50:01

标签: java arrays

我正在尝试测试char [i]是否存在。 例如:

char[] c = {'h', 'e', 'l', 'l', 'o'};

存在位置0 - 4,但以下结果导致错误:

System.out.println(c[5]);

基本上,如果c [i]存在,我如何返回一个为true的布尔值,如果不存在则返回false?

6 个答案:

答案 0 :(得分:4)

尝试

int i = 5;
boolean exists = c.length >= i - 1;

由于char无法保存null值,因此不存在不存在的字符。

答案 1 :(得分:1)

boolean fun(char[] c, int i){
If(i < c.length)
return true;
else
return false;}

答案 2 :(得分:0)

我目前在手机上,所以我没有发布任何代码,但你可以有一个方法,你传递一个数组和一个索引,使用try-catch子句返回一个基于布尔值是否抛出异常。

答案 3 :(得分:0)

您可能希望抛出ArrayIndexOutOfBoundsException来抓住c[i]是否存在。我希望,你也可以参考这个website

答案 4 :(得分:0)

你可以做这样的事情

public boolean isElementExist(Object[] arr, int index){
      if(index < 0)
           return false;
      return arr.length - index > 0
}

答案 5 :(得分:0)

char[] c = {'h','e','l','l','o'};
    int input = Integer.parseInt(JOptionPane.showInputDialog(null,"Please enter an index you want to display"));
    int i =  c.length-1;

    if(input > i ){

        System.out.print("The index: "+input+" does not exist\n there are only "+ i+" in the array \n");       
    }
    else System.out.print("The char at index "+input+" is: "+c[input]+"\n");         
}
  

试试这个。