我必须显示数组中是否存在给定数字。 例如:
int[] number1 = {2,3,6,14,23,8,23,19};
int[] numbers2 = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30};
现在我必须检查number1数组元素是否存在于number2数组中,如果是,则打印当前数字。 那么如何在Java中实现这一目标呢?
我的代码:
int[] number1 = {2,3,6,14,23,8,23,19};
int[] numbers2 = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30};
for(int i=0; i<number2.length;i++){
for(int j =0; j<number1.length:j++){
if(number2[i]==number1[j]){
System.out.println("present number is:"+number1[i]);
}
}
}
答案 0 :(得分:3)
嵌套for循环将帮助您实现这一目标,基本上对于number1
中的每个数字,您需要遍历numbers2
以查看该值是否存在。
for(int i: number1) {
for(int j: numbers2) {
if(i == j) {
System.out.println(i);
break; //exit the inner loop if the number is present
}
}
}
答案 1 :(得分:1)
这是基本想法
答案 2 :(得分:1)
更改i - &gt; j在System.out.println("present number is:"+number1[j]);
答案 3 :(得分:0)
使用Java 8时,它非常简洁。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Hover over one of the buttons, and you'll see none of the console messages gets logged. When removing the `disabled` property, all events are fired.</p>
<button id="button_1" disabled><span>Disabled 1</span></button>