如何获得没有设置长度的数组的特定组件?

时间:2018-02-20 12:37:08

标签: java arrays eclipse input keyboard

我尝试做的是从用户那里获取一组数字,控制台将打印出英语中第二高的数字和西班牙语中的第二低数字。

首先,我尝试从用户那里获取输入,将其放入数组并获取组件的第二高和第二低值。但我无法弄清楚如何抓住我需要的东西。

public static void main(String[] args) {

    //get the length from user
    int length;
    Scanner input = new Scanner(System.in);

    System.out.println("How many variables are you going to enter?: ");

    length = input.nextInt();

    //allocate array for that length

    int[] variables = new int[length];

    for(int counter = 0; counter < length; counter++) {
        System.out.println("Enter variable: ");
        variables[counter] = input.nextInt();


    }

    input.close();

    //print the variables
    System.out.println("Your variables are");
    for(int counter = 0; counter < length; counter++) {
        System.out.println(variables[counter]);
    }


}

2 个答案:

答案 0 :(得分:1)

    System.out.println("------------------");
    Arrays.sort(variables);    //sort array
    System.out.println(variables[1]);   //2nd lowest value
    System.out.println(variables[variables.length-2]);  //2nd highest value 

试试这个兄弟

将此添加到您的代码

答案 1 :(得分:0)

class Demo
{
    public static void findNum(int arr[]){
        int largest = arr[0], second_largest = arr[0];
        int minimum = are[0], second_minimum = are[0];
        for(int i=0;i<arr.length;i++){
            if(arr[i] >= largest){
                second_largest = largest;
                largest = arr[i];
            }
            else if(arr[i]>second_largest){
                second_largest = arr[i];
            }
            if(arr[i] <= minimum){
                second_minimum = minimum;
                minimum = arr[i];
            }
            else if(arr[i]<second_minimum){
                second_minimum = arr[i];
            }

        }
        System.out.println("Second Largest = " + second_largest + " Second_minimum = "+second_minimum);
    }
    public static void main (String[] args) throws java.lang.Exception
    {
        int arr[] = {5,3,2,1,8,77};
        findNum(arr);
    }
}

如果您特别关注不对原始数组进行排序,则可以执行此类操作。