简体   繁体   English

为什么我试图在 main 内部调用的方法不起作用?

[英]Why does my method that I am trying to call to inside main not work?

minGap(array); is not being recognized.不被认可。 I don't know what I have done wrong, but I am sure it is a super simple fix.我不知道我做错了什么,但我确信这是一个超级简单的修复。 Trying to figure out if it is something to do with the data type being used or if it has something to do with the arrangement of the line " " added.试图弄清楚它是否与正在使用的数据类型有关,或者是否与添加的“ ”行的排列有关。 Any hints?任何提示?

package Lab8;
import java.util.*;
import java.util.Scanner;
public class Question_One {

    public static void main(String args[]) {

        int length;
        Scanner input = new Scanner(System.in); //scanner to input any size array user wants

        System.out.println("Please enter the numbers for the array.");
        length = input.nextInt();

        String[] array = new String[length];

        for(int i = 0;i <length;i++) { //counter logic
                System.out.println("How many integers are in the array?"+(i+1));
                array[i] = input.nextLine();
        }
        System.out.println("Enter the numbers for the array (individually):");
        for(int i = 0;i <length;i++) { //counter logic
            System.out.print(array [i]);
            array[i] = input.nextLine();

        }

        input.close();

        minGap(array);

    }

    private static int minGap(int a[], int gapMin) {
        int []gap = new int[a.length];

        //a
        for (int i=0;i<a.length-2;i++) {
            if (gapMin>gap[i]) {
                    gapMin=gap[1];
            }


        }

        return gapMin;


    }

}

I believe you wanted a method to find the minimum gap.我相信您想要一种找到最小差距的方法。 As such, you should not be passing that into the method.因此,您不应将其传递方法中。 Your logic is also a bit off, you want to take the minimum value after gapMin>gap[i] (not a hardcoded gap[1] ).你的逻辑也有点gapMin>gap[i] ,你想在gapMin>gap[i] (不是硬编码gap[1] )之后取最小值。 So you could do,所以你可以这样做,

private static int minGap(int a[]) {
    int gapMin = Integer.MAX_VALUE;
    int[] gap = new int[a.length];
    for (int i = 0; i < a.length; i++) {
        if (gapMin > gap[i]) {
            gapMin = gap[i];
        }
    }
    return gapMin;
}

or (if you're using Java 8+)(如果您使用的是 Java 8+)

private static int minGap(int a[]) {
    return Arrays.stream(a).min().getAsInt();
}

Then you need to actually save that value or print it.然后您需要实际保存该值或print它。 That is, change也就是说,改变

minGap(array);

to (just print it)到(只需打印)

System.out.println(minGap(array));

And you need an array of int (not a String[] ).并且您需要一个int数组(不是String[] )。

int[] array = new int[length];
for(int i = 0; i < length; i++) {
    System.out.printf("Please enter integer %d for the array%n", i + 1);
    array[i] = input.nextInt();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM