Java,怎么把数组中没有某个值作为if的判断条件?

比如数组是s[]={1,2,4,5,6,}里面没有3,作为if的判断条件,最好用遍历。
实际上数组是String类型的,该怎么做?

public class Test{
    public static void main(String[]args){
        int[] s= {1,2,4,5,6};
        int temp = -65535;
        for(int i = 0;i<s.length;i++){
            if(i != 0) {
                if(s[i] - temp != 1){
                    System.out.println((s[i]-1)+"不存在");
                }
            }
            temp = s[i];
        }
    }
}

代码如上。如果最后再添加一个8的话也可以判断出来7不在。

前提是这个数组是int类型并且已经升序排列好了。

如果是乱序的数组在判断之前加一句Arrays.sort(s);即可

另:如果是连续的不存在的数字的话(如 int s[]={1,4,5,6,9}这样的数组)判断更加复杂,这里的代码没有给出

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-10-08
String[] list={1,2,4,5,6,}

for (int i = 0; i < list.length; i++) {
if (“3”.contains(bidIdlist[i])) {
包含
}else{
不包含
}
}
第2个回答  2018-03-28
import java.util.Arrays;
import java.util.List;
//输入年份 月份,输出月份的天数
import java.util.Scanner;

public class Demo09 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Please enter the Year:");
int year=sc.nextInt();//变量year用来接收输入的年份
boolean JudgeYear=year%4==0 && year%100!=0 || year%400==0;
//判断是否是闰年 JudgeYear变量接收true或false
String str=JudgeYear?"is Leap year":"is Pingnian";
//变量str用来接收是闰年或是平年的字符串
System.out.println(str);
System.out.println("Please enter the Month:");
int Month=sc.nextInt();//变量Month接收输入的月份
Integer[] BigMonth={1,3,5,7,8,10,12};
//大月生成一个数组 用Integer是因为下一步int不能
List<Integer> a=Arrays.asList(BigMonth);//将数组转换成List
Integer[] SmallMonth= {4,6,9,11};//同大月
List<Integer> b=Arrays.asList(SmallMonth);//同大月
int Days=0;
if(a.contains(Month)) {
//contains方法来判断数组中是否有Month这个数值
Days=31;
}else if(b.contains(Month)) {
Days=30;
}else if(Month==2) {
if(JudgeYear==true) {
Days=29;
}else if(JudgeYear==false){
Days=28;
}
}
sc.close();
System.out.println(year+str+"\n"+Month+"Month:"+Days);
}
}

相似回答