0

所以第一部分创建一个向量并将一个数字添加到 10 个插槽中。然后在这之后什么都没有发生,我的代码中没有错误,但它只是停止了..为什么?

package ovn7;    
import java.util.Scanner;
public class ovn7a {

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

        int []vektor = new int[10];

        for(int k=1; k<10; k++){
            vektor[k]=0+k;
            System.out.println(k);
        }
    }
    public int find(int tal) {

        System.out.println("tal");
        tal = scan.nextInt();
        int i = 0;
        while(i<10 && vektor[i] != tal) {
            i++;    
        }
        return (i <10) ? i : -1;
    }

}
4

1 回答 1

0

This is your main method:

public static void main(String []args) {
    int []vektor = new int[10];
    for(int k=1; k<10; k++){
        vektor[k]=0+k;
        System.out.println(k);
    }
}

That's all your program does - when it hits the closing right brace of the main method, execution ends. If you want it to execute public int find(int tal) as well, you need to include a method call to your main method:

int index = find(5); //for example

Remember, the main method is the only one that is called automatically when executing the program! You'll have to call find yourself inside main.

EDIT: per request, an example of main with the method call included:

public static void main(String []args) {
    int []vektor = new int[10];
    for(int k=1; k<10; k++){
        vektor[k]=0+k;
        System.out.println(k);
    }
    int index = find(5); // <-- this find(5) here is a method call for find!
    System.out.println("The method returned a value of " + index + ".");
}

You can replace that "5" with any integer, as the method find accepts an integer as an argument. (as a side note, it doesn't matter which integer you pass to find - it overwrites the argument with a new value anyway)

于 2013-10-30T22:39:41.397 回答