[英]In JAVA how to check for multiple number in two ArrayList
Trying to check if a number is binary or not - so User will type an integer & will validate if that is binary or not. 尝试检查数字是否为二进制-因此用户将键入一个整数,并将验证该数字是否为二进制。 My code is as below & it is always returning False so the if statement is not working - also tried to convert to string but getting the same result - Thanks
我的代码如下,它总是返回False,所以if语句不起作用-也试图转换为字符串但得到相同的结果-谢谢
public static void main(String[] args) {
int aa = 5101012;
ArrayList dd = new ArrayList();
while(aa>0){
dd.add(aa%10);
aa = aa/10;}
ArrayList dd1 = new ArrayList();
dd1.add(2);
dd1.add(3);
dd1.add(4);
dd1.add(5);
dd1.add(6);
dd1.add(7);
dd1.add(8);
dd1.add(9);
System.out.println(dd1.contains(dd));}}
***************************REGEX SHORT VERSION********************************************************* If you want to shorten your code you could use regex: ***************************正则表达式简短版本******************** ******************************************如果要缩短代码,可以使用正则表达式:
public static void main(String[] args) {
int aa = 10101;
String test = "" + aa;
System.out.println("" + !test.matches(".*[23456789].*"));
}
This will return true
for 10101
and false
for 5101012
. 对于
10101
,这将返回true
;对于5101012
将返回false
。
************************************LONG VERSION********************************************************* You should check each element individually if you want to see which digits are binary and which ones aren't: ****************************************长期版本************ **************************************************您应该检查每个元素如果要查看哪些数字是二进制数字,哪些不是,请单独查看:
public static void main(String[] args) {
int aa = 5101012;
ArrayList<Integer> dd = new ArrayList<Integer>();
while(aa>0){
dd.add(aa%10);
aa = aa/10;}
ArrayList<Integer> dd1 = new ArrayList<Integer>();
dd1.add(2);
dd1.add(3);
dd1.add(4);
dd1.add(5);
dd1.add(6);
dd1.add(7);
dd1.add(8);
dd1.add(9);
for(Integer a : dd)
{
System.out.println(dd1.contains(a));
}
}
You were trying to see if dd1 contains an arraylist of objects which it doesn't it contains objects( Integer
) individually. 您试图查看dd1是否包含对象的数组列表,而不是单独包含objects(
Integer
)。
One way (not the most elegant) is to convert it to string and then do: 一种方法(不是最优雅的方法)是将其转换为字符串,然后执行以下操作:
for (int i = 0; i < string.length(); i++) {
if ( string.charAt(i) != '1' && string.charAt(i) != '0') {
System.out.println("Not a binary number!");
break;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.