簡體   English   中英

Java中的代碼“永遠運行”

[英]Code 'running' forever in 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;
    }
}         

我被要求輸入一個數字,然后軟件將永遠運行。

您是否輸入了generateVector所需的n數字? 該程序可能只是在用戶輸入時被阻止。

嘗試如下修改類:

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命名約定時,只有類以大寫字母開頭。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM