代码在Java中永远“运行”

时间:2015-08-18 17:24:58

标签: java

我是Java的新手,我发现解决问题很困难。基本上代码得到一个数字,并在函数 generateVector 中生成一个向量。当我运行此代码时,我被要求输入一个数字,然后软件将永远运行。如果可能的话,你能帮助我没有其他类似先进的功能吗?我仍在学习。感谢。

import java.util.Scanner;

public class Atividade02 {
    static Scanner dados = new Scanner(System.in);
    static int n;

    //Main
    public static void main(String args[]){
        System.out.println("Type a number: ");
        n = dados.nextInt();
        int[] VetorA = generateVector(n);

        for(int i=0; i<VetorA.length; i++){
            System.out.println("Position: "+ VetorA[i]);
        }
    }

    //Função
    public static int[] generateVector(int n){
        int[] VetorA = new int [n];
        for (int i=0; i<n; i++){
        VetorA[i] = dados.nextInt();
        }
        return VetorA;
    }
}         

2 个答案:

答案 0 :(得分:3)

  

我被要求输入一个号码然后软件永远保持运行。

您输入n所需的generateVector号码了吗?该程序可能仅在用户输入时被阻止。

答案 1 :(得分:0)

尝试按如下方式修改类:

import java.util.Scanner;

public class Atividade02 {
    // Added private access modifiers for properties.
    // It's not necessary here, but as a general rule, try to not allow direct access to 
    // class properties when possible.
    // Use accessor methods instead, it's a good habit
    private static Scanner dados = new Scanner(System.in);
    private static int n = 0;

    // Main
    public static void main(String args[]){

        // Ask for vector size
        System.out.print("Define vector size: ");
        n = dados.nextInt();

        // Make some space
        System.out.println(); 

        // Changed the method signature, since n it's declared 
        // as a class (static) property it is visible in every method of this class
        int[] vetorA = generateVector();

        // Make some other space
        System.out.println(); 

        // Show results
        for (int i = 0; i < vetorA.length; i++){
            System.out.println("Number "+ vetorA[i] +" has Position: "+ i);
        }
    }

    // The method is intended for internal use 
    // So you can keep this private too.
    private static int[] generateVector(){
        int[] vetorA = new int[n];

        for (int i = 0; i < n; i++) {
            System.out.print("Insert a number into the vector: ");
            vetorA[i] = dados.nextInt();
        }

        return vetorA;
    }
}

此外,当命名变量符合 Java 命名约定时,只有类以大写字母开头。