我试图找出是否可以打印出一个int ONLY,如果它是一个数字数组中的值。 例如:
def openaudio(self,path):
self.connect(self.ui.listWidget,QtCore.SIGNAL('currentTextChanged(QString)'),self.ui.label_4,QtCore.SLOT('setText(QString)'))
index=self.ui.listWidget.currentRow()
path=mlist[index]
self.mediaObject.setCurrentSource(phonon.Phonon.MediaSource(path))
self.mediaObject.play()
我不确定的是你将在“if”之后放在括号中,以便系统打印“它在数组中”只有j在1到9之间。
谢谢!
答案 0 :(得分:5)
使用java.util.Arrays实用程序类。它可以将您的数组转换为允许您使用contains方法的列表,或者它具有二进制搜索,允许您查找数字的索引,如果数组不在数组中,则为-1。
import java.util.Arrays;
import java.util.Random;
public class arrays {
Random random = new Random();
public void method () {
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int j = random.nextInt(20);
if( Arrays.binarySearch(numbers, j) != -1 ) {
System.out.println("It is in the array.");
} else {
System.out.println("It is not in the array.");
}
}
}
答案 1 :(得分:4)
import java.util.Random;
public class arrays {
Random random = new Random();
public void method () {
Integer[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int j = random.nextInt(20);
if(Arrays.asList(numbers).contains(j)) {
System.out.println("It is in the array.");
} else {
System.out.println("It is not in the array.");
}
}
}
答案 2 :(得分:3)
Arrays.asList(numbers).contains(j)
或
ArrayUtils.contains( numbers, j )
答案 3 :(得分:1)
由于您的数组已排序,您可以使用Arrays.binarySearch返回array
中存在的元素索引,否则返回-1
。
if(Arrays.binarySearch(numbers,j) != -1){
system.out.println("It is in the array.");
} else {
system.out.println("It is not in the array.");
}
只是一种更快捷的搜索方式,您也不需要将array
转换为list
。