2015-10-17 256 views
1

我必須用奇數的範圍(這裏是n)填充一個數組:1,3,5,7,9 ......但是每個奇數和我之間總是有一個0不明白爲什麼。用奇數填充數組

注:評論信件是由我們的教授給出的資本項目下的代碼...

下面是代碼:

public class F5B1 { 

    public static java.util.Scanner scanner = new java.util.Scanner(System.in); 

    public static void main(String[] args) { 

     // Creation of Array : DON'T CHANGE THIS PART OF THE PROGRAM. 
     System.out.print("Entrez n : "); 
     int n = scanner.nextInt(); 
     int[] t = new int[n]; 
     int i; 


     // fill the array : PART OF THE PROGRAM TO FULFILL 
     // INSTRUCTIONS : 
     // ADD NO ADDITIONAL VARIABLES 
     // DON'T USE ANY OF THE MATH METHODS 
     // DON'T ADD ANY METHODS 

     // I wrote this piece of code 
     for (i = 0; i < t.length; i++) { 
      if (i % 2 != 0) { 
       t[i] += i; 
      } 
     } 

     // display of the array : DON'T CHANGE THIS PART OF THE PROGRAM 

     System.out.println("Those are the odd numbers : "); 
     for (i = 0; i < t.length; i++) { 
      System.out.println(t[i]); 
     } 
    } 

} 

輸出:

Enter n : 10 
Those are the odd numbers : 
0 
1 
0 
3 
0 
5 
0 
7 
0 
9 
+0

您可以張貼輸出嗎? – dsharew

+0

是的,我當然會這樣做 – algorithmic

+0

你的教授通過讓你在for循環之外聲明'i'給你不好的建議 –

回答

2

對於每個偶數索引,您都得到0,因爲該索引處的值從不設置。

這條線:

int[] t = new int[n]; 

聲明長度n的INT,其中每個元素被初始化爲0的數組現在考慮您的代碼:

for (i = 0; i < t.length; i++) { 
    if (i % 2 != 0) { 
     t[i] += i; 
    } 
} 

你的意思是:當索引我的數組很奇怪,讓我們把它設置爲這個索引,否則,什麼都不做(並且保持0)。這解釋了你得到的結果。

你想要做的不是檢查數組的索引是否是奇數:你想爲數組的每個索引設置一個奇數值。考慮下面的代碼來代替:

for (i = 0; i < t.length; i++) { 
    t[i] = 2 * i + 1; 
} 

對於每個索引,這個陣列的值設置爲奇數(2n+1總是單數)。

(請注意,我寫=而不是+=:它給人的意圖更好,不依賴於一個事實,即陣列初始化爲0)

+0

非常感謝您的快速解答! :)我現在明白了我的錯誤 – algorithmic

0

試試這個相反:

int odd = 1; 
for (int i = 0; i < t.length; i++) { 
    t[i] = odd; 
    odd += 2; 
} 

問題是這樣的:

int[] t = new int[n]; 

將創建一個填充零的數組。在你的for循環中,你設置了奇數,所以其他的都保持爲零。

+0

感謝你的幫助! – algorithmic

2

使用Java 8,IntStream很簡單:

IntStream.range(0, n).filter(element -> element % 2 != 0) 
        .forEach(System.out::println); 

用法:

public class F5B1 { 

    public static java.util.Scanner scanner = new java.util.Scanner(System.in); 

    public static void main(String[] args) { 
     System.out.print("Entrez n : "); 
     int n = scanner.nextInt(); 
     IntStream.range(0, n).filter(element -> element % 2 != 0) 
       .forEach(System.out::println); 
    } 
} 
+0

謝謝,我學到了一些新東西! ,我從來沒有聽說過那 – algorithmic

+0

問題是,答案重寫教授代碼的一部分。 – Tunaki