如果它是数组中的值,是否可以打印数字? (JAVA)

时间:2015-07-26 17:08:28

标签: java arrays

我试图找出是否可以打印出一个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之间。

谢谢!

4 个答案:

答案 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