2011-12-08 70 views
0

在此先感謝。當我爲這個數組輸入一個最小值時,我無法弄清楚爲什麼我的代碼會給我帶來麻煩。它似乎保留最初的0值,但我不知道如何解決這個問題。 Max工作正常。我是否在程序的錯誤部分設置了最大值和最小值?另外,這是我對數組的第一次任務,所以我可能在稍後打印下標時遇到一些問題。數組返回0的最小值(目標是查找最大值和最小值)

再次感謝!

編輯 - 這就解決了這個問題,據我所知。感謝丹W.

for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) { 
     System.out.print("Enter a new number. This will continue until " 
       + "you reach the size of the array. "); 
     arrayOfNumbers[i] = keyboard.nextInt(); 
    } 
      int max = arrayOfNumbers[0]; 
      int min = arrayOfNumbers[0]; 

package program8; 

import java.util.Scanner; 

public class arrayPrint { 

    public static void main(String[] args) { 
     final int NUMBER_OF_ELEMENTS; 
     Scanner keyboard = new Scanner(System.in); 
     System.out.print("Enter the amount of numbers the array will read in. "); 
     NUMBER_OF_ELEMENTS = keyboard.nextInt(); 
       int arrayOfNumbers[] = new int[NUMBER_OF_ELEMENTS]; 
       int max = arrayOfNumbers[0]; 
       int min = arrayOfNumbers[0]; 
     for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) { 
      System.out.print("Enter a new number. This will continue until " 
        + "you reach the size of the array. "); 
      arrayOfNumbers[i] = keyboard.nextInt(); 
     } 
     for (int i = 0; i < arrayOfNumbers.length; i++) { 
      if (max <= arrayOfNumbers[i]) 
       max = arrayOfNumbers[i]; 
     } 
     for (int i = 0; i < arrayOfNumbers.length; i++) { 
      if (min >= arrayOfNumbers[i]) 
       min = arrayOfNumbers[i]; 
     } 
       System.out.print(+max+ "max and " +min+ " min"); 
     } 


} 

回答

1

什麼樣的價值觀,你輸入?因爲一個int有一個默認值0:here 所以,如果你只輸入正數,最小將始終爲0

爲了避免這種情況,以後你有用戶輸入的數字初始化最小和最大,那麼最大和最小值不會默認爲0.

+0

像上面那樣? (我不知道如何在評論中放置代碼,但它沒有看起來很糟糕,所以它在編輯中,在原始代碼之上。我是這樣工作的。我之前已經嘗試過,但它沒有工作,因爲我在它之內第一個for循環的括號,謝謝!看起來是否正確? – user1082706

+0

是的,我當時只輸入正數,謝謝 – user1082706

+0

是的,這看起來不錯,希望它可以工作,請接受答案,如果這解決了您的問題 –