Find the smallest element in an array. [closed]

2019-09-21 16:31发布

I think the problem lies with the invoking of the method or the braces, not 100% sure. When I call the method does it matter if it before or after the main method?

 public class varb
    {
    public static void main (String[] args)
    {   
    double[] array = new double [10]; 
    java.util.Scanner input = new java.util.Scanner(System.in); 
    System.out.println("Enter" + " " + array.length + " numbers");
    for (int c = 0;c<array.length;c++)
    {
    array[c] = input.nextDouble();
    }
    min(array);
    double min(double[] array)
    {
    int i;
    double min = array[0];
    for(i = 1; i < array.length; i++)
     {
    if(min > array[i])
      {
    min = array[i];
      }
     }
    return min;
      } 
     }
    }

2条回答
神经病院院长
2楼-- · 2019-09-21 17:14

The location of main does not matter, it can be placed anywhere in the class, generally convention is to place it as the first method or last method in the class.

You code has severe formatting problems, you should always use and IDE, like Eclipse to avoid such issues.
Fixed your code below:

public class Varb{
    public static void main(String[] args) {

        double[] array = new double[10];
        java.util.Scanner input = new java.util.Scanner(System.in);
        System.out.println("Enter" + " " + array.length + " numbers");
        for (int c = 0; c < array.length; c++) {
            array[c] = input.nextDouble();
        }
        min(array);
    }

    private static double min(double[] array) {
        double min = array[0];
        for (int i = 1; i < array.length; i++) {
            if (array[i] < min) {
                min = array[i];
            }
        }
        return min;
    }
}
查看更多
爷、活的狠高调
3楼-- · 2019-09-21 17:24

You cannot declare a method inside another one.

In your code you try to declare double min(double[] array) inside your main method.

查看更多
登录 后发表回答