将数组元素与整数进行比较

时间:2016-10-27 15:24:35

标签: java arrays

这是我的任务: 创建一个N个随机整数的数组,范围为1到100(您可以使用Java随机类)。从用户获取N的值。接下来要求用户输入此范围内的数字(1到100),然后搜索数组以查找所有出现的搜索编号。对于每次出现,打印出数字和找到它的位置。 然后对数组进行排序并再次搜索,显示所有出现的搜索编号。如果未找到搜索号,则显示相应的消息。

最后,打印数组中所有数字的总和。

我无法弄清楚如何将数组元素与整数进行比较。请帮忙!这是我到目前为止所拥有的

public class Array {

public static void main(String[] args) 
{
    int num;
    int searchNum;
    int position = 0;
    Scanner in= new Scanner(System.in);
    System.out.println("How many random integers you want to create in range (1, 100)");
    num = in.nextInt();
    int[] myList = new int[num];
    for (int i = 0; i < num; i++)
    {
        Random r = new Random();
        int j = r.nextInt(101);
        myList[i] = j;
    }

    System.out.println("Enter a number from 1-100 to search");
    searchNum = in.nextInt();
    for (int i = 0; i < num; i++)
    {
        if (searchNum == myList[i])
        {
            System.out.println(searchNum + " found at location: " + (position+1));
        }
        else 
        {
            position += 1;
        }
    }
}
}

2 个答案:

答案 0 :(得分:0)

System.out.println("Enter a number from 1-100 to search");
searchNum = in.nextInt();
for (int i = 0; i < num; i++)
    if (searchNum == myList[i])
        System.out.println(searchNum + " found at location: " + (i+1));

答案 1 :(得分:0)

我相信你差不多完成了。

public class Array {

public static void main(String[] args) 
{
    Scanner in = new Scanner(System.in);

    System.out.println("How many random integers you want to create in range (1, 100)");
    final int num = in.nextInt();

    int[] myList = new int[num];
    Random r = new Random();
    for (int i = 0; i < num; i++)
    {
        myList[i] = r.nextInt(101);
    }

    System.out.println("Enter a number from 1-100 to search");

    final int searchNum = in.nextInt();
    for (int i = 0; i < num; i++)
    {
        if (searchNum == myList[i])
        {
            System.out.println(searchNum + " found at location: " + i);
        }
    }

    Arrays.sort(myList);

    boolean any = false;

    for (int i = 0; i < num; i++)
    {
        if (searchNum == myList[i])
        {
            System.out.println(searchNum + " found ");
            any = true;
        }
        else if (searchNum > myList[i])
        {
            break;
        }       
    }

    if (!any)
    {
        System.out.println("the search number is not found");
    }
}
}