2015-08-18 103 views
0

我在Java中很新,我發現在解決問題時遇到困難。基本上代碼得到一個數字,並在函數generateVector中生成一個向量。當我運行這個代碼時,我被要求輸入一個數字,然後軟件永遠運行。如果可能的話,你們能否幫助我,而不需要其他先進的功能?我仍在學習。謝謝。在Java中永遠的代碼'運行'

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; 
    } 
}   
+0

你是否填充了矢量?如果我使用像「3 1 2 3」這樣的數據,它似乎對我很好。 – Pshemo

+0

您的generateVector方法正在其for循環的每次迭代中等待更多輸入 – BoDidely

+0

我建議您嘗試調試代碼,並且您可能會發現它的行爲正確。 –

回答

3

我要求把一個號碼,然後軟件相依相偎運行。

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

0

嘗試modfiy類如下:

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

+0

嘿,謝謝你的回答。在這種情況下,您刪除了** for **語句,該語句負責將向量A加載到位置n。用你給我看的代碼,我只會得到向量結果的0。謝謝。 – user2852724

+0

我的歉意,昨天我的大腦是香蕉。我修改了答案。希望我這次得到你了:) – DevJimbo